From c6b124bb31b5bc5db0142f3152e4a2ecd2dd2637 Mon Sep 17 00:00:00 2001 From: Abhinav Date: Wed, 8 Jul 2026 13:22:10 -0700 Subject: [PATCH 01/11] [codex] Grant Windows sandbox access to primary runtime (#31574) ## Why Codex Desktop installs its managed primary runtime under `%USERPROFILE%\.cache\codex-runtimes`. Elevated Windows sandbox commands run as dedicated sandbox users. The synchronous runtime ACL refresh repairs read/execute access for the Desktop runtime directories under `%LOCALAPPDATA%\OpenAI\Codex`, but did not include the managed primary runtime cache. As a result, the Desktop app could discover a bundled runtime while a sandboxed command received `ACCESS_DENIED` when reading or executing it. ## What changed - Include `%USERPROFILE%\.cache\codex-runtimes` in the managed runtime paths considered by the Windows sandbox ACL refresh. - Reuse the existing inherited read/execute ACL repair; no write permission is added. - Add Windows-target regression coverage for the runtime path list and the primary-runtime-only case. ## Impact Bundled Python, Node, and native tools remain usable from elevated Windows sandbox sessions without broadening write access or granting access to the rest of the user profile. ## Validation - `just fmt` - `just test -p codex-windows-sandbox` (10/10 host-side tests passed) - Windows-target path tests included for CI --- .../bin/setup_main/win/setup_runtime_bin.rs | 30 ++++++++++++++----- .../setup_main/win/setup_runtime_bin_tests.rs | 28 +++++++++++++++++ 2 files changed, 51 insertions(+), 7 deletions(-) create mode 100644 codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs index 509670e36b..8b0498d756 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs +++ b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin.rs @@ -10,20 +10,22 @@ use windows_sys::Win32::Security::OBJECT_INHERIT_ACE; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ; +#[cfg(test)] +#[path = "setup_runtime_bin_tests.rs"] +mod tests; + pub(super) fn ensure_codex_app_runtime_paths_readable( sandbox_group_psid: *mut c_void, refresh_errors: &mut Vec, log: &mut dyn Write, ) -> Result<()> { - let local_app_data = local_app_data_root(); - let Some(local_app_data) = local_app_data else { - return Ok(()); - }; - let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE; - let codex_root = local_app_data.join("OpenAI").join("Codex"); + let runtime_paths = runtime_paths( + local_app_data_root(), + std::env::var_os("USERPROFILE").map(PathBuf::from), + ); - for runtime_path in [codex_root.join("bin"), codex_root.join("runtimes")] { + for runtime_path in runtime_paths { if !runtime_path.is_dir() { continue; } @@ -86,6 +88,20 @@ pub(super) fn ensure_codex_app_runtime_paths_readable( Ok(()) } +fn runtime_paths(local_app_data: Option, user_profile: Option) -> Vec { + let mut runtime_paths = Vec::new(); + if let Some(local_app_data) = local_app_data { + let codex_root = local_app_data.join("OpenAI").join("Codex"); + runtime_paths.extend([codex_root.join("bin"), codex_root.join("runtimes")]); + } + // The managed primary runtime is installed outside the LocalAppData runtime roots. + if let Some(user_profile) = user_profile { + runtime_paths.push(user_profile.join(".cache").join("codex-runtimes")); + } + + runtime_paths +} + fn local_app_data_root() -> Option { std::env::var_os("LOCALAPPDATA") .map(PathBuf::from) diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs new file mode 100644 index 0000000000..a3fa300d0b --- /dev/null +++ b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win/setup_runtime_bin_tests.rs @@ -0,0 +1,28 @@ +use super::runtime_paths; +use pretty_assertions::assert_eq; +use std::path::PathBuf; + +#[test] +fn runtime_paths_include_desktop_and_primary_runtime_roots() { + let local_app_data = PathBuf::from(r"C:\Users\user\AppData\Local"); + let user_profile = PathBuf::from(r"C:\Users\user"); + + assert_eq!( + runtime_paths(Some(local_app_data), Some(user_profile)), + vec![ + PathBuf::from(r"C:\Users\user\AppData\Local\OpenAI\Codex\bin"), + PathBuf::from(r"C:\Users\user\AppData\Local\OpenAI\Codex\runtimes"), + PathBuf::from(r"C:\Users\user\.cache\codex-runtimes"), + ] + ); +} + +#[test] +fn primary_runtime_path_does_not_depend_on_local_app_data() { + let user_profile = PathBuf::from(r"C:\Users\user"); + + assert_eq!( + runtime_paths(/*local_app_data*/ None, Some(user_profile)), + vec![PathBuf::from(r"C:\Users\user\.cache\codex-runtimes")] + ); +} From bdaad6820cd884ea11787477f4c495e4de0a8be5 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Wed, 8 Jul 2026 13:35:31 -0700 Subject: [PATCH 02/11] Reuse MCP tool snapshot within a sampling request (#31292) Follow-up to #30226. ## Why #30226 makes Apps World State inspect the MCP tool list, while tool-router construction reads the same list again later in the sampling request. `list_all_tools()` walks the MCP clients and may reconnect or wait for tools, so doing that work twice adds latency and lets context and tool construction observe different MCP states for one request. ## What - Add a lazy MCP tool snapshot to `StepContext`. - Reuse that snapshot for Apps World State and tool-router construction. - Let each new `StepContext` refresh naturally for the next sampling request, without manager-level caching or invalidation. ## Testing - `just test -p codex-core apps_instructions` - `just test -p codex-core apps_guidance_appears_after_background_recovery_within_a_turn` --- codex-rs/core/src/session/step_context.rs | 11 +++++++++++ codex-rs/core/src/session/turn.rs | 8 ++++---- codex-rs/core/src/session/world_state.rs | 4 ++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/codex-rs/core/src/session/step_context.rs b/codex-rs/core/src/session/step_context.rs index 3210eb0286..1d7316d914 100644 --- a/codex-rs/core/src/session/step_context.rs +++ b/codex-rs/core/src/session/step_context.rs @@ -5,6 +5,8 @@ use crate::environment_selection::TurnEnvironmentSnapshot; use crate::session::McpRuntimeSnapshot; use crate::session::turn_context::TurnContext; use codex_exec_server::ResolvedSelectedCapabilityRoot; +use codex_mcp::ToolInfo; +use tokio::sync::OnceCell; /// Request-scoped state that may change between model sampling requests. #[derive(Debug)] @@ -15,6 +17,8 @@ pub(crate) struct StepContext { pub(crate) selected_capability_roots: Vec, /// The exact MCP config and manager used to advertise and execute tools for this step. pub(crate) mcp: Arc, + /// The fixed MCP tool list used for this exact sampling request. + mcp_tool_snapshot: OnceCell>, /// The canonical AGENTS.md value observed with this environment snapshot. pub(crate) loaded_agents_md: Option>, } @@ -32,7 +36,14 @@ impl StepContext { environments, selected_capability_roots, mcp, + mcp_tool_snapshot: OnceCell::new(), loaded_agents_md, } } + + pub(crate) async fn mcp_tools(&self) -> &[ToolInfo] { + self.mcp_tool_snapshot + .get_or_init(|| self.mcp.manager().list_all_tools()) + .await + } } diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index e231f6af86..6ee3ac2863 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -1222,8 +1222,8 @@ pub(crate) async fn built_tools( let turn_context = step_context.turn.as_ref(); let mcp_connection_manager = step_context.mcp.manager(); let has_mcp_servers = mcp_connection_manager.has_servers(); - let all_mcp_tools = mcp_connection_manager - .list_all_tools() + let all_mcp_tools = step_context + .mcp_tools() .or_cancel(cancellation_token) .await?; let loaded_plugins = sess @@ -1236,7 +1236,7 @@ pub(crate) async fn built_tools( let apps_enabled = turn_context.apps_enabled(); let accessible_connectors = - apps_enabled.then(|| connectors::accessible_connectors_from_mcp_tools(&all_mcp_tools)); + apps_enabled.then(|| connectors::accessible_connectors_from_mcp_tools(all_mcp_tools)); let accessible_connectors_with_enabled_state = accessible_connectors.as_ref().map(|connectors| { connectors::with_app_enabled_state(connectors.clone(), &turn_context.config) @@ -1329,7 +1329,7 @@ pub(crate) async fn built_tools( .await }; let mcp_tool_exposure = build_mcp_tool_exposure( - &all_mcp_tools, + all_mcp_tools, connectors.as_deref(), &turn_context.config, search_tool_enabled(turn_context), diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs index a0d93cac83..c7743c3fe1 100644 --- a/codex-rs/core/src/session/world_state.rs +++ b/codex-rs/core/src/session/world_state.rs @@ -41,9 +41,9 @@ impl Session { } let apps_available = if turn_context.config.include_apps_instructions && turn_context.apps_enabled() { - let tools = step_context.mcp.manager().list_all_tools().await; + let tools = step_context.mcp_tools().await; connectors::with_app_enabled_state( - connectors::accessible_connectors_from_mcp_tools(&tools), + connectors::accessible_connectors_from_mcp_tools(tools), &turn_context.config, ) .into_iter() From ba5dd1fd3acd8802325945b88219e69e8b744c40 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Wed, 8 Jul 2026 13:42:06 -0700 Subject: [PATCH 03/11] feat(core): emit canonical hook prompt items (#31630) ## Description This PR moves hook prompts onto the canonical `TurnItem` lifecycle in core. Stop hooks now record their `ResponseItem` through the existing lifecycle path, which emits `ItemStarted` and `ItemCompleted`. App-server consumes those events directly instead of deriving a hook prompt from `RawResponseItem`. ## Why Hook prompts were the only `ThreadItem` app-server synthesized from `RawResponseItem`. This brings them in line with other core-owned turn items while preserving legacy rollout replay. ## What changed - Route stop-hook prompts through `record_response_item_and_emit_turn_item`. - Materialize canonical hook prompts in `ThreadHistoryBuilder`. - Remove `RawResponseItem` to `ThreadItem` synthesis while preserving legacy rollout replay. - Add focused coverage for lifecycle emission and canonical and legacy history materialization. --- .../src/protocol/thread_history.rs | 33 +++++- .../app-server/src/bespoke_event_handling.rs | 100 ------------------ codex-rs/app-server/src/request_processors.rs | 1 - .../request_processors/thread_lifecycle.rs | 16 +-- codex-rs/core/src/session/tests.rs | 40 +++++++ codex-rs/core/src/session/turn.rs | 4 +- 6 files changed, 77 insertions(+), 117 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index 9f7ffa4447..ca8487b792 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -600,6 +600,7 @@ impl ThreadHistoryBuilder { let should_upsert = match item { codex_protocol::items::TurnItem::Plan(plan) => !plan.text.is_empty(), codex_protocol::items::TurnItem::Sleep(_) + | codex_protocol::items::TurnItem::HookPrompt(_) | codex_protocol::items::TurnItem::CommandExecution(_) | codex_protocol::items::TurnItem::DynamicToolCall(_) | codex_protocol::items::TurnItem::CollabAgentToolCall(_) @@ -608,7 +609,6 @@ impl ThreadHistoryBuilder { | codex_protocol::items::TurnItem::EnteredReviewMode(_) | codex_protocol::items::TurnItem::ExitedReviewMode(_) => true, codex_protocol::items::TurnItem::UserMessage(_) - | codex_protocol::items::TurnItem::HookPrompt(_) | codex_protocol::items::TurnItem::AgentMessage(_) | codex_protocol::items::TurnItem::Reasoning(_) | codex_protocol::items::TurnItem::WebSearch(_) @@ -4027,6 +4027,37 @@ mod tests { ); } + #[test] + fn canonical_hook_prompt_completion_updates_turn_history() { + let hook_prompt = CoreTurnItem::HookPrompt(codex_protocol::items::HookPromptItem { + id: "hook-prompt-1".into(), + fragments: vec![CoreHookPromptFragment::from_single_hook( + "Retry with tests.", + "hook-run-1", + )], + }); + let expected_item = ThreadItem::from(hook_prompt.clone()); + let mut builder = ThreadHistoryBuilder::new(); + builder.handle_event(&EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + })); + builder.handle_event(&EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: ThreadId::new(), + turn_id: "turn-a".into(), + item: hook_prompt, + completed_at_ms: 0, + })); + + assert_eq!( + builder.active_turn_snapshot().expect("active turn").items, + vec![expected_item] + ); + } + #[test] fn ignores_plain_user_response_items_in_rollout_replay() { let items = vec![ diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index db5e505eb4..829aa3f126 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -89,7 +89,6 @@ use codex_core::ThreadManager; use codex_protocol::ThreadId; use codex_protocol::items::CollabAgentTool as CoreCollabAgentTool; use codex_protocol::items::TurnItem as CoreTurnItem; -use codex_protocol::items::parse_hook_prompt_message; use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile; use codex_protocol::plan_tool::UpdatePlanArgs; use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo; @@ -1022,13 +1021,6 @@ pub(crate) async fn apply_bespoke_event_handling( .await; } EventMsg::RawResponseItem(raw_response_item_event) => { - maybe_emit_hook_prompt_item_completed( - conversation_id, - &event_turn_id, - &raw_response_item_event.item, - &outgoing, - ) - .await; maybe_emit_raw_response_item_completed( conversation_id, &event_turn_id, @@ -1406,45 +1398,6 @@ async fn maybe_emit_raw_response_item_completed( .await; } -pub(crate) async fn maybe_emit_hook_prompt_item_completed( - conversation_id: ThreadId, - turn_id: &str, - item: &codex_protocol::models::ResponseItem, - outgoing: &ThreadScopedOutgoingMessageSender, -) { - let codex_protocol::models::ResponseItem::Message { - role, content, id, .. - } = item - else { - return; - }; - - if role != "user" { - return; - } - - let Some(hook_prompt) = parse_hook_prompt_message(id.as_ref(), content) else { - return; - }; - - let notification = ItemCompletedNotification { - thread_id: conversation_id.to_string(), - turn_id: turn_id.to_string(), - completed_at_ms: now_unix_timestamp_ms(), - item: ThreadItem::HookPrompt { - id: hook_prompt.id, - fragments: hook_prompt - .fragments - .into_iter() - .map(codex_app_server_protocol::HookPromptFragment::from) - .collect(), - }, - }; - outgoing - .send_server_notification(ServerNotification::ItemCompleted(notification)) - .await; -} - async fn find_and_remove_turn_summary( _conversation_id: ThreadId, thread_state: &Arc>, @@ -2104,10 +2057,8 @@ mod tests { use codex_protocol::AgentPath; use codex_protocol::items::DynamicToolCallItem; use codex_protocol::items::DynamicToolCallStatus as CoreDynamicToolCallStatus; - use codex_protocol::items::HookPromptFragment; use codex_protocol::items::SubAgentActivityItem; use codex_protocol::items::TurnItem as CoreTurnItem; - use codex_protocol::items::build_hook_prompt_message; use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions; use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions; use codex_protocol::models::PermissionProfile; @@ -3993,55 +3944,4 @@ mod tests { assert!(rx.try_recv().is_err(), "no extra messages expected"); Ok(()) } - - #[tokio::test] - async fn test_hook_prompt_raw_response_emits_item_completed() -> Result<()> { - let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY); - let outgoing = Arc::new(OutgoingMessageSender::new( - tx, - codex_analytics::AnalyticsEventsClient::disabled(), - )); - let conversation_id = ThreadId::new(); - let outgoing = ThreadScopedOutgoingMessageSender::new( - outgoing, - vec![ConnectionId(1)], - conversation_id, - ); - let item = build_hook_prompt_message(&[ - HookPromptFragment::from_single_hook("Retry with tests.", "hook-run-1"), - HookPromptFragment::from_single_hook("Then summarize cleanly.", "hook-run-2"), - ]) - .expect("hook prompt message"); - - maybe_emit_hook_prompt_item_completed(conversation_id, "turn-1", &item, &outgoing).await; - - let msg = recv_broadcast_message(&mut rx).await?; - match msg { - OutgoingMessage::AppServerNotification(ServerNotification::ItemCompleted( - notification, - )) => { - assert_eq!(notification.thread_id, conversation_id.to_string()); - assert_eq!(notification.turn_id, "turn-1"); - assert_eq!( - notification.item, - ThreadItem::HookPrompt { - id: notification.item.id().to_string(), - fragments: vec![ - codex_app_server_protocol::HookPromptFragment { - text: "Retry with tests.".into(), - hook_run_id: "hook-run-1".into(), - }, - codex_app_server_protocol::HookPromptFragment { - text: "Then summarize cleanly.".into(), - hook_run_id: "hook-run-2".into(), - }, - ], - } - ); - } - other => bail!("unexpected message: {other:?}"), - } - assert!(rx.try_recv().is_err(), "no extra messages expected"); - Ok(()) - } } diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 42ec2063b4..a7a1f6ce81 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -1,5 +1,4 @@ use crate::bespoke_event_handling::apply_bespoke_event_handling; -use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed; use crate::command_exec::CommandExecManager; use crate::command_exec::StartCommandExecParams; use crate::config_manager::ConfigManager; diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 82a49bae0b..784cd51add 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -316,6 +316,9 @@ pub(super) async fn ensure_listener_task_running( thread_state.track_current_turn_event(&event.id, &event.msg); thread_state.experimental_raw_events }; + if matches!(&event.msg, EventMsg::RawResponseItem(_)) && !raw_events_enabled { + continue; + } let subscribed_connection_ids = thread_state_manager .subscribed_connection_ids(conversation_id) .await; @@ -325,19 +328,6 @@ pub(super) async fn ensure_listener_task_running( conversation_id, ); - if let EventMsg::RawResponseItem(raw_response_item_event) = &event.msg - && !raw_events_enabled - { - maybe_emit_hook_prompt_item_completed( - conversation_id, - &event.id, - &raw_response_item_event.item, - &thread_outgoing, - ) - .await; - continue; - } - apply_bespoke_event_handling( event.clone(), conversation_id, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ac8f9d049e..90f43f2bc3 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -112,6 +112,8 @@ use codex_otel::TelemetryAuthMode; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; +use codex_protocol::items::HookPromptFragment; +use codex_protocol::items::build_hook_prompt_message; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; use codex_protocol::models::InternalChatMessageMetadataPassthrough; @@ -1763,6 +1765,44 @@ async fn record_conversation_items_stamps_missing_turn_id_and_preserves_existing ); } +#[tokio::test] +async fn record_response_item_and_emit_turn_item_emits_hook_prompt_lifecycle() { + let (session, turn_context, rx) = make_session_and_context_with_rx().await; + let response_item = build_hook_prompt_message(&[HookPromptFragment::from_single_hook( + "Retry with tests.", + "hook-run-1", + )]) + .expect("hook prompt message"); + let response_item_id = response_item.id().expect("hook prompt id").to_string(); + + session + .record_response_item_and_emit_turn_item(&turn_context, response_item) + .await; + + let raw_response = rx.recv().await.expect("raw response item event"); + assert!(matches!(raw_response.msg, EventMsg::RawResponseItem(_))); + + let started = rx.recv().await.expect("started hook prompt event"); + assert!(matches!( + started.msg, + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::HookPrompt(item), + .. + }) if item.id == response_item_id + )); + + let completed = rx.recv().await.expect("completed hook prompt event"); + assert!(matches!( + completed.msg, + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::HookPrompt(item), + .. + }) if item.id == response_item_id + )); + + assert!(rx.try_recv().is_err(), "no extra events expected"); +} + #[tokio::test] async fn record_inter_agent_communication_sets_turn_id_in_rollout_and_resume() { let (mut session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 6ee3ac2863..41098b2c1e 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -382,9 +382,9 @@ pub(crate) async fn run_turn( if let Some(hook_prompt_message) = build_hook_prompt_message(&stop_outcome.continuation_fragments) { - sess.record_conversation_items( + sess.record_response_item_and_emit_turn_item( &turn_context, - std::slice::from_ref(&hook_prompt_message), + hook_prompt_message, ) .await; stop_hook_active = true; From bff9c4945a7ba83e5c9b1e5787ce7b0c5f0c613c Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Wed, 8 Jul 2026 13:53:18 -0700 Subject: [PATCH 04/11] feat: change amazon Bedrock GPT-5.6 display names (#31636) ## Why Amazon Bedrock's GPT-5.6 variants currently appear as only `Sol`, `Terra`, and `Luna`. Those labels omit the model family and version, making them ambiguous in model lists and inconsistent with the naming of other GPT models. ## What changed - Rename the three Bedrock model display names to `GPT-5.6 Sol`, `GPT-5.6 Terra`, and `GPT-5.6 Luna`. - Strengthen the Bedrock model-manager test to verify both model IDs and their propagated display names. Model IDs, ordering, priorities, reasoning support, and default selection are unchanged. --- .../src/amazon_bedrock/catalog.rs | 30 +++++++++++++------ codex-rs/model-provider/src/provider.rs | 16 +++++----- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs index 95e522e0c4..48c24ad5c8 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs @@ -19,26 +19,28 @@ pub(crate) fn static_model_catalog() -> ModelsResponse { gpt_5_bedrock_model( GPT_5_5_OPENAI_MODEL_ID, AMAZON_BEDROCK_GPT_5_5_MODEL_ID, + "GPT-5.5", /*priority*/ 0, ), gpt_5_bedrock_model( GPT_5_4_OPENAI_MODEL_ID, AMAZON_BEDROCK_GPT_5_4_MODEL_ID, + "GPT-5.4", /*priority*/ 1, ), gpt_5_6_bedrock_model( AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID, - "Sol", + "GPT-5.6 Sol", /*priority*/ 2, ), gpt_5_6_bedrock_model( AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID, - "Terra", + "GPT-5.6 Terra", /*priority*/ 3, ), gpt_5_6_bedrock_model( AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID, - "Luna", + "GPT-5.6 Luna", /*priority*/ 4, ), ], @@ -55,9 +57,15 @@ pub(crate) fn with_default_only_service_tier(mut catalog: ModelsResponse) -> Mod catalog } -fn gpt_5_bedrock_model(openai_slug: &str, bedrock_slug: &str, priority: i32) -> ModelInfo { +fn gpt_5_bedrock_model( + openai_slug: &str, + bedrock_slug: &str, + display_name: &str, + priority: i32, +) -> ModelInfo { let mut model = bundled_openai_model(openai_slug); model.slug = bedrock_slug.to_string(); + model.display_name = display_name.to_string(); model.priority = priority; model.context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW); model.max_context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW); @@ -67,8 +75,12 @@ fn gpt_5_bedrock_model(openai_slug: &str, bedrock_slug: &str, priority: i32) -> } fn gpt_5_6_bedrock_model(bedrock_slug: &str, display_name: &str, priority: i32) -> ModelInfo { - let mut model = gpt_5_bedrock_model(GPT_5_5_OPENAI_MODEL_ID, bedrock_slug, priority); - model.display_name = display_name.to_string(); + let mut model = gpt_5_bedrock_model( + GPT_5_5_OPENAI_MODEL_ID, + bedrock_slug, + display_name, + priority, + ); model .supported_reasoning_levels .push(ReasoningEffortPreset { @@ -148,9 +160,9 @@ mod tests { .expect("Bedrock catalog should include GPT-5.5"); for (slug, display_name, priority) in [ - (AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID, "Sol", 2), - (AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID, "Terra", 3), - (AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID, "Luna", 4), + (AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID, "GPT-5.6 Sol", 2), + (AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID, "GPT-5.6 Terra", 3), + (AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID, "GPT-5.6 Luna", 4), ] { let mut expected = gpt_5_5.clone(); expected.slug = slug.to_string(); diff --git a/codex-rs/model-provider/src/provider.rs b/codex-rs/model-provider/src/provider.rs index 2b8cb67b97..f2fe59e6c9 100644 --- a/codex-rs/model-provider/src/provider.rs +++ b/codex-rs/model-provider/src/provider.rs @@ -657,20 +657,20 @@ mod tests { provider.models_manager(test_codex_home(), /*config_model_catalog*/ None); let catalog = manager.raw_model_catalog(RefreshStrategy::Online).await; - let model_ids = catalog + let models = catalog .models .iter() - .map(|model| model.slug.as_str()) + .map(|model| (model.slug.as_str(), model.display_name.as_str())) .collect::>(); assert_eq!( - model_ids, + models, vec![ - "openai.gpt-5.5", - "openai.gpt-5.4", - "openai.gpt-5.6-sol", - "openai.gpt-5.6-terra", - "openai.gpt-5.6-luna", + ("openai.gpt-5.5", "GPT-5.5"), + ("openai.gpt-5.4", "GPT-5.4"), + ("openai.gpt-5.6-sol", "GPT-5.6 Sol"), + ("openai.gpt-5.6-terra", "GPT-5.6 Terra"), + ("openai.gpt-5.6-luna", "GPT-5.6 Luna"), ] ); From 602dbb42dcc9504252525bb01182771f39c68cf1 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Wed, 8 Jul 2026 13:53:36 -0700 Subject: [PATCH 05/11] core: stop emitting legacy command events directly (#31629) ## Description This PR removes the last path in core that emits `ExecCommandBegin` / `ExecCommandEnd` directly. Every command execution now starts and completes through canonical `ItemStarted` / `ItemCompleted(TurnItem::CommandExecution)`. The existing `HasLegacyEvent` compatibility layer still fans out Begin/End afterward, so raw core event consumers and legacy rollout replay keep seeing the same events. `UnifiedExecInteraction` is dormant today. Live unified exec uses `UnifiedExecStartup` for command lifecycle and `TerminalInteraction` for `write_stdin` and polling, so this is code cleanup rather than a current product behavior change. The main win is the code-level invariant where all core flows emit `TurnItem` instead of legacy events. ## What changed - Removed the `UnifiedExecInteraction` branches that emitted legacy command events directly. - Routed every command source through the existing canonical `CommandExecution` lifecycle and compatibility fanout. --- codex-rs/core/src/tools/events.rs | 48 ------------------------------- 1 file changed, 48 deletions(-) diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 5b30c6a156..628e6ce9bc 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -3,7 +3,6 @@ use crate::session::session::Session; use crate::session::turn_context::TurnContext; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::sandboxing::ToolError; -use crate::turn_timing::now_unix_timestamp_ms; use codex_apply_patch::AppliedPatchDelta; use codex_protocol::error::CodexErr; use codex_protocol::error::SandboxErr; @@ -14,8 +13,6 @@ use codex_protocol::items::FileChangeItem; use codex_protocol::items::TurnItem; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::ExecCommandBeginEvent; -use codex_protocol::protocol::ExecCommandEndEvent; use codex_protocol::protocol::ExecCommandSource; use codex_protocol::protocol::ExecCommandStatus; use codex_protocol::protocol::FileChange; @@ -104,25 +101,6 @@ pub(crate) async fn emit_exec_command_begin( interaction_input: Option, process_id: Option<&str>, ) { - if matches!(source, ExecCommandSource::UnifiedExecInteraction) { - ctx.session - .send_event( - ctx.turn, - EventMsg::ExecCommandBegin(ExecCommandBeginEvent { - call_id: ctx.call_id.to_string(), - process_id: process_id.map(str::to_owned), - turn_id: ctx.turn.sub_id.clone(), - started_at_ms: now_unix_timestamp_ms(), - command: command.to_vec(), - cwd: cwd.clone(), - parsed_cmd: parsed_cmd.to_vec(), - source, - interaction_input, - }), - ) - .await; - return; - } ctx.session .emit_turn_item_started( ctx.turn, @@ -568,32 +546,6 @@ async fn emit_exec_end( exec_input: ExecCommandInput<'_>, exec_result: ExecCommandResult, ) { - if matches!(exec_input.source, ExecCommandSource::UnifiedExecInteraction) { - ctx.session - .send_event( - ctx.turn, - EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id: ctx.call_id.to_string(), - process_id: exec_input.process_id.map(str::to_owned), - turn_id: ctx.turn.sub_id.clone(), - completed_at_ms: now_unix_timestamp_ms(), - command: exec_input.command.to_vec(), - cwd: exec_input.cwd.clone(), - parsed_cmd: exec_input.parsed_cmd.to_vec(), - source: exec_input.source, - interaction_input: exec_input.interaction_input.map(str::to_owned), - stdout: exec_result.stdout, - stderr: exec_result.stderr, - aggregated_output: exec_result.aggregated_output, - exit_code: exec_result.exit_code, - duration: exec_result.duration, - formatted_output: exec_result.formatted_output, - status: exec_result.status, - }), - ) - .await; - return; - } ctx.session .emit_turn_item_completed( ctx.turn, From e621d7df8c4571e0b996a29095ef0de5bc93af5c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:15 -0700 Subject: [PATCH 06/11] core: preserve Responses WebSockets with system proxy (#31441) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why Responses WebSockets are the normal lower-latency transport for WebSocket-capable providers. They must not bypass an OS-selected proxy when `features.respect_system_proxy` is enabled, but disabling WebSockets whenever the feature is enabled would impose a substantial performance penalty. Merged PR #31622 introduced the reusable proxy-aware WebSocket transport. This PR makes the Responses API its first consumer so the existing fast path uses the same effective proxy and trust policy as HTTP. ## What changed - Register `codex-websocket-client` as a workspace dependency and use it from `codex-api`. - Feed the shared crate’s route-independent `WebSocketConnection` into the existing Responses message pump. - Require a configured `HttpClientFactory` for normal Responses WebSocket connections and the CLI doctor probe, so neither path can open a connection without consulting the effective proxy policy. - Pass the session factory from `core` and the effective configuration factory from `doctor`. - Add an end-to-end Responses test that enables `RespectSystemProxy`, asserts the resolved policy, completes a turn over WebSocket, and verifies the connection and request counts. - Keep the existing Responses protocol handling, ping/pong pump, and session-scoped HTTP fallback unchanged. The DNS, proxy, TLS, custom-CA, and Happy Eyeballs implementation and its transport tests live in merged PR #31622. This PR deliberately contains only the Responses integration and does not duplicate that transport code. ## Review guide 1. `codex-rs/codex-api/src/endpoint/responses_websocket.rs` constructs the shared connector and adapts its uniform stream to the existing pump. 2. `codex-rs/core/src/client.rs` supplies the session-scoped factory for production Responses connections. 3. `codex-rs/cli/src/doctor.rs` supplies the effective configuration factory to the handshake probe. 4. `codex-rs/core/tests/suite/client_websockets.rs` covers the enabled-feature path end to end. ## Test plan - `cargo check --tests -p codex-api -p codex-core -p codex-cli` - `just test -p codex-api` - `just test -p codex-core responses_websocket_streams_with_system_proxy_feature` - `cargo shear` - `just bazel-lock-check` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/31441). * #31637 * #31431 * #31363 * #31362 * #31361 * __->__ #31441 --- codex-rs/Cargo.lock | 1 + codex-rs/Cargo.toml | 1 + codex-rs/cli/src/doctor.rs | 2 + codex-rs/codex-api/Cargo.toml | 1 + .../src/endpoint/responses_websocket.rs | 42 ++++++-------- codex-rs/core/src/client.rs | 1 + .../core/tests/suite/client_websockets.rs | 56 ++++++++++++++++++- 7 files changed, 77 insertions(+), 27 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 9856ef9cd3..3d98479749 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1940,6 +1940,7 @@ dependencies = [ "codex-http-client", "codex-protocol", "codex-utils-rustls-provider", + "codex-websocket-client", "eventsource-stream", "futures", "http 1.4.0", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 0085b663ef..7b153dfaa0 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -168,6 +168,7 @@ codex-code-mode = { path = "code-mode" } codex-code-mode-protocol = { path = "code-mode-protocol" } codex-home = { path = "codex-home" } codex-http-client = { path = "http-client" } +codex-websocket-client = { path = "websocket-client" } codex-config = { path = "config" } codex-connectors = { path = "connectors" } codex-connectors-extension = { path = "ext/connectors" } diff --git a/codex-rs/cli/src/doctor.rs b/codex-rs/cli/src/doctor.rs index 2e9c0094c4..7f06a611bc 100644 --- a/codex-rs/cli/src/doctor.rs +++ b/codex-rs/cli/src/doctor.rs @@ -2383,9 +2383,11 @@ async fn websocket_reachability_check( HeaderValue::from_static(RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE), ); let client = ResponsesWebsocketClient::new(api_provider, api_auth); + let http_client_factory = config.http_client_factory(); match tokio::time::timeout( provider.websocket_connect_timeout(), client.probe_handshake( + &http_client_factory, extra_headers, default_headers(), WEBSOCKET_IMMEDIATE_CLOSE_GRACE, diff --git a/codex-rs/codex-api/Cargo.toml b/codex-rs/codex-api/Cargo.toml index 084b058e12..21f6b67425 100644 --- a/codex-rs/codex-api/Cargo.toml +++ b/codex-rs/codex-api/Cargo.toml @@ -13,6 +13,7 @@ codex-client = { workspace = true } codex-http-client = { workspace = true } codex-protocol = { workspace = true } codex-utils-rustls-provider = { workspace = true } +codex-websocket-client = { workspace = true } futures = { workspace = true } http = { workspace = true } reqwest = { workspace = true, features = ["json", "stream"] } diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index cce056f638..88e7fbb9b4 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -11,8 +11,9 @@ use crate::sse::ResponsesStreamEvent; use crate::sse::process_responses_event; use crate::telemetry::WebsocketTelemetry; use codex_client::TransportError; -use codex_http_client::maybe_build_rustls_client_config_with_custom_ca; -use codex_utils_rustls_provider::ensure_rustls_crypto_provider; +use codex_http_client::HttpClientFactory; +use codex_websocket_client::WebSocketConnection; +use codex_websocket_client::WebSocketConnector; use futures::SinkExt; use futures::StreamExt; use http::HeaderMap; @@ -25,14 +26,10 @@ use serde_json::map::Map as JsonMap; use std::sync::Arc; use std::sync::OnceLock; use std::time::Duration; -use tokio::net::TcpStream; use tokio::sync::Mutex; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::time::Instant; -use tokio_tungstenite::MaybeTlsStream; -use tokio_tungstenite::WebSocketStream; -use tokio_tungstenite::connect_async_tls_with_config; use tokio_tungstenite::tungstenite::Error as WsError; use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::client::IntoClientRequest; @@ -62,7 +59,7 @@ enum WsCommand { } impl WsStream { - fn new(inner: WebSocketStream>) -> Self { + fn new(inner: WebSocketConnection) -> Self { let (tx_command, mut rx_command) = mpsc::channel::(32); let (tx_message, rx_message) = mpsc::unbounded_channel::>(); @@ -334,6 +331,7 @@ impl ResponsesWebsocketClient { )] pub async fn connect( &self, + http_client_factory: &HttpClientFactory, extra_headers: HeaderMap, default_headers: HeaderMap, turn_state: Option>>, @@ -349,7 +347,7 @@ impl ResponsesWebsocketClient { self.auth.add_auth_headers(&mut headers); let (stream, _status, server_reasoning_included, models_etag, server_model) = - connect_websocket(ws_url, headers, turn_state.clone()).await?; + connect_websocket(ws_url, headers, http_client_factory, turn_state.clone()).await?; Ok(ResponsesWebsocketConnection::new( stream, self.provider.stream_idle_timeout, @@ -369,6 +367,7 @@ impl ResponsesWebsocketClient { /// a usable connection from a policy rejection that closes right away. pub async fn probe_handshake( &self, + http_client_factory: &HttpClientFactory, extra_headers: HeaderMap, default_headers: HeaderMap, immediate_close_timeout: Duration, @@ -383,7 +382,13 @@ impl ResponsesWebsocketClient { self.auth.add_auth_headers(&mut headers); let (mut stream, status, reasoning_included, models_etag, server_model) = - connect_websocket(ws_url.clone(), headers, /*turn_state*/ None).await?; + connect_websocket( + ws_url.clone(), + headers, + http_client_factory, + /*turn_state*/ None, + ) + .await?; let immediate_close = tokio::time::timeout(immediate_close_timeout, stream.next()) .await .ok() @@ -437,9 +442,9 @@ fn merge_request_headers( async fn connect_websocket( url: Url, headers: HeaderMap, + http_client_factory: &HttpClientFactory, turn_state: Option>>, ) -> Result<(WsStream, StatusCode, bool, Option, Option), ApiError> { - ensure_rustls_crypto_provider(); info!("connecting to websocket: {url}"); let mut request = url @@ -448,20 +453,9 @@ async fn connect_websocket( .map_err(|err| ApiError::Stream(format!("failed to build websocket request: {err}")))?; request.headers_mut().extend(headers); - // Secure websocket traffic needs the same custom-CA policy as reqwest-based HTTPS traffic. - // If a Codex-specific CA bundle is configured, build an explicit rustls connector so this - // websocket path does not fall back to tungstenite's default native-roots-only behavior. - let connector = maybe_build_rustls_client_config_with_custom_ca() - .map_err(|err| ApiError::Stream(format!("failed to configure websocket TLS: {err}")))? - .map(tokio_tungstenite::Connector::Rustls); - - let response = connect_async_tls_with_config( - request, - Some(websocket_config()), - false, // `false` means "do not disable Nagle", which is tungstenite's recommended default. - connector, - ) - .await; + let connector = WebSocketConnector::new(http_client_factory) + .map_err(|err| ApiError::Stream(format!("failed to configure websocket TLS: {err}")))?; + let response = connector.connect(request, websocket_config()).await; let (stream, response) = match response { Ok((stream, response)) => { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 8c98a3372e..2bd4ae3bcf 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -1006,6 +1006,7 @@ impl ModelClient { let result = match tokio::time::timeout( websocket_connect_timeout, ApiWebSocketResponsesClient::new(api_provider, api_auth).connect( + &self.http_client_factory, headers, codex_login::default_client::default_headers(), /*turn_state*/ None, diff --git a/codex-rs/core/tests/suite/client_websockets.rs b/codex-rs/core/tests/suite/client_websockets.rs index 05a93807b2..71d0965ef9 100755 --- a/codex-rs/core/tests/suite/client_websockets.rs +++ b/codex-rs/core/tests/suite/client_websockets.rs @@ -8,6 +8,7 @@ use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER; use codex_features::Feature; +use codex_http_client::OutboundProxyPolicy; use codex_login::CodexAuth; use codex_login::auth::AgentIdentityAuthPolicy; use codex_model_provider_info::ModelProviderInfo; @@ -102,6 +103,7 @@ fn assert_request_trace_matches(body: &serde_json::Value, expected_trace: &W3cTr struct WebsocketTestHarness { _codex_home: TempDir, client: ModelClient, + outbound_proxy_policy: OutboundProxyPolicy, session_id: SessionId, thread_id: ThreadId, model_info: ModelInfo, @@ -230,6 +232,38 @@ async fn responses_websocket_streams_without_feature_flag_when_provider_supports server.shutdown().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_websocket_streams_with_system_proxy_feature() { + skip_if_no_network!(); + + let server = start_websocket_server(vec![vec![vec![ + ev_response_created("resp-1"), + ev_completed("resp-1"), + ]]]) + .await; + + let harness = websocket_harness_with_provider_options( + websocket_provider(&server), + /*runtime_metrics_enabled*/ false, + /*concurrent_reasoning_summaries_enabled*/ false, + /*enabled_features*/ &[Feature::RespectSystemProxy], + ) + .await; + assert_eq!( + harness.outbound_proxy_policy, + OutboundProxyPolicy::RespectSystemProxy + ); + let mut client_session = harness.client.new_session(); + let prompt = prompt_with_input(vec![message_item("hello")]); + + stream_until_complete(&mut client_session, &harness, &prompt).await; + + assert_eq!(server.handshakes().len(), 1); + assert_eq!(server.single_connection().len(), 1); + + server.shutdown().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn responses_websocket_reuses_connection_with_per_turn_trace_payloads() { skip_if_no_network!(); @@ -389,8 +423,10 @@ async fn responses_websocket_request_prewarm_reuses_connection() { let mut provider = websocket_provider(&server); provider.name = ModelProviderInfo::create_openai_provider(/*base_url*/ None).name; let harness = websocket_harness_with_provider_options( - provider, /*runtime_metrics_enabled*/ true, + provider, + /*runtime_metrics_enabled*/ true, /*concurrent_reasoning_summaries_enabled*/ true, + /*enabled_features*/ &[], ) .await; let mut client_session = harness.client.new_session(); @@ -1005,8 +1041,10 @@ async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() { let mut provider = websocket_provider(&server); provider.name = ModelProviderInfo::create_openai_provider(/*base_url*/ None).name; let harness = websocket_harness_with_provider_options( - provider, /*runtime_metrics_enabled*/ false, + provider, + /*runtime_metrics_enabled*/ false, /*concurrent_reasoning_summaries_enabled*/ false, + /*enabled_features*/ &[], ) .await; @@ -2216,6 +2254,7 @@ async fn websocket_harness_with_options( websocket_provider(server), runtime_metrics_enabled, /*concurrent_reasoning_summaries_enabled*/ false, + /*enabled_features*/ &[], ) .await } @@ -2224,6 +2263,7 @@ async fn websocket_harness_with_provider_options( provider: ModelProviderInfo, runtime_metrics_enabled: bool, concurrent_reasoning_summaries_enabled: bool, + enabled_features: &[Feature], ) -> WebsocketTestHarness { let codex_home = TempDir::new().unwrap(); let mut config = load_default_config_for_test(&codex_home).await; @@ -2240,6 +2280,15 @@ async fn websocket_harness_with_provider_options( .enable(Feature::ConcurrentReasoningSummaries) .expect("test config should allow feature update"); } + for feature in enabled_features { + config + .features + .enable(*feature) + .expect("test config should allow feature update"); + } + config.respect_system_proxy = config.features.enabled(Feature::RespectSystemProxy); + let http_client_factory = config.http_client_factory(); + let outbound_proxy_policy = http_client_factory.outbound_proxy_policy(); let config = Arc::new(config); let model_info = codex_core::test_support::construct_model_info_offline(MODEL, &config); let thread_id = ThreadId::new(); @@ -2284,12 +2333,13 @@ async fn websocket_harness_with_provider_options( .features .enabled(Feature::ConcurrentReasoningSummaries), /*attestation_provider*/ None, - config.http_client_factory(), + http_client_factory, ); WebsocketTestHarness { _codex_home: codex_home, client, + outbound_proxy_policy, session_id, thread_id, model_info, From e3efc867ff2b0034431946c1399b4c801bbbfd23 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:20 -0700 Subject: [PATCH 07/11] model-provider: route model discovery through HTTP client factory --- codex-rs/core/src/test_support.rs | 8 ++++++- codex-rs/core/src/thread_manager.rs | 9 ++++++- codex-rs/memories/write/src/startup_tests.rs | 4 +++- .../model-provider/src/amazon_bedrock/mod.rs | 2 ++ codex-rs/model-provider/src/lib.rs | 1 + .../model-provider/src/models_endpoint.rs | 23 ++++++++++++++++-- codex-rs/model-provider/src/provider.rs | 24 +++++++++++++++---- 7 files changed, 62 insertions(+), 9 deletions(-) diff --git a/codex-rs/core/src/test_support.rs b/codex-rs/core/src/test_support.rs index 1f946602f5..8e8af7da5d 100644 --- a/codex-rs/core/src/test_support.rs +++ b/codex-rs/core/src/test_support.rs @@ -11,6 +11,8 @@ use codex_exec_server::EnvironmentManager; use codex_extension_api::LoadUserInstructionsFuture; use codex_extension_api::LoadedUserInstructions; use codex_extension_api::UserInstructionsProvider; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_model_provider::create_model_provider; @@ -155,7 +157,11 @@ pub fn models_manager_with_provider( provider: ModelProviderInfo, ) -> SharedModelsManager { let provider = create_model_provider(provider, Some(auth_manager)); - provider.models_manager(codex_home, /*config_model_catalog*/ None) + provider.models_manager( + codex_home, + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + /*config_model_catalog*/ None, + ) } pub fn get_model_offline(model: Option<&str>) -> String { diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 669da49547..f22bdd9af9 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -32,6 +32,8 @@ use codex_extension_api::LoadedUserInstructions; use codex_extension_api::UserInstructionsProvider; use codex_extension_api::empty_extension_registry; use codex_features::Feature; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR; @@ -266,6 +268,7 @@ pub fn build_models_manager( let provider = create_model_provider(config.model_provider.clone(), Some(auth_manager)); provider.models_manager( config.codex_home.to_path_buf(), + config.http_client_factory(), config.model_catalog.clone(), ) } @@ -457,7 +460,11 @@ impl ThreadManager { threads: Arc::new(RwLock::new(HashMap::new())), thread_created_tx, models_manager: create_model_provider(provider, Some(auth_manager.clone())) - .models_manager(codex_home, /*config_model_catalog*/ None), + .models_manager( + codex_home, + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + /*config_model_catalog*/ None, + ), environment_manager, skills_service, plugins_manager, diff --git a/codex-rs/memories/write/src/startup_tests.rs b/codex-rs/memories/write/src/startup_tests.rs index fad1ce14a4..b1e6ec492b 100644 --- a/codex-rs/memories/write/src/startup_tests.rs +++ b/codex-rs/memories/write/src/startup_tests.rs @@ -10,6 +10,7 @@ use codex_git_utils::diff_since_latest_init; use codex_git_utils::reset_git_repository; use codex_login::AuthManager; use codex_login::CodexAuth; +use codex_model_provider::HttpClientFactory; use codex_model_provider::ModelProvider; use codex_model_provider::ModelProviderFuture; use codex_model_provider::ProviderAccountResult; @@ -627,10 +628,11 @@ impl ModelProvider for MockMemoryModelProvider { fn models_manager( &self, codex_home: PathBuf, + http_client_factory: HttpClientFactory, config_model_catalog: Option, ) -> codex_models_manager::manager::SharedModelsManager { self.delegate - .models_manager(codex_home, config_model_catalog) + .models_manager(codex_home, http_client_factory, config_model_catalog) } } diff --git a/codex-rs/model-provider/src/amazon_bedrock/mod.rs b/codex-rs/model-provider/src/amazon_bedrock/mod.rs index 9fdf937bcb..7568b535b2 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/mod.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/mod.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use codex_api::ApiError; use codex_api::Provider; use codex_api::SharedAuthProvider; +use codex_http_client::HttpClientFactory; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::auth::BedrockApiKeyAuth; @@ -165,6 +166,7 @@ impl ModelProvider for AmazonBedrockModelProvider { fn models_manager( &self, _codex_home: PathBuf, + _http_client_factory: HttpClientFactory, config_model_catalog: Option, ) -> SharedModelsManager { Arc::new(StaticModelsManager::new( diff --git a/codex-rs/model-provider/src/lib.rs b/codex-rs/model-provider/src/lib.rs index 15967c4fe0..771bf97b87 100644 --- a/codex-rs/model-provider/src/lib.rs +++ b/codex-rs/model-provider/src/lib.rs @@ -11,6 +11,7 @@ pub use auth::auth_provider_from_auth; pub use auth::unauthenticated_auth_provider; pub use bearer_auth_provider::BearerAuthProvider; pub use bearer_auth_provider::BearerAuthProvider as CoreAuthProvider; +pub use codex_http_client::HttpClientFactory; pub use codex_model_provider_info::CHATGPT_CODEX_BASE_URL; pub use codex_protocol::account::ProviderAccount; pub use provider::ModelProvider; diff --git a/codex-rs/model-provider/src/models_endpoint.rs b/codex-rs/model-provider/src/models_endpoint.rs index 9a203c26e1..1f04db72f3 100644 --- a/codex-rs/model-provider/src/models_endpoint.rs +++ b/codex-rs/model-provider/src/models_endpoint.rs @@ -10,11 +10,13 @@ use codex_api::auth_header_telemetry; use codex_api::map_api_error; use codex_feedback::FeedbackRequestTags; use codex_feedback::emit_feedback_request_tags_with_auth_env; +use codex_http_client::ClientRouteClass; +use codex_http_client::HttpClientFactory; use codex_login::AuthEnvTelemetry; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::collect_auth_env_telemetry; -use codex_login::default_client::build_reqwest_client; +use codex_login::default_client::build_default_reqwest_client_for_route; use codex_model_provider_info::ModelProviderInfo; use codex_models_manager::manager::ModelsEndpointClient; use codex_models_manager::manager::ModelsEndpointFuture; @@ -38,16 +40,19 @@ const MODELS_ENDPOINT: &str = "/models"; pub(crate) struct OpenAiModelsEndpoint { provider_info: ModelProviderInfo, auth_manager: Option>, + http_client_factory: HttpClientFactory, } impl OpenAiModelsEndpoint { pub(crate) fn new( provider_info: ModelProviderInfo, auth_manager: Option>, + http_client_factory: HttpClientFactory, ) -> Self { Self { provider_info, auth_manager, + http_client_factory, } } @@ -75,7 +80,14 @@ impl OpenAiModelsEndpoint { let auth_mode = auth.as_ref().map(CodexAuth::auth_mode); let api_provider = self.provider_info.to_api_provider(auth_mode)?; let api_auth = resolve_provider_auth(auth.as_ref(), &self.provider_info)?; - let transport = ReqwestTransport::new(build_reqwest_client()); + let request_url = api_provider.url_for_path(MODELS_ENDPOINT); + let client = build_default_reqwest_client_for_route( + &self.http_client_factory, + &request_url, + ClientRouteClass::Api, + ) + .map_err(std::io::Error::from)?; + let transport = ReqwestTransport::new(client); let auth_telemetry = auth_header_telemetry(api_auth.as_ref()); let agent_identity_telemetry = if let Some(CodexAuth::AgentIdentity(auth)) = auth.as_ref() { Some(agent_identity_telemetry(auth)) @@ -229,8 +241,13 @@ mod tests { use std::num::NonZeroU64; use super::*; + use codex_http_client::OutboundProxyPolicy; use codex_protocol::config_types::ModelProviderAuthInfo; + fn default_http_client_factory() -> HttpClientFactory { + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) + } + fn provider_info_with_command_auth() -> ModelProviderInfo { ModelProviderInfo { auth: Some(ModelProviderAuthInfo { @@ -253,6 +270,7 @@ mod tests { let endpoint = OpenAiModelsEndpoint::new( provider_info_with_command_auth(), /*auth_manager*/ None, + default_http_client_factory(), ); assert!(endpoint.has_command_auth()); @@ -263,6 +281,7 @@ mod tests { let endpoint = OpenAiModelsEndpoint::new( ModelProviderInfo::create_openai_provider(/*base_url*/ None), /*auth_manager*/ None, + default_http_client_factory(), ); assert!(!endpoint.has_command_auth()); diff --git a/codex-rs/model-provider/src/provider.rs b/codex-rs/model-provider/src/provider.rs index f2fe59e6c9..054da9f281 100644 --- a/codex-rs/model-provider/src/provider.rs +++ b/codex-rs/model-provider/src/provider.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use codex_api::ApiError; use codex_api::Provider; use codex_api::SharedAuthProvider; +use codex_http_client::HttpClientFactory; use codex_login::AuthManager; use codex_login::CodexAuth; use codex_model_provider_info::ModelProviderInfo; @@ -197,6 +198,7 @@ pub trait ModelProvider: fmt::Debug + Send + Sync { fn models_manager( &self, codex_home: PathBuf, + http_client_factory: HttpClientFactory, config_model_catalog: Option, ) -> SharedModelsManager; } @@ -314,6 +316,7 @@ impl ModelProvider for ConfiguredModelProvider { fn models_manager( &self, codex_home: PathBuf, + http_client_factory: HttpClientFactory, config_model_catalog: Option, ) -> SharedModelsManager { match config_model_catalog { @@ -325,6 +328,7 @@ impl ModelProvider for ConfiguredModelProvider { let endpoint = Arc::new(OpenAiModelsEndpoint::new( self.info.clone(), self.auth_manager.clone(), + http_client_factory, )); Arc::new(OpenAiModelsManager::new( codex_home, @@ -340,6 +344,7 @@ impl ModelProvider for ConfiguredModelProvider { mod tests { use std::num::NonZeroU64; + use codex_http_client::OutboundProxyPolicy; use codex_login::auth::AgentIdentityAuthPolicy; use codex_login::auth::BedrockApiKeyAuth; use codex_model_provider_info::ModelProviderAwsAuthInfo; @@ -363,6 +368,10 @@ mod tests { use super::*; use crate::auth::AgentIdentitySessionFallback; + fn default_http_client_factory() -> HttpClientFactory { + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) + } + fn provider_info_with_command_auth() -> ModelProviderInfo { ModelProviderInfo { auth: Some(ModelProviderAuthInfo { @@ -653,8 +662,11 @@ mod tests { ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None), /*auth_manager*/ None, ); - let manager = - provider.models_manager(test_codex_home(), /*config_model_catalog*/ None); + let manager = provider.models_manager( + test_codex_home(), + default_http_client_factory(), + /*config_model_catalog*/ None, + ); let catalog = manager.raw_model_catalog(RefreshStrategy::Online).await; let models = catalog @@ -701,6 +713,7 @@ mod tests { ); let manager = provider.models_manager( test_codex_home(), + default_http_client_factory(), Some(ModelsResponse { models: vec![configured_model], }), @@ -746,8 +759,11 @@ mod tests { )), ); - let manager = - provider.models_manager(test_codex_home(), /*config_model_catalog*/ None); + let manager = provider.models_manager( + test_codex_home(), + default_http_client_factory(), + /*config_model_catalog*/ None, + ); let catalog = manager.raw_model_catalog(RefreshStrategy::Online).await; assert!( From f36a89b588135c0fe69327cd257b82672886ecbb Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:20 -0700 Subject: [PATCH 08/11] core: route realtime and memories through HTTP client factory --- codex-rs/core/src/client.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 2bd4ae3bcf..251b7c1dcf 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -70,7 +70,6 @@ use codex_login::CodexAuth; use codex_login::RefreshTokenError; use codex_login::UnauthorizedRecovery; use codex_login::default_client::build_default_reqwest_client_for_route; -use codex_login::default_client::build_reqwest_client; use codex_otel::SessionTelemetry; use codex_otel::current_span_w3c_trace_context; use codex_protocol::auth::AuthMode; @@ -155,6 +154,7 @@ const WS_REQUEST_HEADER_RESPONSES_LITE_CLIENT_METADATA_KEY: &str = const RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06"; const X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER: &str = "x-openai-internal-codex-responses-lite"; +const REALTIME_CALLS_ENDPOINT: &str = "/realtime/calls"; const RESPONSES_ENDPOINT: &str = "/responses"; const RESPONSES_COMPACT_ENDPOINT: &str = "/responses/compact"; // `/responses/compact` is unary, so the timeout covers the full response rather than one idle @@ -549,7 +549,7 @@ impl ModelClient { } let client_setup = self.current_client_setup().await?; let transport = - self.build_responses_transport(&client_setup.api_provider, RESPONSES_COMPACT_ENDPOINT)?; + self.build_api_transport(&client_setup.api_provider, RESPONSES_COMPACT_ENDPOINT)?; let request_telemetry = Self::build_request_telemetry( session_telemetry, AuthRequestTelemetryContext::new( @@ -651,8 +651,8 @@ impl ModelClient { sideband_headers.extend(sideband_websocket_auth_headers( client_setup.api_auth.as_ref(), )); - let transport = ReqwestTransport::new(build_reqwest_client()); let api_provider = api_provider_override.unwrap_or(client_setup.api_provider); + let transport = self.build_api_transport(&api_provider, REALTIME_CALLS_ENDPOINT)?; let response = ApiRealtimeCallClient::new(transport, api_provider, client_setup.api_auth) .create_with_session_and_headers(sdp, session_config, extra_headers) .await @@ -682,7 +682,8 @@ impl ModelClient { } let client_setup = self.current_client_setup().await?; - let transport = ReqwestTransport::new(build_reqwest_client()); + let transport = + self.build_api_transport(&client_setup.api_provider, MEMORIES_SUMMARIZE_ENDPOINT)?; let request_telemetry = Self::build_request_telemetry( session_telemetry, AuthRequestTelemetryContext::new( @@ -961,7 +962,7 @@ impl ModelClient { }) } - fn build_responses_transport( + fn build_api_transport( &self, api_provider: &ApiProvider, endpoint: &str, @@ -1413,7 +1414,7 @@ impl ModelClientSession { let client_setup = self.client.current_client_setup().await?; let transport = self .client - .build_responses_transport(&client_setup.api_provider, RESPONSES_ENDPOINT)?; + .build_api_transport(&client_setup.api_provider, RESPONSES_ENDPOINT)?; let request_auth_context = AuthRequestTelemetryContext::new( client_setup.auth.as_ref().map(CodexAuth::auth_mode), client_setup.api_auth.as_ref(), From 794659a66798e8c224dca033a6036a69227a2aa2 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:20 -0700 Subject: [PATCH 09/11] codex-api: route file uploads through HTTP client factory --- codex-rs/codex-api/src/files.rs | 107 +++++++++++++++++++-------- codex-rs/core/src/mcp_openai_file.rs | 2 + 2 files changed, 78 insertions(+), 31 deletions(-) diff --git a/codex-rs/codex-api/src/files.rs b/codex-rs/codex-api/src/files.rs index 3cd3932d06..c568555885 100644 --- a/codex-rs/codex-api/src/files.rs +++ b/codex-rs/codex-api/src/files.rs @@ -2,7 +2,10 @@ use std::time::Duration; use crate::AuthProvider; use bytes::Bytes; -use codex_http_client::build_reqwest_client_with_custom_ca; +use codex_http_client::BuildRouteAwareHttpClientError; +use codex_http_client::ClientRouteClass; +use codex_http_client::HttpClientFactory; +use codex_http_client::OutboundProxyPolicy; use futures::Stream; use reqwest::StatusCode; use reqwest::header::CONTENT_LENGTH; @@ -55,6 +58,12 @@ pub enum OpenAiFileError { #[source] source: serde_json::Error, }, + #[error("failed to build OpenAI file client for {url}: {source}")] + ClientBuild { + url: String, + #[source] + source: BuildRouteAwareHttpClientError, + }, #[error("OpenAI file upload for `{file_id}` is not ready yet")] UploadNotReady { file_id: String }, #[error("OpenAI file upload for `{file_id}` failed: {message}")] @@ -84,6 +93,7 @@ pub fn openai_file_uri(file_id: &str) -> String { pub async fn upload_openai_file( base_url: &str, auth: &dyn AuthProvider, + http_client_factory: &HttpClientFactory, file_name: String, file_size_bytes: u64, contents: impl Stream> + Send + 'static, @@ -97,18 +107,23 @@ pub async fn upload_openai_file( } let create_url = format!("{}/files", base_url.trim_end_matches('/')); - let create_response = authorized_request(auth, reqwest::Method::POST, &create_url) - .json(&serde_json::json!({ - "file_name": file_name.as_str(), - "file_size": file_size_bytes, - "use_case": OPENAI_FILE_USE_CASE, - })) - .send() - .await - .map_err(|source| OpenAiFileError::Request { - url: create_url.clone(), - source, - })?; + let create_response = authorized_request( + http_client_factory, + auth, + reqwest::Method::POST, + &create_url, + )? + .json(&serde_json::json!({ + "file_name": file_name.as_str(), + "file_size": file_size_bytes, + "use_case": OPENAI_FILE_USE_CASE, + })) + .send() + .await + .map_err(|source| OpenAiFileError::Request { + url: create_url.clone(), + source, + })?; let create_status = create_response.status(); let create_body = create_response.text().await.unwrap_or_default(); if !create_status.is_success() { @@ -124,7 +139,7 @@ pub async fn upload_openai_file( source, })?; - let upload_response = build_reqwest_client() + let upload_response = build_reqwest_client(http_client_factory, &create_payload.upload_url)? .put(&create_payload.upload_url) .timeout(OPENAI_FILE_REQUEST_TIMEOUT) .header("x-ms-blob-type", "BlockBlob") @@ -153,14 +168,19 @@ pub async fn upload_openai_file( ); let finalize_started_at = Instant::now(); loop { - let finalize_response = authorized_request(auth, reqwest::Method::POST, &finalize_url) - .json(&serde_json::json!({})) - .send() - .await - .map_err(|source| OpenAiFileError::Request { - url: finalize_url.clone(), - source, - })?; + let finalize_response = authorized_request( + http_client_factory, + auth, + reqwest::Method::POST, + &finalize_url, + )? + .json(&serde_json::json!({})) + .send() + .await + .map_err(|source| OpenAiFileError::Request { + url: finalize_url.clone(), + source, + })?; let finalize_status = finalize_response.status(); let finalize_body = finalize_response.text().await.unwrap_or_default(); if !finalize_status.is_success() { @@ -213,25 +233,45 @@ pub async fn upload_openai_file( } fn authorized_request( + http_client_factory: &HttpClientFactory, auth: &dyn AuthProvider, method: reqwest::Method, url: &str, -) -> reqwest::RequestBuilder { +) -> Result { let mut headers = http::HeaderMap::new(); auth.add_auth_headers(&mut headers); - let client = build_reqwest_client(); - client + let client = build_reqwest_client(http_client_factory, url)?; + Ok(client .request(method, url) .timeout(OPENAI_FILE_REQUEST_TIMEOUT) - .headers(headers) + .headers(headers)) } -fn build_reqwest_client() -> reqwest::Client { - build_reqwest_client_with_custom_ca(reqwest::Client::builder()).unwrap_or_else(|error| { - tracing::warn!(error = %error, "failed to build OpenAI file upload client"); - reqwest::Client::new() - }) +fn build_reqwest_client( + http_client_factory: &HttpClientFactory, + url: &str, +) -> Result { + match http_client_factory.build_reqwest_client( + reqwest::Client::builder(), + url, + ClientRouteClass::Api, + ) { + Ok(client) => Ok(client), + Err(error) + if matches!( + http_client_factory.outbound_proxy_policy(), + OutboundProxyPolicy::ReqwestDefault + ) => + { + tracing::warn!(%error, "failed to build OpenAI file upload client"); + Ok(reqwest::Client::new()) + } + Err(source) => Err(OpenAiFileError::ClientBuild { + url: url.to_string(), + source, + }), + } } #[cfg(test)] @@ -254,6 +294,10 @@ mod tests { #[derive(Clone, Copy)] struct ChatGptTestAuth; + fn default_http_client_factory() -> HttpClientFactory { + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) + } + impl AuthProvider for ChatGptTestAuth { fn add_auth_headers(&self, headers: &mut reqwest::header::HeaderMap) { headers.insert( @@ -324,6 +368,7 @@ mod tests { let uploaded = upload_openai_file( &base_url, &chatgpt_auth(), + &default_http_client_factory(), "hello.txt".to_string(), /*file_size_bytes*/ 5, contents, diff --git a/codex-rs/core/src/mcp_openai_file.rs b/codex-rs/core/src/mcp_openai_file.rs index 5044568cd6..462b27ffd8 100644 --- a/codex-rs/core/src/mcp_openai_file.rs +++ b/codex-rs/core/src/mcp_openai_file.rs @@ -159,9 +159,11 @@ async fn build_uploaded_argument_value( .unwrap_or("file") .to_string(); let upload_auth = codex_model_provider::auth_provider_from_auth(auth); + let http_client_factory = turn_context.config.http_client_factory(); let uploaded = upload_openai_file( turn_context.config.chatgpt_base_url.trim_end_matches('/'), upload_auth.as_ref(), + &http_client_factory, file_name, metadata.size, contents, From 587b55a635779a163705fb3d91eda5873095f130 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:20 -0700 Subject: [PATCH 10/11] build: ratchet direct reqwest dependencies --- codex-rs/deny.toml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/codex-rs/deny.toml b/codex-rs/deny.toml index 4e52422f39..b15f7b2335 100644 --- a/codex-rs/deny.toml +++ b/codex-rs/deny.toml @@ -233,6 +233,39 @@ deny = [ "tonic", "zbus", ], reason = "first-party traits must use native async trait methods with explicit Send bounds" }, + # Migration ratchet: `codex-http-client` is the intended reqwest owner. Remove each temporary + # wrapper when that crate's direct reqwest dependency is migrated to the shared abstraction. + { crate = "reqwest", wrappers = [ + # Intended owner. + "codex-http-client", + # Temporary migration exceptions. + "codex-agent-identity", + "codex-api", + "codex-app-server", + "codex-app-server-daemon", + "codex-backend-client", + "codex-cloud-tasks", + "codex-core", + "codex-core-plugins", + "codex-exec-server", + "codex-lmstudio", + "codex-login", + "codex-ollama", + "codex-otel", + "codex-protocol", + "codex-responses-api-proxy", + "codex-rmcp-client", + "codex-tui", + "core_test_support", + # Third-party crates that own their reqwest integration. These are not part of the + # first-party migration count above. + "oauth2", + "opentelemetry-http", + "opentelemetry-otlp", + "rmcp", + "sentry", + "webrtc-sys-build", + ], reason = "new direct reqwest dependencies must use codex-http-client; temporary wrappers track migration debt" }, ] # List of features to allow/deny From 5628d32e265a4c00232f7bdc15e17a58c2352cd9 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 8 Jul 2026 14:06:20 -0700 Subject: [PATCH 11/11] login: use route-aware HTTP client abstraction --- codex-rs/Cargo.lock | 1 + codex-rs/http-client/src/outbound_proxy.rs | 11 +++++++++++ codex-rs/login/Cargo.toml | 1 + codex-rs/login/src/auth/default_client.rs | 12 ++++-------- codex-rs/login/src/auth/revoke.rs | 7 ++++++- codex-rs/login/src/device_code_auth.rs | 13 +++++++------ codex-rs/login/src/server.rs | 6 +++--- 7 files changed, 33 insertions(+), 18 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 3d98479749..55f67ca0d9 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3345,6 +3345,7 @@ dependencies = [ "codex-terminal-detection", "codex-utils-template", "core_test_support", + "http 1.4.0", "jsonwebtoken", "keyring", "once_cell", diff --git a/codex-rs/http-client/src/outbound_proxy.rs b/codex-rs/http-client/src/outbound_proxy.rs index 71793025ed..b8ad6fef95 100644 --- a/codex-rs/http-client/src/outbound_proxy.rs +++ b/codex-rs/http-client/src/outbound_proxy.rs @@ -15,6 +15,7 @@ use std::time::Instant; use crate::custom_ca::BuildCustomCaTransportError; use crate::custom_ca::build_reqwest_client_with_custom_ca; +use crate::default_client::HttpClient; #[cfg(any(target_os = "windows", target_os = "macos"))] use sha2::Digest; #[cfg(any(target_os = "windows", target_os = "macos"))] @@ -158,6 +159,16 @@ impl HttpClientFactory { ) } + /// Builds an HTTP client for a concrete outbound route. + pub fn build_client( + &self, + request_url: &str, + route_class: ClientRouteClass, + ) -> Result { + self.build_reqwest_client(reqwest::Client::builder(), request_url, route_class) + .map(HttpClient::new) + } + /// Builds a reqwest client for a concrete outbound route. pub fn build_reqwest_client( &self, diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 3eb253d7dc..9e4dd17722 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -20,6 +20,7 @@ codex-protocol = { workspace = true } codex-secrets = { workspace = true } codex-terminal-detection = { workspace = true } codex-utils-template = { workspace = true } +http = { workspace = true } once_cell = { workspace = true } os_info = { workspace = true } rand = { workspace = true } diff --git a/codex-rs/login/src/auth/default_client.rs b/codex-rs/login/src/auth/default_client.rs index 089e78340b..bf5f983429 100644 --- a/codex-rs/login/src/auth/default_client.rs +++ b/codex-rs/login/src/auth/default_client.rs @@ -273,16 +273,12 @@ fn default_reqwest_client_builder() -> reqwest::ClientBuilder { with_chatgpt_cloudflare_cookie_store(builder) } -/// Builds a raw reqwest client for an auth endpoint without Codex default headers. -pub(crate) fn build_raw_auth_reqwest_client( +/// Builds an HTTP client for an auth endpoint without Codex default headers. +pub(crate) fn create_raw_auth_client( endpoint: &str, auth_route_config: Option<&AuthRouteConfig>, -) -> Result { - auth_http_client_factory(auth_route_config).build_reqwest_client( - reqwest::Client::builder(), - endpoint, - ClientRouteClass::Auth, - ) +) -> Result { + auth_http_client_factory(auth_route_config).build_client(endpoint, ClientRouteClass::Auth) } /// Builds the default Codex reqwest client for an auth endpoint. diff --git a/codex-rs/login/src/auth/revoke.rs b/codex-rs/login/src/auth/revoke.rs index ca22adb571..6b2b21dcf8 100644 --- a/codex-rs/login/src/auth/revoke.rs +++ b/codex-rs/login/src/auth/revoke.rs @@ -155,6 +155,9 @@ fn derive_revoke_token_endpoint(refresh_endpoint: &str) -> Option { #[cfg(test)] mod tests { use super::*; + use codex_http_client::ClientRouteClass; + use codex_http_client::HttpClientFactory; + use codex_http_client::OutboundProxyPolicy; use core_test_support::skip_if_no_network; use wiremock::Mock; use wiremock::MockServer; @@ -181,8 +184,10 @@ mod tests { .mount(&server) .await; - let client = HttpClient::new(reqwest::Client::new()); let endpoint = format!("{}/oauth/revoke", server.uri()); + let client = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault) + .build_client(&endpoint, ClientRouteClass::Auth) + .expect("test HTTP client should build"); let error = revoke_oauth_token( &client, endpoint.as_str(), diff --git a/codex-rs/login/src/device_code_auth.rs b/codex-rs/login/src/device_code_auth.rs index 70e6dff225..e3bd34600c 100644 --- a/codex-rs/login/src/device_code_auth.rs +++ b/codex-rs/login/src/device_code_auth.rs @@ -1,4 +1,5 @@ -use reqwest::StatusCode; +use codex_http_client::HttpClient; +use http::StatusCode; use serde::Deserialize; use serde::Serialize; use serde::de::Deserializer; @@ -6,7 +7,7 @@ use serde::de::{self}; use std::time::Duration; use std::time::Instant; -use crate::default_client::build_raw_auth_reqwest_client; +use crate::default_client::create_raw_auth_client; use crate::pkce::PkceCodes; use crate::server::ServerOptions; use std::io; @@ -60,7 +61,7 @@ struct CodeSuccessResp { /// Request the user code and polling interval. async fn request_user_code( - client: &reqwest::Client, + client: &HttpClient, auth_base_url: &str, client_id: &str, ) -> std::io::Result { @@ -97,7 +98,7 @@ async fn request_user_code( /// Poll token endpoint until a code is issued or timeout occurs. async fn poll_for_token( - client: &reqwest::Client, + client: &HttpClient, auth_base_url: &str, device_auth_id: &str, user_code: &str, @@ -160,7 +161,7 @@ pub async fn request_device_code(opts: &ServerOptions) -> std::io::Result std::io::Result<()> { let base_url = opts.issuer.trim_end_matches('/'); - let client = build_raw_auth_reqwest_client(base_url, opts.auth_route_config.as_ref())?; + let client = create_raw_auth_client(base_url, opts.auth_route_config.as_ref())?; let api_base_url = format!("{base_url}/api/accounts"); let code_resp = poll_for_token( diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 01671bf0b1..804d05434e 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -27,7 +27,7 @@ use std::time::Duration; use crate::auth::AuthDotJson; use crate::auth::AuthKeyringBackendKind; use crate::auth::save_auth; -use crate::default_client::build_raw_auth_reqwest_client; +use crate::default_client::create_raw_auth_client; use crate::default_client::originator; use crate::outbound_proxy::AuthRouteConfig; use crate::pkce::PkceCodes; @@ -798,7 +798,7 @@ pub(crate) async fn exchange_code_for_tokens( // The route selected for the issuer is reused for token exchange; the token endpoint path is // not resolved separately. - let client = build_raw_auth_reqwest_client(issuer.trim_end_matches('/'), auth_route_config)?; + let client = create_raw_auth_client(issuer.trim_end_matches('/'), auth_route_config)?; let token_endpoint = format!("{}/oauth/token", issuer.trim_end_matches('/')); info!( issuer = %sanitize_url_for_logging(issuer), @@ -1120,7 +1120,7 @@ pub(crate) async fn obtain_api_key( access_token: String, } let token_endpoint = format!("{}/oauth/token", issuer.trim_end_matches('/')); - let client = build_raw_auth_reqwest_client(&token_endpoint, auth_route_config)?; + let client = create_raw_auth_client(&token_endpoint, auth_route_config)?; let resp = client .post(token_endpoint) .header("Content-Type", "application/x-www-form-urlencoded")