From 828b837235f0bf6adaf4f8648951bf60c722e86b Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Apr 2026 00:18:18 -0700 Subject: [PATCH 1/5] Extract tool registry planning into codex-tools (#16513) ## Why This is a larger step in the `codex-core` -> `codex-tools` migration called out in `AGENTS.md`. `codex-rs/core/src/tools/spec.rs` had become mostly pure tool-spec assembly plus handler registration. That made it hard to move more of the tool-definition layer into `codex-tools`, because the runtime binding and the crate-independent planning logic were still interleaved in one function. Splitting those concerns gives `codex-tools` ownership of the declarative registry plan while keeping `codex-core` responsible for instantiating concrete handlers. ## What Changed - Add a `codex-tools` registry-plan layer in `codex-rs/tools/src/tool_registry_plan.rs` and `codex-rs/tools/src/tool_registry_plan_types.rs`. - Move feature-gated tool-spec assembly, MCP/dynamic tool conversion, tool-search aliases, and code-mode nested-plan expansion into `codex-tools`. - Keep `codex-rs/core/src/tools/spec.rs` as the core-side adapter that maps each planned handler kind to concrete runtime handler instances. - Update `spec_tests.rs` to import the moved `codex_tools` symbols directly instead of relying on top-level `spec.rs` re-exports. This is intended to be a straight refactor with no behavior change and no new test surface. ## Verification - `cargo test -p codex-tools` - `cargo test -p codex-core tools::spec::tests` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/16513). * #16521 * __->__ #16513 --- codex-rs/core/src/tools/spec.rs | 674 ++++-------------- codex-rs/core/src/tools/spec_tests.rs | 13 + codex-rs/tools/src/lib.rs | 8 + codex-rs/tools/src/tool_registry_plan.rs | 488 +++++++++++++ .../tools/src/tool_registry_plan_types.rs | 118 +++ 5 files changed, 768 insertions(+), 533 deletions(-) create mode 100644 codex-rs/tools/src/tool_registry_plan.rs create mode 100644 codex-rs/tools/src/tool_registry_plan_types.rs diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 1a9db07084..86f4840a43 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -1,79 +1,23 @@ use crate::shell::Shell; use crate::shell::ShellType; -use crate::tools::code_mode::PUBLIC_TOOL_NAME; -use crate::tools::code_mode::WAIT_TOOL_NAME; use crate::tools::handlers::agent_jobs::BatchJobHandler; use crate::tools::handlers::multi_agents_common::DEFAULT_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS; use crate::tools::handlers::multi_agents_common::MIN_WAIT_TIMEOUT_MS; use crate::tools::registry::ToolRegistryBuilder; -use crate::tools::registry::tool_handler_key; use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::mcp_connection_manager::ToolInfo; use codex_protocol::dynamic_tools::DynamicToolSpec; -use codex_protocol::openai_models::ApplyPatchToolType; -use codex_protocol::openai_models::ConfigShellToolType; -use codex_tools::CommandToolOptions; use codex_tools::DiscoverableTool; -use codex_tools::REQUEST_USER_INPUT_TOOL_NAME; -use codex_tools::ShellToolOptions; -use codex_tools::SpawnAgentToolOptions; -use codex_tools::TOOL_SEARCH_DEFAULT_LIMIT; -use codex_tools::TOOL_SEARCH_TOOL_NAME; -use codex_tools::TOOL_SUGGEST_TOOL_NAME; -use codex_tools::ToolSearchAppSource; -use codex_tools::ToolSpec; +use codex_tools::ToolHandlerKind; +use codex_tools::ToolRegistryPlanAppTool; +use codex_tools::ToolRegistryPlanParams; use codex_tools::ToolUserShellType; use codex_tools::ToolsConfig; -use codex_tools::ViewImageToolOptions; use codex_tools::WaitAgentTimeoutOptions; -use codex_tools::WebSearchToolOptions; -use codex_tools::augment_tool_spec_for_code_mode; -use codex_tools::collect_code_mode_tool_definitions; -use codex_tools::collect_tool_search_app_infos; -use codex_tools::collect_tool_suggest_entries; -use codex_tools::create_apply_patch_freeform_tool; -use codex_tools::create_apply_patch_json_tool; -use codex_tools::create_assign_task_tool; -use codex_tools::create_close_agent_tool_v1; -use codex_tools::create_close_agent_tool_v2; -use codex_tools::create_code_mode_tool; -use codex_tools::create_exec_command_tool; -use codex_tools::create_image_generation_tool; -use codex_tools::create_js_repl_reset_tool; -use codex_tools::create_js_repl_tool; -use codex_tools::create_list_agents_tool; -use codex_tools::create_list_dir_tool; -use codex_tools::create_list_mcp_resource_templates_tool; -use codex_tools::create_list_mcp_resources_tool; -use codex_tools::create_local_shell_tool; -use codex_tools::create_read_mcp_resource_tool; -use codex_tools::create_report_agent_job_result_tool; -use codex_tools::create_request_permissions_tool; -use codex_tools::create_request_user_input_tool; -use codex_tools::create_resume_agent_tool; -use codex_tools::create_send_input_tool_v1; -use codex_tools::create_send_message_tool; -use codex_tools::create_shell_command_tool; -use codex_tools::create_shell_tool; -use codex_tools::create_spawn_agent_tool_v1; -use codex_tools::create_spawn_agent_tool_v2; -use codex_tools::create_spawn_agents_on_csv_tool; -use codex_tools::create_test_sync_tool; -use codex_tools::create_tool_search_tool; -use codex_tools::create_tool_suggest_tool; -use codex_tools::create_update_plan_tool; -use codex_tools::create_view_image_tool; -use codex_tools::create_wait_agent_tool_v1; -use codex_tools::create_wait_agent_tool_v2; -use codex_tools::create_wait_tool; -use codex_tools::create_web_search_tool; -use codex_tools::create_write_stdin_tool; -use codex_tools::dynamic_tool_to_responses_api_tool; -use codex_tools::mcp_tool_to_responses_api_tool; -use codex_tools::request_permissions_tool_description; -use codex_tools::request_user_input_tool_description; +use codex_tools::build_tool_registry_plan; use std::collections::HashMap; +use std::sync::Arc; #[cfg(test)] pub(crate) use codex_tools::mcp_call_tool_result_output_schema; @@ -88,32 +32,6 @@ pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType { } } -fn agent_type_description(config: &ToolsConfig) -> String { - if config.agent_type_description.is_empty() { - crate::agent::role::spawn_tool_spec::build(&std::collections::BTreeMap::new()) - } else { - config.agent_type_description.clone() - } -} - -fn push_tool_spec( - builder: &mut ToolRegistryBuilder, - spec: ToolSpec, - supports_parallel_tool_calls: bool, - code_mode_enabled: bool, -) { - let spec = if code_mode_enabled { - augment_tool_spec_for_code_mode(spec) - } else { - spec - }; - if supports_parallel_tool_calls { - builder.push_spec_with_parallel_support(spec, /*supports_parallel_tool_calls*/ true); - } else { - builder.push_spec(spec); - } -} - /// Builds the tool registry builder while collecting tool specs for later serialization. #[cfg(test)] pub(crate) fn build_specs( @@ -168,10 +86,38 @@ pub(crate) fn build_specs_with_discoverable_tools( use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2; use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2; use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2; - use std::sync::Arc; let mut builder = ToolRegistryBuilder::new(); - + let app_tool_sources = app_tools.as_ref().map(|app_tools| { + app_tools + .values() + .map(|tool| ToolRegistryPlanAppTool { + tool_name: tool.tool_name.as_str(), + tool_namespace: tool.tool_namespace.as_str(), + server_name: tool.server_name.as_str(), + connector_name: tool.connector_name.as_deref(), + connector_description: tool.connector_description.as_deref(), + }) + .collect::>() + }); + let default_agent_type_description = + crate::agent::role::spawn_tool_spec::build(&std::collections::BTreeMap::new()); + let plan = build_tool_registry_plan( + config, + ToolRegistryPlanParams { + mcp_tools: mcp_tools.as_ref(), + app_tools: app_tool_sources.as_deref(), + discoverable_tools: discoverable_tools.as_deref(), + dynamic_tools, + default_agent_type_description: &default_agent_type_description, + wait_agent_timeouts: WaitAgentTimeoutOptions { + default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, + min_timeout_ms: MIN_WAIT_TIMEOUT_MS, + max_timeout_ms: MAX_WAIT_TIMEOUT_MS, + }, + codex_apps_mcp_server_name: CODEX_APPS_MCP_SERVER_NAME, + }, + ); let shell_handler = Arc::new(ShellHandler); let unified_exec_handler = Arc::new(UnifiedExecHandler); let plan_handler = Arc::new(PlanHandler); @@ -185,468 +131,130 @@ pub(crate) fn build_specs_with_discoverable_tools( let request_user_input_handler = Arc::new(RequestUserInputHandler { default_mode_request_user_input: config.default_mode_request_user_input, }); + let mut tool_search_handler = None; let tool_suggest_handler = Arc::new(ToolSuggestHandler); let code_mode_handler = Arc::new(CodeModeExecuteHandler); let code_mode_wait_handler = Arc::new(CodeModeWaitHandler); let js_repl_handler = Arc::new(JsReplHandler); let js_repl_reset_handler = Arc::new(JsReplResetHandler); - let exec_permission_approvals_enabled = config.exec_permission_approvals_enabled; - if config.code_mode_enabled { - let nested_config = config.for_code_mode_nested_tools(); - let (nested_specs, _) = build_specs_with_discoverable_tools( - &nested_config, - mcp_tools.clone(), - app_tools.clone(), - /*discoverable_tools*/ None, - dynamic_tools, - ) - .build(); - let enabled_tools = collect_code_mode_tool_definitions( - nested_specs - .iter() - .map(|configured_tool| &configured_tool.spec), - ) - .into_iter() - .map(|tool| (tool.name, tool.description)) - .collect::>(); - push_tool_spec( - &mut builder, - create_code_mode_tool(&enabled_tools, config.code_mode_only_enabled), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler(PUBLIC_TOOL_NAME, code_mode_handler); - push_tool_spec( - &mut builder, - create_wait_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler(WAIT_TOOL_NAME, code_mode_wait_handler); - } - - match &config.shell_type { - ConfigShellToolType::Default => { - push_tool_spec( - &mut builder, - create_shell_tool(ShellToolOptions { - exec_permission_approvals_enabled, - }), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, + for spec in plan.specs { + if spec.supports_parallel_tool_calls { + builder.push_spec_with_parallel_support( + spec.spec, /*supports_parallel_tool_calls*/ true, ); - } - ConfigShellToolType::Local => { - push_tool_spec( - &mut builder, - create_local_shell_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - } - ConfigShellToolType::UnifiedExec => { - push_tool_spec( - &mut builder, - create_exec_command_tool(CommandToolOptions { - allow_login_shell: config.allow_login_shell, - exec_permission_approvals_enabled, - }), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_write_stdin_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("exec_command", unified_exec_handler.clone()); - builder.register_handler("write_stdin", unified_exec_handler); - } - ConfigShellToolType::Disabled => { - // Do nothing. - } - ConfigShellToolType::ShellCommand => { - push_tool_spec( - &mut builder, - create_shell_command_tool(CommandToolOptions { - allow_login_shell: config.allow_login_shell, - exec_permission_approvals_enabled, - }), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - } - } - - if config.shell_type != ConfigShellToolType::Disabled { - // Always register shell aliases so older prompts remain compatible. - builder.register_handler("shell", shell_handler.clone()); - builder.register_handler("container.exec", shell_handler.clone()); - builder.register_handler("local_shell", shell_handler); - builder.register_handler("shell_command", shell_command_handler); - } - - if mcp_tools.is_some() { - push_tool_spec( - &mut builder, - create_list_mcp_resources_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_list_mcp_resource_templates_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_read_mcp_resource_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - builder.register_handler("list_mcp_resources", mcp_resource_handler.clone()); - builder.register_handler("list_mcp_resource_templates", mcp_resource_handler.clone()); - builder.register_handler("read_mcp_resource", mcp_resource_handler); - } - - push_tool_spec( - &mut builder, - create_update_plan_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("update_plan", plan_handler); - - if config.js_repl_enabled { - push_tool_spec( - &mut builder, - create_js_repl_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_js_repl_reset_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("js_repl", js_repl_handler); - builder.register_handler("js_repl_reset", js_repl_reset_handler); - } - - if config.request_user_input { - push_tool_spec( - &mut builder, - create_request_user_input_tool(request_user_input_tool_description( - config.default_mode_request_user_input, - )), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler(REQUEST_USER_INPUT_TOOL_NAME, request_user_input_handler); - } - - if config.request_permissions_tool_enabled { - push_tool_spec( - &mut builder, - create_request_permissions_tool(request_permissions_tool_description()), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("request_permissions", request_permissions_handler); - } - - if config.search_tool - && let Some(app_tools) = app_tools - { - let search_tool_handler = Arc::new(ToolSearchHandler::new(app_tools.clone())); - let search_app_infos = collect_tool_search_app_infos( - app_tools.values().map(|tool| ToolSearchAppSource { - server_name: &tool.server_name, - connector_name: tool.connector_name.as_deref(), - connector_description: tool.connector_description.as_deref(), - }), - CODEX_APPS_MCP_SERVER_NAME, - ); - push_tool_spec( - &mut builder, - create_tool_search_tool(&search_app_infos, TOOL_SEARCH_DEFAULT_LIMIT), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - builder.register_handler(TOOL_SEARCH_TOOL_NAME, search_tool_handler); - - for tool in app_tools.values() { - let alias_name = - tool_handler_key(tool.tool_name.as_str(), Some(tool.tool_namespace.as_str())); - - builder.register_handler(alias_name, mcp_handler.clone()); - } - } - - if config.tool_suggest - && let Some(discoverable_tools) = discoverable_tools - .as_ref() - .filter(|tools| !tools.is_empty()) - { - builder.push_spec_with_parallel_support( - create_tool_suggest_tool(&collect_tool_suggest_entries(discoverable_tools)), - /*supports_parallel_tool_calls*/ true, - ); - builder.register_handler(TOOL_SUGGEST_TOOL_NAME, tool_suggest_handler); - } - - if let Some(apply_patch_tool_type) = &config.apply_patch_tool_type { - match apply_patch_tool_type { - ApplyPatchToolType::Freeform => { - push_tool_spec( - &mut builder, - create_apply_patch_freeform_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - } - ApplyPatchToolType::Function => { - push_tool_spec( - &mut builder, - create_apply_patch_json_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - } - } - builder.register_handler("apply_patch", apply_patch_handler); - } - - if config - .experimental_supported_tools - .iter() - .any(|tool| tool == "list_dir") - { - let list_dir_handler = Arc::new(ListDirHandler); - push_tool_spec( - &mut builder, - create_list_dir_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - builder.register_handler("list_dir", list_dir_handler); - } - - if config - .experimental_supported_tools - .contains(&"test_sync_tool".to_string()) - { - let test_sync_handler = Arc::new(TestSyncHandler); - push_tool_spec( - &mut builder, - create_test_sync_tool(), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - builder.register_handler("test_sync_tool", test_sync_handler); - } - - if let Some(web_search_tool) = create_web_search_tool(WebSearchToolOptions { - web_search_mode: config.web_search_mode, - web_search_config: config.web_search_config.as_ref(), - web_search_tool_type: config.web_search_tool_type, - }) { - push_tool_spec( - &mut builder, - web_search_tool, - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - } - - if config.image_gen_tool { - push_tool_spec( - &mut builder, - create_image_generation_tool("png"), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - } - - push_tool_spec( - &mut builder, - create_view_image_tool(ViewImageToolOptions { - can_request_original_image_detail: config.can_request_original_image_detail, - }), - /*supports_parallel_tool_calls*/ true, - config.code_mode_enabled, - ); - builder.register_handler("view_image", view_image_handler); - - if config.collab_tools { - if config.multi_agent_v2 { - let agent_type_description = agent_type_description(config); - push_tool_spec( - &mut builder, - create_spawn_agent_tool_v2(SpawnAgentToolOptions { - available_models: &config.available_models, - agent_type_description, - }), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_send_message_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_assign_task_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_wait_agent_tool_v2(WaitAgentTimeoutOptions { - default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, - min_timeout_ms: MIN_WAIT_TIMEOUT_MS, - max_timeout_ms: MAX_WAIT_TIMEOUT_MS, - }), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_close_agent_tool_v2(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_list_agents_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("spawn_agent", Arc::new(SpawnAgentHandlerV2)); - builder.register_handler("send_message", Arc::new(SendMessageHandlerV2)); - builder.register_handler("assign_task", Arc::new(AssignTaskHandlerV2)); - builder.register_handler("wait_agent", Arc::new(WaitAgentHandlerV2)); - builder.register_handler("close_agent", Arc::new(CloseAgentHandlerV2)); - builder.register_handler("list_agents", Arc::new(ListAgentsHandlerV2)); } else { - let agent_type_description = agent_type_description(config); - push_tool_spec( - &mut builder, - create_spawn_agent_tool_v1(SpawnAgentToolOptions { - available_models: &config.available_models, - agent_type_description, - }), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_send_input_tool_v1(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_resume_agent_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("resume_agent", Arc::new(ResumeAgentHandler)); - push_tool_spec( - &mut builder, - create_wait_agent_tool_v1(WaitAgentTimeoutOptions { - default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, - min_timeout_ms: MIN_WAIT_TIMEOUT_MS, - max_timeout_ms: MAX_WAIT_TIMEOUT_MS, - }), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - push_tool_spec( - &mut builder, - create_close_agent_tool_v1(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("spawn_agent", Arc::new(SpawnAgentHandler)); - builder.register_handler("send_input", Arc::new(SendInputHandler)); - builder.register_handler("wait_agent", Arc::new(WaitAgentHandler)); - builder.register_handler("close_agent", Arc::new(CloseAgentHandler)); + builder.push_spec(spec.spec); } } - if config.agent_jobs_tools { - let agent_jobs_handler = Arc::new(BatchJobHandler); - push_tool_spec( - &mut builder, - create_spawn_agents_on_csv_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("spawn_agents_on_csv", agent_jobs_handler.clone()); - if config.agent_jobs_worker_tools { - push_tool_spec( - &mut builder, - create_report_agent_job_result_tool(), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler("report_agent_job_result", agent_jobs_handler); - } - } - - if let Some(mcp_tools) = mcp_tools { - let mut entries: Vec<(String, rmcp::model::Tool)> = mcp_tools.into_iter().collect(); - entries.sort_by(|a, b| a.0.cmp(&b.0)); - - for (name, tool) in entries.into_iter() { - match mcp_tool_to_responses_api_tool(name.clone(), &tool) { - Ok(converted_tool) => { - push_tool_spec( - &mut builder, - ToolSpec::Function(converted_tool), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler(name, mcp_handler.clone()); + for handler in plan.handlers { + match handler.kind { + ToolHandlerKind::AgentJobs => { + builder.register_handler(handler.name, Arc::new(BatchJobHandler)); + } + ToolHandlerKind::ApplyPatch => { + builder.register_handler(handler.name, apply_patch_handler.clone()); + } + ToolHandlerKind::AssignTaskV2 => { + builder.register_handler(handler.name, Arc::new(AssignTaskHandlerV2)); + } + ToolHandlerKind::CloseAgentV1 => { + builder.register_handler(handler.name, Arc::new(CloseAgentHandler)); + } + ToolHandlerKind::CloseAgentV2 => { + builder.register_handler(handler.name, Arc::new(CloseAgentHandlerV2)); + } + ToolHandlerKind::CodeModeExecute => { + builder.register_handler(handler.name, code_mode_handler.clone()); + } + ToolHandlerKind::CodeModeWait => { + builder.register_handler(handler.name, code_mode_wait_handler.clone()); + } + ToolHandlerKind::DynamicTool => { + builder.register_handler(handler.name, dynamic_tool_handler.clone()); + } + ToolHandlerKind::JsRepl => { + builder.register_handler(handler.name, js_repl_handler.clone()); + } + ToolHandlerKind::JsReplReset => { + builder.register_handler(handler.name, js_repl_reset_handler.clone()); + } + ToolHandlerKind::ListAgentsV2 => { + builder.register_handler(handler.name, Arc::new(ListAgentsHandlerV2)); + } + ToolHandlerKind::ListDir => { + builder.register_handler(handler.name, Arc::new(ListDirHandler)); + } + ToolHandlerKind::Mcp => { + builder.register_handler(handler.name, mcp_handler.clone()); + } + ToolHandlerKind::McpResource => { + builder.register_handler(handler.name, mcp_resource_handler.clone()); + } + ToolHandlerKind::Plan => { + builder.register_handler(handler.name, plan_handler.clone()); + } + ToolHandlerKind::RequestPermissions => { + builder.register_handler(handler.name, request_permissions_handler.clone()); + } + ToolHandlerKind::RequestUserInput => { + builder.register_handler(handler.name, request_user_input_handler.clone()); + } + ToolHandlerKind::ResumeAgentV1 => { + builder.register_handler(handler.name, Arc::new(ResumeAgentHandler)); + } + ToolHandlerKind::SendInputV1 => { + builder.register_handler(handler.name, Arc::new(SendInputHandler)); + } + ToolHandlerKind::SendMessageV2 => { + builder.register_handler(handler.name, Arc::new(SendMessageHandlerV2)); + } + ToolHandlerKind::Shell => { + builder.register_handler(handler.name, shell_handler.clone()); + } + ToolHandlerKind::ShellCommand => { + builder.register_handler(handler.name, shell_command_handler.clone()); + } + ToolHandlerKind::SpawnAgentV1 => { + builder.register_handler(handler.name, Arc::new(SpawnAgentHandler)); + } + ToolHandlerKind::SpawnAgentV2 => { + builder.register_handler(handler.name, Arc::new(SpawnAgentHandlerV2)); + } + ToolHandlerKind::TestSync => { + builder.register_handler(handler.name, Arc::new(TestSyncHandler)); + } + ToolHandlerKind::ToolSearch => { + if tool_search_handler.is_none() { + tool_search_handler = app_tools + .as_ref() + .map(|app_tools| Arc::new(ToolSearchHandler::new(app_tools.clone()))); } - Err(e) => { - tracing::error!("Failed to convert {name:?} MCP tool to OpenAI tool: {e:?}"); + if let Some(tool_search_handler) = tool_search_handler.as_ref() { + builder.register_handler(handler.name, tool_search_handler.clone()); } } + ToolHandlerKind::ToolSuggest => { + builder.register_handler(handler.name, tool_suggest_handler.clone()); + } + ToolHandlerKind::UnifiedExec => { + builder.register_handler(handler.name, unified_exec_handler.clone()); + } + ToolHandlerKind::ViewImage => { + builder.register_handler(handler.name, view_image_handler.clone()); + } + ToolHandlerKind::WaitAgentV1 => { + builder.register_handler(handler.name, Arc::new(WaitAgentHandler)); + } + ToolHandlerKind::WaitAgentV2 => { + builder.register_handler(handler.name, Arc::new(WaitAgentHandlerV2)); + } } } - - if !dynamic_tools.is_empty() { - for tool in dynamic_tools { - match dynamic_tool_to_responses_api_tool(tool) { - Ok(converted_tool) => { - push_tool_spec( - &mut builder, - ToolSpec::Function(converted_tool), - /*supports_parallel_tool_calls*/ false, - config.code_mode_enabled, - ); - builder.register_handler(tool.name.clone(), dynamic_tool_handler.clone()); - } - Err(e) => { - tracing::error!( - "Failed to convert dynamic tool {:?} to OpenAI tool: {e:?}", - tool.name - ); - } - } - } - } - builder } + #[cfg(test)] #[path = "spec_tests.rs"] mod tests; diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index b4b68da25d..222d7e4c72 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -4,6 +4,7 @@ use crate::models_manager::model_info::with_config_overrides; use crate::shell::Shell; use crate::shell::ShellType; use crate::tools::ToolRouter; +use crate::tools::registry::tool_handler_key; use crate::tools::router::ToolRouterParams; use codex_app_server_protocol::AppInfo; use codex_features::Feature; @@ -13,6 +14,7 @@ use codex_protocol::config_types::WebSearchConfig; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::VIEW_IMAGE_TOOL_NAME; +use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; @@ -32,6 +34,9 @@ use codex_tools::ResponsesApiWebSearchFilters; use codex_tools::ResponsesApiWebSearchUserLocation; use codex_tools::ShellCommandBackendConfig; use codex_tools::SpawnAgentToolOptions; +use codex_tools::TOOL_SEARCH_TOOL_NAME; +use codex_tools::TOOL_SUGGEST_TOOL_NAME; +use codex_tools::ToolSpec; use codex_tools::ToolsConfig; use codex_tools::ToolsConfigParams; use codex_tools::UnifiedExecShellMode; @@ -203,6 +208,14 @@ fn spawn_agent_tool_options(config: &ToolsConfig) -> SpawnAgentToolOptions<'_> { } } +fn agent_type_description(config: &ToolsConfig) -> String { + if config.agent_type_description.is_empty() { + crate::agent::role::spawn_tool_spec::build(&BTreeMap::new()) + } else { + config.agent_type_description.clone() + } +} + fn wait_agent_timeout_options() -> WaitAgentTimeoutOptions { WaitAgentTimeoutOptions { default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, diff --git a/codex-rs/tools/src/lib.rs b/codex-rs/tools/src/lib.rs index 3bce0fb107..91931e8944 100644 --- a/codex-rs/tools/src/lib.rs +++ b/codex-rs/tools/src/lib.rs @@ -18,6 +18,8 @@ mod responses_api; mod tool_config; mod tool_definition; mod tool_discovery; +mod tool_registry_plan; +mod tool_registry_plan_types; mod tool_spec; mod tool_suggest; mod utility_tool; @@ -107,6 +109,12 @@ pub use tool_discovery::collect_tool_suggest_entries; pub use tool_discovery::create_tool_search_tool; pub use tool_discovery::create_tool_suggest_tool; pub use tool_discovery::filter_tool_suggest_discoverable_tools_for_client; +pub use tool_registry_plan::build_tool_registry_plan; +pub use tool_registry_plan_types::ToolHandlerKind; +pub use tool_registry_plan_types::ToolHandlerSpec; +pub use tool_registry_plan_types::ToolRegistryPlan; +pub use tool_registry_plan_types::ToolRegistryPlanAppTool; +pub use tool_registry_plan_types::ToolRegistryPlanParams; pub use tool_spec::ConfiguredToolSpec; pub use tool_spec::ResponsesApiWebSearchFilters; pub use tool_spec::ResponsesApiWebSearchUserLocation; diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs new file mode 100644 index 0000000000..01cda5d64e --- /dev/null +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -0,0 +1,488 @@ +use crate::CommandToolOptions; +use crate::REQUEST_USER_INPUT_TOOL_NAME; +use crate::ShellToolOptions; +use crate::SpawnAgentToolOptions; +use crate::TOOL_SEARCH_DEFAULT_LIMIT; +use crate::TOOL_SEARCH_TOOL_NAME; +use crate::TOOL_SUGGEST_TOOL_NAME; +use crate::ToolHandlerKind; +use crate::ToolRegistryPlan; +use crate::ToolRegistryPlanParams; +use crate::ToolSearchAppSource; +use crate::ToolSpec; +use crate::ToolsConfig; +use crate::ViewImageToolOptions; +use crate::WebSearchToolOptions; +use crate::collect_code_mode_tool_definitions; +use crate::collect_tool_search_app_infos; +use crate::collect_tool_suggest_entries; +use crate::create_apply_patch_freeform_tool; +use crate::create_apply_patch_json_tool; +use crate::create_assign_task_tool; +use crate::create_close_agent_tool_v1; +use crate::create_close_agent_tool_v2; +use crate::create_code_mode_tool; +use crate::create_exec_command_tool; +use crate::create_image_generation_tool; +use crate::create_js_repl_reset_tool; +use crate::create_js_repl_tool; +use crate::create_list_agents_tool; +use crate::create_list_dir_tool; +use crate::create_list_mcp_resource_templates_tool; +use crate::create_list_mcp_resources_tool; +use crate::create_local_shell_tool; +use crate::create_read_mcp_resource_tool; +use crate::create_report_agent_job_result_tool; +use crate::create_request_permissions_tool; +use crate::create_request_user_input_tool; +use crate::create_resume_agent_tool; +use crate::create_send_input_tool_v1; +use crate::create_send_message_tool; +use crate::create_shell_command_tool; +use crate::create_shell_tool; +use crate::create_spawn_agent_tool_v1; +use crate::create_spawn_agent_tool_v2; +use crate::create_spawn_agents_on_csv_tool; +use crate::create_test_sync_tool; +use crate::create_tool_search_tool; +use crate::create_tool_suggest_tool; +use crate::create_update_plan_tool; +use crate::create_view_image_tool; +use crate::create_wait_agent_tool_v1; +use crate::create_wait_agent_tool_v2; +use crate::create_wait_tool; +use crate::create_web_search_tool; +use crate::create_write_stdin_tool; +use crate::dynamic_tool_to_responses_api_tool; +use crate::mcp_tool_to_responses_api_tool; +use crate::request_permissions_tool_description; +use crate::request_user_input_tool_description; +use crate::tool_registry_plan_types::agent_type_description; +use codex_protocol::openai_models::ApplyPatchToolType; +use codex_protocol::openai_models::ConfigShellToolType; +use rmcp::model::Tool as McpTool; + +pub fn build_tool_registry_plan( + config: &ToolsConfig, + params: ToolRegistryPlanParams<'_>, +) -> ToolRegistryPlan { + let mut plan = ToolRegistryPlan::new(); + let exec_permission_approvals_enabled = config.exec_permission_approvals_enabled; + + if config.code_mode_enabled { + let nested_config = config.for_code_mode_nested_tools(); + let nested_plan = build_tool_registry_plan( + &nested_config, + ToolRegistryPlanParams { + discoverable_tools: None, + ..params + }, + ); + let enabled_tools = collect_code_mode_tool_definitions( + nested_plan + .specs + .iter() + .map(|configured_tool| &configured_tool.spec), + ) + .into_iter() + .map(|tool| (tool.name, tool.description)) + .collect::>(); + plan.push_spec( + create_code_mode_tool(&enabled_tools, config.code_mode_only_enabled), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler( + codex_code_mode::PUBLIC_TOOL_NAME, + ToolHandlerKind::CodeModeExecute, + ); + plan.push_spec( + create_wait_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler( + codex_code_mode::WAIT_TOOL_NAME, + ToolHandlerKind::CodeModeWait, + ); + } + + match &config.shell_type { + ConfigShellToolType::Default => { + plan.push_spec( + create_shell_tool(ShellToolOptions { + exec_permission_approvals_enabled, + }), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + } + ConfigShellToolType::Local => { + plan.push_spec( + create_local_shell_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + } + ConfigShellToolType::UnifiedExec => { + plan.push_spec( + create_exec_command_tool(CommandToolOptions { + allow_login_shell: config.allow_login_shell, + exec_permission_approvals_enabled, + }), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.push_spec( + create_write_stdin_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("exec_command", ToolHandlerKind::UnifiedExec); + plan.register_handler("write_stdin", ToolHandlerKind::UnifiedExec); + } + ConfigShellToolType::Disabled => {} + ConfigShellToolType::ShellCommand => { + plan.push_spec( + create_shell_command_tool(CommandToolOptions { + allow_login_shell: config.allow_login_shell, + exec_permission_approvals_enabled, + }), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + } + } + + if config.shell_type != ConfigShellToolType::Disabled { + plan.register_handler("shell", ToolHandlerKind::Shell); + plan.register_handler("container.exec", ToolHandlerKind::Shell); + plan.register_handler("local_shell", ToolHandlerKind::Shell); + plan.register_handler("shell_command", ToolHandlerKind::ShellCommand); + } + + if params.mcp_tools.is_some() { + plan.push_spec( + create_list_mcp_resources_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.push_spec( + create_list_mcp_resource_templates_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.push_spec( + create_read_mcp_resource_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.register_handler("list_mcp_resources", ToolHandlerKind::McpResource); + plan.register_handler("list_mcp_resource_templates", ToolHandlerKind::McpResource); + plan.register_handler("read_mcp_resource", ToolHandlerKind::McpResource); + } + + plan.push_spec( + create_update_plan_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("update_plan", ToolHandlerKind::Plan); + + if config.js_repl_enabled { + plan.push_spec( + create_js_repl_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_js_repl_reset_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("js_repl", ToolHandlerKind::JsRepl); + plan.register_handler("js_repl_reset", ToolHandlerKind::JsReplReset); + } + + if config.request_user_input { + plan.push_spec( + create_request_user_input_tool(request_user_input_tool_description( + config.default_mode_request_user_input, + )), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler( + REQUEST_USER_INPUT_TOOL_NAME, + ToolHandlerKind::RequestUserInput, + ); + } + + if config.request_permissions_tool_enabled { + plan.push_spec( + create_request_permissions_tool(request_permissions_tool_description()), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("request_permissions", ToolHandlerKind::RequestPermissions); + } + + if config.search_tool + && let Some(app_tools) = params.app_tools + { + let search_app_infos = collect_tool_search_app_infos( + app_tools.iter().map(|tool| ToolSearchAppSource { + server_name: tool.server_name, + connector_name: tool.connector_name, + connector_description: tool.connector_description, + }), + params.codex_apps_mcp_server_name, + ); + plan.push_spec( + create_tool_search_tool(&search_app_infos, TOOL_SEARCH_DEFAULT_LIMIT), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.register_handler(TOOL_SEARCH_TOOL_NAME, ToolHandlerKind::ToolSearch); + + for tool in app_tools { + plan.register_handler( + format!("{}:{}", tool.tool_namespace, tool.tool_name), + ToolHandlerKind::Mcp, + ); + } + } + + if config.tool_suggest + && let Some(discoverable_tools) = + params.discoverable_tools.filter(|tools| !tools.is_empty()) + { + plan.push_spec( + create_tool_suggest_tool(&collect_tool_suggest_entries(discoverable_tools)), + /*supports_parallel_tool_calls*/ true, + /*code_mode_enabled*/ false, + ); + plan.register_handler(TOOL_SUGGEST_TOOL_NAME, ToolHandlerKind::ToolSuggest); + } + + if let Some(apply_patch_tool_type) = &config.apply_patch_tool_type { + match apply_patch_tool_type { + ApplyPatchToolType::Freeform => { + plan.push_spec( + create_apply_patch_freeform_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + } + ApplyPatchToolType::Function => { + plan.push_spec( + create_apply_patch_json_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + } + } + plan.register_handler("apply_patch", ToolHandlerKind::ApplyPatch); + } + + if config + .experimental_supported_tools + .iter() + .any(|tool| tool == "list_dir") + { + plan.push_spec( + create_list_dir_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.register_handler("list_dir", ToolHandlerKind::ListDir); + } + + if config + .experimental_supported_tools + .iter() + .any(|tool| tool == "test_sync_tool") + { + plan.push_spec( + create_test_sync_tool(), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.register_handler("test_sync_tool", ToolHandlerKind::TestSync); + } + + if let Some(web_search_tool) = create_web_search_tool(WebSearchToolOptions { + web_search_mode: config.web_search_mode, + web_search_config: config.web_search_config.as_ref(), + web_search_tool_type: config.web_search_tool_type, + }) { + plan.push_spec( + web_search_tool, + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + } + + if config.image_gen_tool { + plan.push_spec( + create_image_generation_tool("png"), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + } + + plan.push_spec( + create_view_image_tool(ViewImageToolOptions { + can_request_original_image_detail: config.can_request_original_image_detail, + }), + /*supports_parallel_tool_calls*/ true, + config.code_mode_enabled, + ); + plan.register_handler("view_image", ToolHandlerKind::ViewImage); + + if config.collab_tools { + if config.multi_agent_v2 { + let agent_type_description = + agent_type_description(config, params.default_agent_type_description); + plan.push_spec( + create_spawn_agent_tool_v2(SpawnAgentToolOptions { + available_models: &config.available_models, + agent_type_description, + }), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_send_message_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_assign_task_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_wait_agent_tool_v2(params.wait_agent_timeouts), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_close_agent_tool_v2(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_list_agents_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV2); + plan.register_handler("send_message", ToolHandlerKind::SendMessageV2); + plan.register_handler("assign_task", ToolHandlerKind::AssignTaskV2); + plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV2); + plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV2); + plan.register_handler("list_agents", ToolHandlerKind::ListAgentsV2); + } else { + let agent_type_description = + agent_type_description(config, params.default_agent_type_description); + plan.push_spec( + create_spawn_agent_tool_v1(SpawnAgentToolOptions { + available_models: &config.available_models, + agent_type_description, + }), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_send_input_tool_v1(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_resume_agent_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("resume_agent", ToolHandlerKind::ResumeAgentV1); + plan.push_spec( + create_wait_agent_tool_v1(params.wait_agent_timeouts), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.push_spec( + create_close_agent_tool_v1(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("spawn_agent", ToolHandlerKind::SpawnAgentV1); + plan.register_handler("send_input", ToolHandlerKind::SendInputV1); + plan.register_handler("wait_agent", ToolHandlerKind::WaitAgentV1); + plan.register_handler("close_agent", ToolHandlerKind::CloseAgentV1); + } + } + + if config.agent_jobs_tools { + plan.push_spec( + create_spawn_agents_on_csv_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("spawn_agents_on_csv", ToolHandlerKind::AgentJobs); + if config.agent_jobs_worker_tools { + plan.push_spec( + create_report_agent_job_result_tool(), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler("report_agent_job_result", ToolHandlerKind::AgentJobs); + } + } + + if let Some(mcp_tools) = params.mcp_tools { + let mut entries: Vec<(String, &McpTool)> = mcp_tools + .iter() + .map(|(name, tool)| (name.clone(), tool)) + .collect(); + entries.sort_by(|left, right| left.0.cmp(&right.0)); + + for (name, tool) in entries { + match mcp_tool_to_responses_api_tool(name.clone(), tool) { + Ok(converted_tool) => { + plan.push_spec( + ToolSpec::Function(converted_tool), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler(name, ToolHandlerKind::Mcp); + } + Err(error) => { + tracing::error!( + "Failed to convert {name:?} MCP tool to OpenAI tool: {error:?}" + ); + } + } + } + } + + for tool in params.dynamic_tools { + match dynamic_tool_to_responses_api_tool(tool) { + Ok(converted_tool) => { + plan.push_spec( + ToolSpec::Function(converted_tool), + /*supports_parallel_tool_calls*/ false, + config.code_mode_enabled, + ); + plan.register_handler(tool.name.clone(), ToolHandlerKind::DynamicTool); + } + Err(error) => { + tracing::error!( + "Failed to convert dynamic tool {:?} to OpenAI tool: {error:?}", + tool.name + ); + } + } + } + + plan +} diff --git a/codex-rs/tools/src/tool_registry_plan_types.rs b/codex-rs/tools/src/tool_registry_plan_types.rs new file mode 100644 index 0000000000..bdcb75acd8 --- /dev/null +++ b/codex-rs/tools/src/tool_registry_plan_types.rs @@ -0,0 +1,118 @@ +use crate::ConfiguredToolSpec; +use crate::DiscoverableTool; +use crate::ToolSpec; +use crate::ToolsConfig; +use crate::WaitAgentTimeoutOptions; +use crate::augment_tool_spec_for_code_mode; +use codex_protocol::dynamic_tools::DynamicToolSpec; +use rmcp::model::Tool as McpTool; +use std::collections::HashMap; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ToolHandlerKind { + AgentJobs, + ApplyPatch, + AssignTaskV2, + CloseAgentV1, + CloseAgentV2, + CodeModeExecute, + CodeModeWait, + DynamicTool, + JsRepl, + JsReplReset, + ListAgentsV2, + ListDir, + Mcp, + McpResource, + Plan, + RequestPermissions, + RequestUserInput, + ResumeAgentV1, + SendInputV1, + SendMessageV2, + Shell, + ShellCommand, + SpawnAgentV1, + SpawnAgentV2, + TestSync, + ToolSearch, + ToolSuggest, + UnifiedExec, + ViewImage, + WaitAgentV1, + WaitAgentV2, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolHandlerSpec { + pub name: String, + pub kind: ToolHandlerKind, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ToolRegistryPlan { + pub specs: Vec, + pub handlers: Vec, +} + +#[derive(Debug, Clone, Copy)] +pub struct ToolRegistryPlanParams<'a> { + pub mcp_tools: Option<&'a HashMap>, + pub app_tools: Option<&'a [ToolRegistryPlanAppTool<'a>]>, + pub discoverable_tools: Option<&'a [DiscoverableTool]>, + pub dynamic_tools: &'a [DynamicToolSpec], + pub default_agent_type_description: &'a str, + pub wait_agent_timeouts: WaitAgentTimeoutOptions, + pub codex_apps_mcp_server_name: &'a str, +} + +#[derive(Debug, Clone, Copy)] +pub struct ToolRegistryPlanAppTool<'a> { + pub tool_name: &'a str, + pub tool_namespace: &'a str, + pub server_name: &'a str, + pub connector_name: Option<&'a str>, + pub connector_description: Option<&'a str>, +} + +impl ToolRegistryPlan { + pub(crate) fn new() -> Self { + Self { + specs: Vec::new(), + handlers: Vec::new(), + } + } + + pub(crate) fn push_spec( + &mut self, + spec: ToolSpec, + supports_parallel_tool_calls: bool, + code_mode_enabled: bool, + ) { + let spec = if code_mode_enabled { + augment_tool_spec_for_code_mode(spec) + } else { + spec + }; + self.specs + .push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls)); + } + + pub(crate) fn register_handler(&mut self, name: impl Into, kind: ToolHandlerKind) { + self.handlers.push(ToolHandlerSpec { + name: name.into(), + kind, + }); + } +} + +pub(crate) fn agent_type_description( + config: &ToolsConfig, + default_agent_type_description: &str, +) -> String { + if config.agent_type_description.is_empty() { + default_agent_type_description.to_string() + } else { + config.agent_type_description.clone() + } +} From 5131e0de4524d28f3e9bd848de035b557c21eeff Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Apr 2026 00:26:51 -0700 Subject: [PATCH 2/5] Move tool registry plan tests into codex-tools (#16521) ## Why #16513 moved pure tool-registry planning into `codex-tools`, but much of the corresponding spec/feature-gating coverage still lived in `codex-core`. That leaves the tests for planner behavior in the crate that no longer owns that logic and makes the next extraction steps harder to review. ## What Move the planner-only `spec_tests.rs` coverage into `codex-rs/tools/src/tool_registry_plan_tests.rs` and wire it up from `codex-rs/tools/src/tool_registry_plan.rs` using the crate-local `#[path = "tool_registry_plan_tests.rs"] mod tests;` pattern. The `codex-core` test file now keeps the core-side integration checks: router-visible model tool lists, namespaced handler alias registration, shell adapter behavior, and MCP schema edge cases that still exercise the `core` binding layer. ## Verification - `cargo test -p codex-tools` - `cargo test -p codex-core tools::spec::tests` --- codex-rs/core/src/tools/spec_tests.rs | 1848 ---------------- codex-rs/tools/src/tool_registry_plan.rs | 4 + .../tools/src/tool_registry_plan_tests.rs | 1878 +++++++++++++++++ 3 files changed, 1882 insertions(+), 1848 deletions(-) create mode 100644 codex-rs/tools/src/tool_registry_plan_tests.rs diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index 222d7e4c72..61cb494679 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -10,61 +10,28 @@ use codex_app_server_protocol::AppInfo; use codex_features::Feature; use codex_features::Features; use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; -use codex_protocol::config_types::WebSearchConfig; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; -use codex_protocol::models::VIEW_IMAGE_TOOL_NAME; use codex_protocol::openai_models::ConfigShellToolType; -use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::ModelInfo; use codex_protocol::openai_models::ModelsResponse; -use codex_protocol::openai_models::WebSearchToolType; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_tools::AdditionalProperties; -use codex_tools::CommandToolOptions; use codex_tools::ConfiguredToolSpec; -use codex_tools::DiscoverablePluginInfo; use codex_tools::DiscoverableTool; -use codex_tools::FreeformTool; use codex_tools::JsonSchema; use codex_tools::ResponsesApiTool; -use codex_tools::ResponsesApiWebSearchFilters; -use codex_tools::ResponsesApiWebSearchUserLocation; use codex_tools::ShellCommandBackendConfig; -use codex_tools::SpawnAgentToolOptions; use codex_tools::TOOL_SEARCH_TOOL_NAME; use codex_tools::TOOL_SUGGEST_TOOL_NAME; use codex_tools::ToolSpec; use codex_tools::ToolsConfig; use codex_tools::ToolsConfigParams; use codex_tools::UnifiedExecShellMode; -use codex_tools::ViewImageToolOptions; -use codex_tools::WaitAgentTimeoutOptions; use codex_tools::ZshForkConfig; -use codex_tools::create_apply_patch_freeform_tool; -use codex_tools::create_close_agent_tool_v1; -use codex_tools::create_close_agent_tool_v2; -use codex_tools::create_exec_command_tool; -use codex_tools::create_request_permissions_tool; -use codex_tools::create_request_user_input_tool; -use codex_tools::create_resume_agent_tool; -use codex_tools::create_send_input_tool_v1; -use codex_tools::create_send_message_tool; -use codex_tools::create_spawn_agent_tool_v1; -use codex_tools::create_spawn_agent_tool_v2; -use codex_tools::create_update_plan_tool; -use codex_tools::create_view_image_tool; -use codex_tools::create_wait_agent_tool_v1; -use codex_tools::create_wait_agent_tool_v2; -use codex_tools::create_write_stdin_tool; use codex_tools::mcp_tool_to_deferred_responses_api_tool; -use codex_tools::request_permissions_tool_description; -use codex_tools::request_user_input_tool_description; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; -use serde_json::json; use std::collections::BTreeMap; use std::path::PathBuf; @@ -174,17 +141,6 @@ fn assert_contains_tool_names(tools: &[ConfiguredToolSpec], expected_subset: &[& } } -fn assert_lacks_tool_name(tools: &[ConfiguredToolSpec], expected_absent: &str) { - let names = tools - .iter() - .map(ConfiguredToolSpec::name) - .collect::>(); - assert!( - !names.contains(&expected_absent), - "expected tool {expected_absent} to be absent; had: {names:?}" - ); -} - fn shell_tool_name(config: &ToolsConfig) -> Option<&'static str> { match config.shell_type { ConfigShellToolType::Default => Some("shell"), @@ -195,35 +151,6 @@ fn shell_tool_name(config: &ToolsConfig) -> Option<&'static str> { } } -fn request_user_input_tool_spec(default_mode_request_user_input: bool) -> ToolSpec { - create_request_user_input_tool(request_user_input_tool_description( - default_mode_request_user_input, - )) -} - -fn spawn_agent_tool_options(config: &ToolsConfig) -> SpawnAgentToolOptions<'_> { - SpawnAgentToolOptions { - available_models: &config.available_models, - agent_type_description: agent_type_description(config), - } -} - -fn agent_type_description(config: &ToolsConfig) -> String { - if config.agent_type_description.is_empty() { - crate::agent::role::spawn_tool_spec::build(&BTreeMap::new()) - } else { - config.agent_type_description.clone() - } -} - -fn wait_agent_timeout_options() -> WaitAgentTimeoutOptions { - WaitAgentTimeoutOptions { - default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, - min_timeout_ms: MIN_WAIT_TIMEOUT_MS, - max_timeout_ms: MAX_WAIT_TIMEOUT_MS, - } -} - fn find_tool<'a>(tools: &'a [ConfiguredToolSpec], expected_name: &str) -> &'a ConfiguredToolSpec { tools .iter() @@ -231,45 +158,6 @@ fn find_tool<'a>(tools: &'a [ConfiguredToolSpec], expected_name: &str) -> &'a Co .unwrap_or_else(|| panic!("expected tool {expected_name}")) } -fn strip_descriptions_schema(schema: &mut JsonSchema) { - match schema { - JsonSchema::Boolean { description } - | JsonSchema::String { description } - | JsonSchema::Number { description } => { - *description = None; - } - JsonSchema::Array { items, description } => { - strip_descriptions_schema(items); - *description = None; - } - JsonSchema::Object { - properties, - required: _, - additional_properties, - } => { - for v in properties.values_mut() { - strip_descriptions_schema(v); - } - if let Some(AdditionalProperties::Schema(s)) = additional_properties { - strip_descriptions_schema(s); - } - } - } -} - -fn strip_descriptions_tool(spec: &mut ToolSpec) { - match spec { - ToolSpec::ToolSearch { parameters, .. } => strip_descriptions_schema(parameters), - ToolSpec::Function(ResponsesApiTool { parameters, .. }) => { - strip_descriptions_schema(parameters); - } - ToolSpec::Freeform(_) - | ToolSpec::LocalShell {} - | ToolSpec::ImageGeneration { .. } - | ToolSpec::WebSearch { .. } => {} - } -} - fn model_info_from_models_json(slug: &str) -> ModelInfo { let config = test_config(); let response: ModelsResponse = @@ -306,607 +194,6 @@ fn model_provided_unified_exec_is_blocked_for_windows_sandboxed_policies() { assert_eq!(config.shell_type, expected_shell_type); } -#[test] -fn test_full_toolset_specs_for_gpt5_codex_unified_exec_web_search() { - let model_info = model_info_from_models_json("gpt-5-codex"); - let mut features = Features::with_defaults(); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Live), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - // Build actual map name -> spec - use std::collections::BTreeMap; - use std::collections::HashSet; - let mut actual: BTreeMap = BTreeMap::from([]); - let mut duplicate_names = Vec::new(); - for t in &tools { - let name = t.name().to_string(); - if actual.insert(name.clone(), t.spec.clone()).is_some() { - duplicate_names.push(name); - } - } - assert!( - duplicate_names.is_empty(), - "duplicate tool entries detected: {duplicate_names:?}" - ); - - // Build expected from the same helpers used by the builder. - let mut expected: BTreeMap = BTreeMap::from([]); - for spec in [ - create_exec_command_tool(CommandToolOptions { - allow_login_shell: true, - exec_permission_approvals_enabled: false, - }), - create_write_stdin_tool(), - create_update_plan_tool(), - request_user_input_tool_spec(/*default_mode_request_user_input*/ false), - create_apply_patch_freeform_tool(), - ToolSpec::WebSearch { - external_web_access: Some(true), - filters: None, - user_location: None, - search_context_size: None, - search_content_types: None, - }, - create_view_image_tool(ViewImageToolOptions { - can_request_original_image_detail: config.can_request_original_image_detail, - }), - ] { - expected.insert(spec.name().to_string(), spec); - } - let collab_specs = if config.multi_agent_v2 { - vec![ - create_spawn_agent_tool_v2(spawn_agent_tool_options(&config)), - create_send_message_tool(), - create_wait_agent_tool_v2(wait_agent_timeout_options()), - create_close_agent_tool_v2(), - ] - } else { - vec![ - create_spawn_agent_tool_v1(spawn_agent_tool_options(&config)), - create_send_input_tool_v1(), - create_wait_agent_tool_v1(wait_agent_timeout_options()), - create_close_agent_tool_v1(), - ] - }; - for spec in collab_specs { - expected.insert(spec.name().to_string(), spec); - } - if !config.multi_agent_v2 { - let spec = create_resume_agent_tool(); - expected.insert(spec.name().to_string(), spec); - } - - if config.exec_permission_approvals_enabled { - let spec = create_request_permissions_tool(request_permissions_tool_description()); - expected.insert(spec.name().to_string(), spec); - } - - // Exact name set match — this is the only test allowed to fail when tools change. - let actual_names: HashSet<_> = actual.keys().cloned().collect(); - let expected_names: HashSet<_> = expected.keys().cloned().collect(); - assert_eq!(actual_names, expected_names, "tool name set mismatch"); - - // Compare specs ignoring human-readable descriptions. - for name in expected.keys() { - let mut a = actual.get(name).expect("present").clone(); - let mut e = expected.get(name).expect("present").clone(); - strip_descriptions_tool(&mut a); - strip_descriptions_tool(&mut e); - assert_eq!(a, e, "spec mismatch for {name}"); - } -} - -#[test] -fn test_build_specs_collab_tools_enabled() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::Collab); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names( - &tools, - &["spawn_agent", "send_input", "wait_agent", "close_agent"], - ); - assert_lacks_tool_name(&tools, "spawn_agents_on_csv"); - assert_lacks_tool_name(&tools, "list_agents"); - - let spawn_agent = find_tool(&tools, "spawn_agent"); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &spawn_agent.spec else { - panic!("spawn_agent should be a function tool"); - }; - let JsonSchema::Object { properties, .. } = parameters else { - panic!("spawn_agent should use object params"); - }; - assert!(properties.contains_key("fork_context")); - assert!(!properties.contains_key("fork_turns")); -} - -#[test] -fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::Collab); - features.enable(Feature::MultiAgentV2); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names( - &tools, - &[ - "spawn_agent", - "send_message", - "assign_task", - "wait_agent", - "close_agent", - "list_agents", - ], - ); - - let spawn_agent = find_tool(&tools, "spawn_agent"); - let ToolSpec::Function(ResponsesApiTool { - parameters, - output_schema, - .. - }) = &spawn_agent.spec - else { - panic!("spawn_agent should be a function tool"); - }; - let JsonSchema::Object { - properties, - required, - .. - } = parameters - else { - panic!("spawn_agent should use object params"); - }; - assert!(properties.contains_key("task_name")); - assert!(properties.contains_key("message")); - assert!(properties.contains_key("fork_turns")); - assert!(!properties.contains_key("items")); - assert!(!properties.contains_key("fork_context")); - assert_eq!( - required.as_ref(), - Some(&vec!["task_name".to_string(), "message".to_string()]) - ); - let output_schema = output_schema - .as_ref() - .expect("spawn_agent should define output schema"); - assert_eq!( - output_schema["required"], - json!(["agent_id", "task_name", "nickname"]) - ); - - let send_message = find_tool(&tools, "send_message"); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &send_message.spec else { - panic!("send_message should be a function tool"); - }; - let JsonSchema::Object { - properties, - required, - .. - } = parameters - else { - panic!("send_message should use object params"); - }; - assert!(properties.contains_key("target")); - assert!(!properties.contains_key("interrupt")); - assert!(properties.contains_key("message")); - assert!(!properties.contains_key("items")); - assert_eq!( - required.as_ref(), - Some(&vec!["target".to_string(), "message".to_string()]) - ); - - let assign_task = find_tool(&tools, "assign_task"); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &assign_task.spec else { - panic!("assign_task should be a function tool"); - }; - let JsonSchema::Object { - properties, - required, - .. - } = parameters - else { - panic!("assign_task should use object params"); - }; - assert!(properties.contains_key("target")); - assert!(properties.contains_key("message")); - assert!(!properties.contains_key("items")); - assert_eq!( - required.as_ref(), - Some(&vec!["target".to_string(), "message".to_string()]) - ); - - let wait_agent = find_tool(&tools, "wait_agent"); - let ToolSpec::Function(ResponsesApiTool { - parameters, - output_schema, - .. - }) = &wait_agent.spec - else { - panic!("wait_agent should be a function tool"); - }; - let JsonSchema::Object { - properties, - required, - .. - } = parameters - else { - panic!("wait_agent should use object params"); - }; - assert!(!properties.contains_key("targets")); - assert!(properties.contains_key("timeout_ms")); - assert_eq!(required, &None); - let output_schema = output_schema - .as_ref() - .expect("wait_agent should define output schema"); - assert_eq!( - output_schema["properties"]["message"]["description"], - json!("Brief wait summary without the agent's final content.") - ); - - let list_agents = find_tool(&tools, "list_agents"); - let ToolSpec::Function(ResponsesApiTool { - parameters, - output_schema, - .. - }) = &list_agents.spec - else { - panic!("list_agents should be a function tool"); - }; - let JsonSchema::Object { - properties, - required, - .. - } = parameters - else { - panic!("list_agents should use object params"); - }; - assert!(properties.contains_key("path_prefix")); - assert_eq!(required.as_ref(), None); - let output_schema = output_schema - .as_ref() - .expect("list_agents should define output schema"); - assert_eq!( - output_schema["properties"]["agents"]["items"]["required"], - json!(["agent_name", "agent_status", "last_task_message"]) - ); - assert_lacks_tool_name(&tools, "send_input"); - assert_lacks_tool_name(&tools, "resume_agent"); -} - -#[test] -fn test_build_specs_enable_fanout_enables_agent_jobs_and_collab_tools() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::SpawnCsv); - features.normalize_dependencies(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names( - &tools, - &[ - "spawn_agent", - "send_input", - "wait_agent", - "close_agent", - "spawn_agents_on_csv", - ], - ); -} - -#[test] -fn view_image_tool_omits_detail_without_original_detail_feature() { - let config = test_config(); - let mut model_info = - ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - model_info.supports_image_detail_original = true; - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else { - panic!("view_image should be a function tool"); - }; - let JsonSchema::Object { properties, .. } = parameters else { - panic!("view_image should use an object schema"); - }; - assert!(!properties.contains_key("detail")); -} - -#[test] -fn view_image_tool_includes_detail_with_original_detail_feature() { - let config = test_config(); - let mut model_info = - ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - model_info.supports_image_detail_original = true; - let mut features = Features::with_defaults(); - features.enable(Feature::ImageDetailOriginal); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME); - let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else { - panic!("view_image should be a function tool"); - }; - let JsonSchema::Object { properties, .. } = parameters else { - panic!("view_image should use an object schema"); - }; - assert!(properties.contains_key("detail")); - let Some(JsonSchema::String { - description: Some(description), - }) = properties.get("detail") - else { - panic!("view_image detail should include a description"); - }; - assert!(description.contains("only supported value is `original`")); - assert!(description.contains("omit this field for default resized behavior")); -} - -#[test] -fn test_build_specs_agent_job_worker_tools_enabled() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::SpawnCsv); - features.normalize_dependencies(); - features.enable(Feature::Sqlite); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::SubAgent(SubAgentSource::Other( - "agent_job:test".to_string(), - )), - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names( - &tools, - &[ - "spawn_agent", - "send_input", - "resume_agent", - "wait_agent", - "close_agent", - "spawn_agents_on_csv", - "report_agent_job_result", - ], - ); - assert_lacks_tool_name(&tools, "request_user_input"); -} - -#[test] -fn request_user_input_description_reflects_default_mode_feature_flag() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let request_user_input_tool = find_tool(&tools, "request_user_input"); - assert_eq!( - request_user_input_tool.spec, - request_user_input_tool_spec(/*default_mode_request_user_input*/ false) - ); - - features.enable(Feature::DefaultModeRequestUserInput); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let request_user_input_tool = find_tool(&tools, "request_user_input"); - assert_eq!( - request_user_input_tool.spec, - request_user_input_tool_spec(/*default_mode_request_user_input*/ true) - ); -} - -#[test] -fn request_permissions_requires_feature_flag() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_lacks_tool_name(&tools, "request_permissions"); - - let mut features = Features::with_defaults(); - features.enable(Feature::RequestPermissionsTool); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let request_permissions_tool = find_tool(&tools, "request_permissions"); - assert_eq!( - request_permissions_tool.spec, - create_request_permissions_tool(request_permissions_tool_description()) - ); -} - -#[test] -fn request_permissions_tool_is_independent_from_additional_permissions() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::ExecPermissionApprovals); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - assert_lacks_tool_name(&tools, "request_permissions"); -} - #[test] fn get_memory_requires_feature_flag() { let config = test_config(); @@ -936,153 +223,6 @@ fn get_memory_requires_feature_flag() { ); } -#[test] -fn js_repl_requires_feature_flag() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - assert!( - !tools.iter().any(|tool| tool.spec.name() == "js_repl"), - "js_repl should be disabled when the feature is off" - ); - assert!( - !tools.iter().any(|tool| tool.spec.name() == "js_repl_reset"), - "js_repl_reset should be disabled when the feature is off" - ); -} - -#[test] -fn js_repl_enabled_adds_tools() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::JsRepl); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names(&tools, &["js_repl", "js_repl_reset"]); -} - -#[test] -fn image_generation_tools_require_feature_and_supported_model() { - let config = test_config(); - let mut supported_model_info = - ModelsManager::construct_model_info_offline_for_tests("gpt-5.2", &config); - supported_model_info.slug = "custom/gpt-5.2-variant".to_string(); - let mut unsupported_model_info = supported_model_info.clone(); - unsupported_model_info.input_modalities = vec![InputModality::Text]; - let default_features = Features::with_defaults(); - let mut image_generation_features = default_features.clone(); - image_generation_features.enable(Feature::ImageGeneration); - - let available_models = Vec::new(); - let default_tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &supported_model_info, - available_models: &available_models, - features: &default_features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (default_tools, _) = build_specs( - &default_tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert!( - !default_tools - .iter() - .any(|tool| tool.spec.name() == "image_generation"), - "image_generation should be disabled by default" - ); - - let supported_tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &supported_model_info, - available_models: &available_models, - features: &image_generation_features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (supported_tools, _) = build_specs( - &supported_tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert_contains_tool_names(&supported_tools, &["image_generation"]); - let image_generation_tool = find_tool(&supported_tools, "image_generation"); - assert_eq!( - serde_json::to_value(&image_generation_tool.spec).expect("serialize image tool"), - serde_json::json!({ - "type": "image_generation", - "output_format": "png" - }) - ); - - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &unsupported_model_info, - available_models: &available_models, - features: &image_generation_features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - assert!( - !tools - .iter() - .any(|tool| tool.spec.name() == "image_generation"), - "image_generation should be disabled for unsupported models" - ); -} - fn assert_model_tools( model_slug: &str, features: &Features, @@ -1134,239 +274,6 @@ fn assert_default_model_tools( assert_model_tools(model_slug, features, web_search_mode, &expected); } -#[test] -fn web_search_mode_cached_sets_external_web_access_false() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - let tool = find_tool(&tools, "web_search"); - assert_eq!( - tool.spec, - ToolSpec::WebSearch { - external_web_access: Some(false), - filters: None, - user_location: None, - search_context_size: None, - search_content_types: None, - } - ); -} - -#[test] -fn web_search_mode_live_sets_external_web_access_true() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Live), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - let tool = find_tool(&tools, "web_search"); - assert_eq!( - tool.spec, - ToolSpec::WebSearch { - external_web_access: Some(true), - filters: None, - user_location: None, - search_context_size: None, - search_content_types: None, - } - ); -} - -#[test] -fn web_search_config_is_forwarded_to_tool_spec() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - let web_search_config = WebSearchConfig { - filters: Some(codex_protocol::config_types::WebSearchFilters { - allowed_domains: Some(vec!["example.com".to_string()]), - }), - user_location: Some(codex_protocol::config_types::WebSearchUserLocation { - r#type: codex_protocol::config_types::WebSearchUserLocationType::Approximate, - country: Some("US".to_string()), - region: Some("California".to_string()), - city: Some("San Francisco".to_string()), - timezone: Some("America/Los_Angeles".to_string()), - }), - search_context_size: Some(codex_protocol::config_types::WebSearchContextSize::High), - }; - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Live), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }) - .with_web_search_config(Some(web_search_config.clone())); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - let tool = find_tool(&tools, "web_search"); - assert_eq!( - tool.spec, - ToolSpec::WebSearch { - external_web_access: Some(true), - filters: web_search_config - .filters - .map(ResponsesApiWebSearchFilters::from), - user_location: web_search_config - .user_location - .map(ResponsesApiWebSearchUserLocation::from), - search_context_size: web_search_config.search_context_size, - search_content_types: None, - } - ); -} - -#[test] -fn web_search_tool_type_text_and_image_sets_search_content_types() { - let config = test_config(); - let mut model_info = - ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - model_info.web_search_tool_type = WebSearchToolType::TextAndImage; - let features = Features::with_defaults(); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Live), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - let tool = find_tool(&tools, "web_search"); - assert_eq!( - tool.spec, - ToolSpec::WebSearch { - external_web_access: Some(true), - filters: None, - user_location: None, - search_context_size: None, - search_content_types: Some(vec!["text".to_string(), "image".to_string()]), - } - ); -} - -#[test] -fn mcp_resource_tools_are_hidden_without_mcp_servers() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - assert!( - !tools.iter().any(|tool| matches!( - tool.spec.name(), - "list_mcp_resources" | "list_mcp_resource_templates" | "read_mcp_resource" - )), - "MCP resource tools should be omitted when no MCP servers are configured" - ); -} - -#[test] -fn mcp_resource_tools_are_included_when_mcp_servers_are_present() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - Some(HashMap::new()), - /*app_tools*/ None, - &[], - ) - .build(); - - assert_contains_tool_names( - &tools, - &[ - "list_mcp_resources", - "list_mcp_resource_templates", - "read_mcp_resource", - ], - ); -} - #[test] fn test_build_specs_gpt5_codex_default() { let features = Features::with_defaults(); @@ -1674,492 +581,6 @@ fn shell_zsh_fork_prefers_shell_command_over_unified_exec() { ); } -#[test] -#[ignore] -fn test_parallel_support_flags() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - assert!(find_tool(&tools, "exec_command").supports_parallel_tool_calls); - assert!(!find_tool(&tools, "write_stdin").supports_parallel_tool_calls); -} - -#[test] -fn test_test_model_info_includes_sync_tool() { - let _config = test_config(); - let mut model_info = model_info_from_models_json("gpt-5-codex"); - model_info.experimental_supported_tools = vec!["test_sync_tool".to_string()]; - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - - assert!(tools.iter().any(|tool| tool.name() == "test_sync_tool")); -} - -#[test] -fn test_build_specs_mcp_tools_converted() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("o3", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Live), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - Some(HashMap::from([( - "test_server/do_something_cool".to_string(), - mcp_tool( - "do_something_cool", - "Do something cool", - serde_json::json!({ - "type": "object", - "properties": { - "string_argument": { "type": "string" }, - "number_argument": { "type": "number" }, - "object_argument": { - "type": "object", - "properties": { - "string_property": { "type": "string" }, - "number_property": { "type": "number" }, - }, - "required": ["string_property", "number_property"], - "additionalProperties": false, - }, - }, - }), - ), - )])), - /*app_tools*/ None, - &[], - ) - .build(); - - let tool = find_tool(&tools, "test_server/do_something_cool"); - assert_eq!( - &tool.spec, - &ToolSpec::Function(ResponsesApiTool { - name: "test_server/do_something_cool".to_string(), - parameters: JsonSchema::Object { - properties: BTreeMap::from([ - ( - "string_argument".to_string(), - JsonSchema::String { description: None } - ), - ( - "number_argument".to_string(), - JsonSchema::Number { description: None } - ), - ( - "object_argument".to_string(), - JsonSchema::Object { - properties: BTreeMap::from([ - ( - "string_property".to_string(), - JsonSchema::String { description: None } - ), - ( - "number_property".to_string(), - JsonSchema::Number { description: None } - ), - ]), - required: Some(vec![ - "string_property".to_string(), - "number_property".to_string(), - ]), - additional_properties: Some(false.into()), - }, - ), - ]), - required: None, - additional_properties: None, - }, - description: "Do something cool".to_string(), - strict: false, - output_schema: Some(mcp_call_tool_result_output_schema(serde_json::json!({}))), - defer_loading: None, - }) - ); -} - -#[test] -fn test_build_specs_mcp_tools_sorted_by_name() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("o3", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - // Intentionally construct a map with keys that would sort alphabetically. - let tools_map: HashMap = HashMap::from([ - ( - "test_server/do".to_string(), - mcp_tool("a", "a", serde_json::json!({"type": "object"})), - ), - ( - "test_server/something".to_string(), - mcp_tool("b", "b", serde_json::json!({"type": "object"})), - ), - ( - "test_server/cool".to_string(), - mcp_tool("c", "c", serde_json::json!({"type": "object"})), - ), - ]); - - let (tools, _) = build_specs(&tools_config, Some(tools_map), /*app_tools*/ None, &[]).build(); - - // Only assert that the MCP tools themselves are sorted by fully-qualified name. - let mcp_names: Vec<_> = tools - .iter() - .map(|t| t.name().to_string()) - .filter(|n| n.starts_with("test_server/")) - .collect(); - let expected = vec![ - "test_server/cool".to_string(), - "test_server/do".to_string(), - "test_server/something".to_string(), - ]; - assert_eq!(mcp_names, expected); -} - -#[test] -fn search_tool_description_lists_each_codex_apps_connector_once() { - let model_info = search_capable_model_info(); - let mut features = Features::with_defaults(); - features.enable(Feature::Apps); - features.enable(Feature::ToolSearch); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let (tools, _) = build_specs( - &tools_config, - Some(HashMap::from([ - ( - "mcp__codex_apps__calendar_create_event".to_string(), - mcp_tool( - "calendar_create_event", - "Create calendar event", - serde_json::json!({"type": "object"}), - ), - ), - ( - "mcp__rmcp__echo".to_string(), - mcp_tool("echo", "Echo", serde_json::json!({"type": "object"})), - ), - ])), - Some(HashMap::from([ - ( - "mcp__codex_apps__calendar_create_event".to_string(), - ToolInfo { - server_name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - tool_name: "_create_event".to_string(), - tool_namespace: "mcp__codex_apps__calendar".to_string(), - tool: mcp_tool( - "calendar-create-event", - "Create calendar event", - serde_json::json!({"type": "object"}), - ), - connector_id: Some("calendar".to_string()), - connector_name: Some("Calendar".to_string()), - plugin_display_names: Vec::new(), - connector_description: Some( - "Plan events and manage your calendar.".to_string(), - ), - }, - ), - ( - "mcp__codex_apps__calendar_list_events".to_string(), - ToolInfo { - server_name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - tool_name: "_list_events".to_string(), - tool_namespace: "mcp__codex_apps__calendar".to_string(), - tool: mcp_tool( - "calendar-list-events", - "List calendar events", - serde_json::json!({"type": "object"}), - ), - connector_id: Some("calendar".to_string()), - connector_name: Some("Calendar".to_string()), - plugin_display_names: Vec::new(), - connector_description: Some( - "Plan events and manage your calendar.".to_string(), - ), - }, - ), - ( - "mcp__codex_apps__gmail_search_threads".to_string(), - ToolInfo { - server_name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - tool_name: "_search_threads".to_string(), - tool_namespace: "mcp__codex_apps__gmail".to_string(), - tool: mcp_tool( - "gmail-search-threads", - "Search email threads", - serde_json::json!({"type": "object"}), - ), - connector_id: Some("gmail".to_string()), - connector_name: Some("Gmail".to_string()), - plugin_display_names: Vec::new(), - connector_description: Some("Find and summarize email threads.".to_string()), - }, - ), - ( - "mcp__rmcp__echo".to_string(), - ToolInfo { - server_name: "rmcp".to_string(), - tool_name: "echo".to_string(), - tool_namespace: "rmcp".to_string(), - tool: mcp_tool("echo", "Echo", serde_json::json!({"type": "object"})), - connector_id: None, - connector_name: None, - plugin_display_names: Vec::new(), - connector_description: None, - }, - ), - ])), - &[], - ) - .build(); - - let search_tool = find_tool(&tools, TOOL_SEARCH_TOOL_NAME); - let ToolSpec::ToolSearch { description, .. } = &search_tool.spec else { - panic!("expected tool_search tool"); - }; - let description = description.as_str(); - assert!(description.contains("- Calendar: Plan events and manage your calendar.")); - assert!(description.contains("- Gmail: Find and summarize email threads.")); - assert_eq!( - description - .matches("- Calendar: Plan events and manage your calendar.") - .count(), - 1 - ); - assert!(!description.contains("mcp__rmcp__echo")); -} - -#[test] -fn search_tool_requires_model_capability_and_feature_flag() { - let model_info = search_capable_model_info(); - let app_tools = Some(HashMap::from([( - "mcp__codex_apps__calendar_create_event".to_string(), - ToolInfo { - server_name: CODEX_APPS_MCP_SERVER_NAME.to_string(), - tool_name: "calendar_create_event".to_string(), - tool_namespace: "mcp__codex_apps__calendar".to_string(), - tool: mcp_tool( - "calendar_create_event", - "Create calendar event", - serde_json::json!({"type": "object"}), - ), - connector_id: Some("calendar".to_string()), - connector_name: Some("Calendar".to_string()), - connector_description: None, - plugin_display_names: Vec::new(), - }, - )])); - - let features = Features::with_defaults(); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &ModelInfo { - supports_search_tool: false, - ..model_info.clone() - }, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - app_tools.clone(), - &[], - ) - .build(); - assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); - - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - app_tools.clone(), - &[], - ) - .build(); - assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); - - let mut features = Features::with_defaults(); - features.enable(Feature::ToolSearch); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs(&tools_config, /*mcp_tools*/ None, app_tools, &[]).build(); - assert_contains_tool_names(&tools, &[TOOL_SEARCH_TOOL_NAME]); -} - -#[test] -fn tool_suggest_is_not_registered_without_feature_flag() { - let model_info = search_capable_model_info(); - let mut features = Features::with_defaults(); - features.enable(Feature::ToolSearch); - features.enable(Feature::Apps); - features.enable(Feature::Plugins); - features.disable(Feature::ToolSuggest); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs_with_discoverable_tools( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - Some(vec![discoverable_connector( - "connector_2128aebfecb84f64a069897515042a44", - "Google Calendar", - "Plan events and schedules.", - )]), - &[], - ) - .build(); - - assert!( - !tools - .iter() - .any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME) - ); -} - -#[test] -fn tool_suggest_can_be_registered_without_search_tool() { - let model_info = ModelInfo { - supports_search_tool: false, - ..search_capable_model_info() - }; - let mut features = Features::with_defaults(); - features.enable(Feature::Apps); - features.enable(Feature::Plugins); - features.enable(Feature::ToolSuggest); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - let (tools, _) = build_specs_with_discoverable_tools( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - Some(vec![discoverable_connector( - "connector_2128aebfecb84f64a069897515042a44", - "Google Calendar", - "Plan events and schedules.", - )]), - &[], - ) - .build(); - - assert_contains_tool_names(&tools, &[TOOL_SUGGEST_TOOL_NAME]); - assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); - - let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); - let ToolSpec::Function(ResponsesApiTool { description, .. }) = &tool_suggest.spec else { - panic!("expected function tool"); - }; - assert!(description.contains( - "Suggests a missing connector in an installed plugin, or in narrower cases a not installed but discoverable plugin" - )); - assert!(description.contains( - "You've already tried to find a matching available tool for the user's request but couldn't find a good match. This includes `tool_search` (if available) and other means." - )); -} - #[test] fn tool_suggest_requires_apps_and_plugins_features() { let model_info = search_capable_model_info(); @@ -2353,111 +774,6 @@ fn search_tool_registers_namespaced_app_tool_aliases() { assert!(registry.has_handler(alias.as_str(), /*namespace*/ None)); } -#[test] -fn tool_suggest_description_lists_discoverable_tools() { - let model_info = search_capable_model_info(); - let mut features = Features::with_defaults(); - features.enable(Feature::Apps); - features.enable(Feature::Plugins); - features.enable(Feature::ToolSearch); - features.enable(Feature::ToolSuggest); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let discoverable_tools = vec![ - discoverable_connector( - "connector_2128aebfecb84f64a069897515042a44", - "Google Calendar", - "Plan events and schedules.", - ), - discoverable_connector( - "connector_68df038e0ba48191908c8434991bbac2", - "Gmail", - "Find and summarize email threads.", - ), - DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo { - id: "sample@test".to_string(), - name: "Sample Plugin".to_string(), - description: None, - has_skills: true, - mcp_server_names: vec!["sample-docs".to_string()], - app_connector_ids: vec!["connector_sample".to_string()], - })), - ]; - - let (tools, _) = build_specs_with_discoverable_tools( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - Some(discoverable_tools), - &[], - ) - .build(); - - let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); - let ToolSpec::Function(ResponsesApiTool { - description, - parameters, - .. - }) = &tool_suggest.spec - else { - panic!("expected function tool"); - }; - assert!(description.contains( - "Suggests a missing connector in an installed plugin, or in narrower cases a not installed but discoverable plugin" - )); - assert!(description.contains("Google Calendar")); - assert!(description.contains("Gmail")); - assert!(description.contains("Sample Plugin")); - assert!(description.contains("Plan events and schedules.")); - assert!(description.contains("Find and summarize email threads.")); - assert!(description.contains("id: `sample@test`, type: plugin, action: install")); - assert!(description.contains("`action_type`: `install` or `enable`")); - assert!( - description.contains("skills; MCP servers: sample-docs; app connectors: connector_sample") - ); - assert!( - description.contains( - "You've already tried to find a matching available tool for the user's request but couldn't find a good match. This includes `tool_search` (if available) and other means." - ) - ); - assert!(description.contains( - "For connectors/apps that are not installed but needed for an installed plugin, suggest to install them if the task requirements match precisely." - )); - assert!(description.contains( - "For plugins that are not installed but discoverable, only suggest discoverable and installable plugins when the user's intent very explicitly and unambiguously matches that plugin itself." - )); - assert!(description.contains( - "Do not suggest a plugin just because one of its connectors or capabilities seems relevant." - )); - assert!(description.contains( - "Apply the stricter explicit-and-unambiguous rule for *discoverable tools* like plugin install suggestions; *missing tools* like connector install suggestions continue to use the normal clear-fit standard." - )); - assert!(description.contains("DO NOT explore or recommend tools that are not on this list.")); - assert!(!description.contains("{{discoverable_tools}}")); - assert!(!description.contains("tool_search fails to find a good match")); - let JsonSchema::Object { required, .. } = parameters else { - panic!("expected object parameters"); - }; - assert_eq!( - required.as_ref(), - Some(&vec![ - "tool_type".to_string(), - "action_type".to_string(), - "tool_id".to_string(), - "suggest_reason".to_string(), - ]) - ); -} - #[test] fn test_mcp_tool_property_missing_type_defaults_to_string() { let config = test_config(); @@ -2802,95 +1118,6 @@ fn test_get_openai_tools_mcp_tools_with_additional_properties_schema() { ); } -#[test] -fn code_mode_augments_builtin_tool_descriptions_with_typed_sample() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CodeMode); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let ToolSpec::Function(ResponsesApiTool { description, .. }) = - &find_tool(&tools, "view_image").spec - else { - panic!("expected function tool"); - }; - - assert_eq!( - description, - "View a local image from the filesystem (only use if given a full filepath by the user, and the image isn't already attached to the thread context within tags).\n\nexec tool declaration:\n```ts\ndeclare const tools: { view_image(args: { path: string; }): Promise<{ detail: string | null; image_url: string; }>; };\n```" - ); -} - -#[test] -fn code_mode_augments_mcp_tool_descriptions_with_namespaced_sample() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CodeMode); - features.enable(Feature::UnifiedExec); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let (tools, _) = build_specs( - &tools_config, - Some(HashMap::from([( - "mcp__sample__echo".to_string(), - mcp_tool( - "echo", - "Echo text", - serde_json::json!({ - "type": "object", - "properties": { - "message": {"type": "string"} - }, - "required": ["message"], - "additionalProperties": false - }), - ), - )])), - /*app_tools*/ None, - &[], - ) - .build(); - - let ToolSpec::Function(ResponsesApiTool { description, .. }) = - &find_tool(&tools, "mcp__sample__echo").spec - else { - panic!("expected function tool"); - }; - - assert_eq!( - description, - "Echo text\n\nexec tool declaration:\n```ts\ndeclare const tools: { mcp__sample__echo(args: { message: string; }): Promise<{ _meta?: unknown; content: Array; isError?: boolean; structuredContent?: unknown; }>; };\n```" - ); -} - #[test] fn code_mode_only_restricts_model_tools_to_exec_tools() { let mut features = Features::with_defaults(); @@ -2904,78 +1131,3 @@ fn code_mode_only_restricts_model_tools_to_exec_tools() { &["exec", "wait"], ); } - -#[test] -fn code_mode_only_exec_description_includes_full_nested_tool_details() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CodeMode); - features.enable(Feature::CodeModeOnly); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let ToolSpec::Freeform(FreeformTool { description, .. }) = &find_tool(&tools, "exec").spec - else { - panic!("expected freeform tool"); - }; - - assert!(!description.contains("Enabled nested tools:")); - assert!(!description.contains("Nested tool reference:")); - assert!(description.starts_with( - "Use `exec/wait` tool to run all other tools, do not attempt to use any other tools directly" - )); - assert!(description.contains("### `update_plan` (`update_plan`)")); - assert!(description.contains("### `view_image` (`view_image`)")); -} - -#[test] -fn code_mode_exec_description_omits_nested_tool_details_when_not_code_mode_only() { - let config = test_config(); - let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); - let mut features = Features::with_defaults(); - features.enable(Feature::CodeMode); - let available_models = Vec::new(); - let tools_config = ToolsConfig::new(&ToolsConfigParams { - model_info: &model_info, - available_models: &available_models, - features: &features, - web_search_mode: Some(WebSearchMode::Cached), - session_source: SessionSource::Cli, - sandbox_policy: &SandboxPolicy::DangerFullAccess, - windows_sandbox_level: WindowsSandboxLevel::Disabled, - }); - - let (tools, _) = build_specs( - &tools_config, - /*mcp_tools*/ None, - /*app_tools*/ None, - &[], - ) - .build(); - let ToolSpec::Freeform(FreeformTool { description, .. }) = &find_tool(&tools, "exec").spec - else { - panic!("expected freeform tool"); - }; - - assert!(!description.starts_with( - "Use `exec/wait` tool to run all other tools, do not attempt to use any other tools directly" - )); - assert!(!description.contains("### `update_plan` (`update_plan`)")); - assert!(!description.contains("### `view_image` (`view_image`)")); -} diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs index 01cda5d64e..314d93f55f 100644 --- a/codex-rs/tools/src/tool_registry_plan.rs +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -486,3 +486,7 @@ pub fn build_tool_registry_plan( plan } + +#[cfg(test)] +#[path = "tool_registry_plan_tests.rs"] +mod tests; diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs new file mode 100644 index 0000000000..c2c4a0aea1 --- /dev/null +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -0,0 +1,1878 @@ +use super::*; +use crate::AdditionalProperties; +use crate::ConfiguredToolSpec; +use crate::DiscoverablePluginInfo; +use crate::DiscoverableTool; +use crate::FreeformTool; +use crate::JsonSchema; +use crate::ResponsesApiTool; +use crate::ResponsesApiWebSearchFilters; +use crate::ResponsesApiWebSearchUserLocation; +use crate::ToolHandlerSpec; +use crate::ToolRegistryPlanAppTool; +use crate::ToolsConfigParams; +use crate::WaitAgentTimeoutOptions; +use crate::mcp_call_tool_result_output_schema; +use codex_app_server_protocol::AppInfo; +use codex_features::Feature; +use codex_features::Features; +use codex_protocol::config_types::WebSearchConfig; +use codex_protocol::config_types::WebSearchMode; +use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::dynamic_tools::DynamicToolSpec; +use codex_protocol::models::VIEW_IMAGE_TOOL_NAME; +use codex_protocol::openai_models::InputModality; +use codex_protocol::openai_models::ModelInfo; +use codex_protocol::openai_models::WebSearchToolType; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::SubAgentSource; +use pretty_assertions::assert_eq; +use serde_json::json; +use std::collections::BTreeMap; +use std::collections::HashMap; + +const CODEX_APPS_MCP_SERVER_NAME: &str = "codex_apps"; +const DEFAULT_AGENT_TYPE_DESCRIPTION: &str = "Test agent type description."; +const DEFAULT_WAIT_TIMEOUT_MS: i64 = 30_000; +const MIN_WAIT_TIMEOUT_MS: i64 = 10_000; +const MAX_WAIT_TIMEOUT_MS: i64 = 3_600_000; + +#[test] +fn test_full_toolset_specs_for_gpt5_codex_unified_exec_web_search() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Live), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + let mut actual = BTreeMap::new(); + let mut duplicate_names = Vec::new(); + for tool in &tools { + let name = tool.name().to_string(); + if actual.insert(name.clone(), tool.spec.clone()).is_some() { + duplicate_names.push(name); + } + } + assert!( + duplicate_names.is_empty(), + "duplicate tool entries detected: {duplicate_names:?}" + ); + + let mut expected = BTreeMap::new(); + for spec in [ + create_exec_command_tool(CommandToolOptions { + allow_login_shell: true, + exec_permission_approvals_enabled: false, + }), + create_write_stdin_tool(), + create_update_plan_tool(), + request_user_input_tool_spec(/*default_mode_request_user_input*/ false), + create_apply_patch_freeform_tool(), + ToolSpec::WebSearch { + external_web_access: Some(true), + filters: None, + user_location: None, + search_context_size: None, + search_content_types: None, + }, + create_view_image_tool(ViewImageToolOptions { + can_request_original_image_detail: config.can_request_original_image_detail, + }), + ] { + expected.insert(spec.name().to_string(), spec); + } + let collab_specs = if config.multi_agent_v2 { + vec![ + create_spawn_agent_tool_v2(spawn_agent_tool_options(&config)), + create_send_message_tool(), + create_wait_agent_tool_v2(wait_agent_timeout_options()), + create_close_agent_tool_v2(), + ] + } else { + vec![ + create_spawn_agent_tool_v1(spawn_agent_tool_options(&config)), + create_send_input_tool_v1(), + create_wait_agent_tool_v1(wait_agent_timeout_options()), + create_close_agent_tool_v1(), + ] + }; + for spec in collab_specs { + expected.insert(spec.name().to_string(), spec); + } + if !config.multi_agent_v2 { + let spec = create_resume_agent_tool(); + expected.insert(spec.name().to_string(), spec); + } + + if config.exec_permission_approvals_enabled { + let spec = create_request_permissions_tool(request_permissions_tool_description()); + expected.insert(spec.name().to_string(), spec); + } + + assert_eq!( + actual.keys().collect::>(), + expected.keys().collect::>(), + "tool name set mismatch" + ); + + for name in expected.keys() { + let mut actual_spec = actual.get(name).expect("present").clone(); + let mut expected_spec = expected.get(name).expect("present").clone(); + strip_descriptions_tool(&mut actual_spec); + strip_descriptions_tool(&mut expected_spec); + assert_eq!(actual_spec, expected_spec, "spec mismatch for {name}"); + } +} + +#[test] +fn test_build_specs_collab_tools_enabled() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::Collab); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names( + &tools, + &["spawn_agent", "send_input", "wait_agent", "close_agent"], + ); + assert_lacks_tool_name(&tools, "spawn_agents_on_csv"); + assert_lacks_tool_name(&tools, "list_agents"); + + let spawn_agent = find_tool(&tools, "spawn_agent"); + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &spawn_agent.spec else { + panic!("spawn_agent should be a function tool"); + }; + let JsonSchema::Object { properties, .. } = parameters else { + panic!("spawn_agent should use object params"); + }; + assert!(properties.contains_key("fork_context")); + assert!(!properties.contains_key("fork_turns")); +} + +#[test] +fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::Collab); + features.enable(Feature::MultiAgentV2); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names( + &tools, + &[ + "spawn_agent", + "send_message", + "assign_task", + "wait_agent", + "close_agent", + "list_agents", + ], + ); + + let spawn_agent = find_tool(&tools, "spawn_agent"); + let ToolSpec::Function(ResponsesApiTool { + parameters, + output_schema, + .. + }) = &spawn_agent.spec + else { + panic!("spawn_agent should be a function tool"); + }; + let JsonSchema::Object { + properties, + required, + .. + } = parameters + else { + panic!("spawn_agent should use object params"); + }; + assert!(properties.contains_key("task_name")); + assert!(properties.contains_key("message")); + assert!(properties.contains_key("fork_turns")); + assert!(!properties.contains_key("items")); + assert!(!properties.contains_key("fork_context")); + assert_eq!( + required.as_ref(), + Some(&vec!["task_name".to_string(), "message".to_string()]) + ); + let output_schema = output_schema + .as_ref() + .expect("spawn_agent should define output schema"); + assert_eq!( + output_schema["required"], + json!(["agent_id", "task_name", "nickname"]) + ); + + let send_message = find_tool(&tools, "send_message"); + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &send_message.spec else { + panic!("send_message should be a function tool"); + }; + let JsonSchema::Object { + properties, + required, + .. + } = parameters + else { + panic!("send_message should use object params"); + }; + assert!(properties.contains_key("target")); + assert!(!properties.contains_key("interrupt")); + assert!(properties.contains_key("message")); + assert!(!properties.contains_key("items")); + assert_eq!( + required.as_ref(), + Some(&vec!["target".to_string(), "message".to_string()]) + ); + + let assign_task = find_tool(&tools, "assign_task"); + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &assign_task.spec else { + panic!("assign_task should be a function tool"); + }; + let JsonSchema::Object { + properties, + required, + .. + } = parameters + else { + panic!("assign_task should use object params"); + }; + assert!(properties.contains_key("target")); + assert!(properties.contains_key("message")); + assert!(!properties.contains_key("items")); + assert_eq!( + required.as_ref(), + Some(&vec!["target".to_string(), "message".to_string()]) + ); + + let wait_agent = find_tool(&tools, "wait_agent"); + let ToolSpec::Function(ResponsesApiTool { + parameters, + output_schema, + .. + }) = &wait_agent.spec + else { + panic!("wait_agent should be a function tool"); + }; + let JsonSchema::Object { + properties, + required, + .. + } = parameters + else { + panic!("wait_agent should use object params"); + }; + assert!(!properties.contains_key("targets")); + assert!(properties.contains_key("timeout_ms")); + assert_eq!(required, &None); + let output_schema = output_schema + .as_ref() + .expect("wait_agent should define output schema"); + assert_eq!( + output_schema["properties"]["message"]["description"], + json!("Brief wait summary without the agent's final content.") + ); + + let list_agents = find_tool(&tools, "list_agents"); + let ToolSpec::Function(ResponsesApiTool { + parameters, + output_schema, + .. + }) = &list_agents.spec + else { + panic!("list_agents should be a function tool"); + }; + let JsonSchema::Object { + properties, + required, + .. + } = parameters + else { + panic!("list_agents should use object params"); + }; + assert!(properties.contains_key("path_prefix")); + assert_eq!(required.as_ref(), None); + let output_schema = output_schema + .as_ref() + .expect("list_agents should define output schema"); + assert_eq!( + output_schema["properties"]["agents"]["items"]["required"], + json!(["agent_name", "agent_status", "last_task_message"]) + ); + assert_lacks_tool_name(&tools, "send_input"); + assert_lacks_tool_name(&tools, "resume_agent"); +} + +#[test] +fn test_build_specs_enable_fanout_enables_agent_jobs_and_collab_tools() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::SpawnCsv); + features.normalize_dependencies(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names( + &tools, + &[ + "spawn_agent", + "send_input", + "wait_agent", + "close_agent", + "spawn_agents_on_csv", + ], + ); +} + +#[test] +fn view_image_tool_omits_detail_without_original_detail_feature() { + let mut model_info = model_info(); + model_info.supports_image_detail_original = true; + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME); + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else { + panic!("view_image should be a function tool"); + }; + let JsonSchema::Object { properties, .. } = parameters else { + panic!("view_image should use an object schema"); + }; + assert!(!properties.contains_key("detail")); +} + +#[test] +fn view_image_tool_includes_detail_with_original_detail_feature() { + let mut model_info = model_info(); + model_info.supports_image_detail_original = true; + let mut features = Features::with_defaults(); + features.enable(Feature::ImageDetailOriginal); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME); + let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else { + panic!("view_image should be a function tool"); + }; + let JsonSchema::Object { properties, .. } = parameters else { + panic!("view_image should use an object schema"); + }; + assert!(properties.contains_key("detail")); + let Some(JsonSchema::String { + description: Some(description), + }) = properties.get("detail") + else { + panic!("view_image detail should include a description"); + }; + assert!(description.contains("only supported value is `original`")); + assert!(description.contains("omit this field for default resized behavior")); +} + +#[test] +fn test_build_specs_agent_job_worker_tools_enabled() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::SpawnCsv); + features.normalize_dependencies(); + features.enable(Feature::Sqlite); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::SubAgent(SubAgentSource::Other( + "agent_job:test".to_string(), + )), + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names( + &tools, + &[ + "spawn_agent", + "send_input", + "resume_agent", + "wait_agent", + "close_agent", + "spawn_agents_on_csv", + "report_agent_job_result", + ], + ); + assert_lacks_tool_name(&tools, "request_user_input"); +} + +#[test] +fn request_user_input_description_reflects_default_mode_feature_flag() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let request_user_input_tool = find_tool(&tools, REQUEST_USER_INPUT_TOOL_NAME); + assert_eq!( + request_user_input_tool.spec, + request_user_input_tool_spec(/*default_mode_request_user_input*/ false) + ); + + features.enable(Feature::DefaultModeRequestUserInput); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let request_user_input_tool = find_tool(&tools, REQUEST_USER_INPUT_TOOL_NAME); + assert_eq!( + request_user_input_tool.spec, + request_user_input_tool_spec(/*default_mode_request_user_input*/ true) + ); +} + +#[test] +fn request_permissions_requires_feature_flag() { + let model_info = model_info(); + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + assert_lacks_tool_name(&tools, "request_permissions"); + + let mut features = Features::with_defaults(); + features.enable(Feature::RequestPermissionsTool); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let request_permissions_tool = find_tool(&tools, "request_permissions"); + assert_eq!( + request_permissions_tool.spec, + create_request_permissions_tool(request_permissions_tool_description()) + ); +} + +#[test] +fn request_permissions_tool_is_independent_from_additional_permissions() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::ExecPermissionApprovals); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_lacks_tool_name(&tools, "request_permissions"); +} + +#[test] +fn js_repl_requires_feature_flag() { + let model_info = model_info(); + let features = Features::with_defaults(); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert!( + !tools.iter().any(|tool| tool.spec.name() == "js_repl"), + "js_repl should be disabled when the feature is off" + ); + assert!( + !tools.iter().any(|tool| tool.spec.name() == "js_repl_reset"), + "js_repl_reset should be disabled when the feature is off" + ); +} + +#[test] +fn js_repl_enabled_adds_tools() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::JsRepl); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names(&tools, &["js_repl", "js_repl_reset"]); +} + +#[test] +fn image_generation_tools_require_feature_and_supported_model() { + let supported_model_info = model_info(); + let mut unsupported_model_info = supported_model_info.clone(); + unsupported_model_info.input_modalities = vec![InputModality::Text]; + let default_features = Features::with_defaults(); + let mut image_generation_features = default_features.clone(); + image_generation_features.enable(Feature::ImageGeneration); + + let available_models = Vec::new(); + let default_tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &supported_model_info, + available_models: &available_models, + features: &default_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (default_tools, _) = build_specs( + &default_tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + assert!( + !default_tools + .iter() + .any(|tool| tool.spec.name() == "image_generation"), + "image_generation should be disabled by default" + ); + + let supported_tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &supported_model_info, + available_models: &available_models, + features: &image_generation_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (supported_tools, _) = build_specs( + &supported_tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + assert_contains_tool_names(&supported_tools, &["image_generation"]); + let image_generation_tool = find_tool(&supported_tools, "image_generation"); + assert_eq!( + serde_json::to_value(&image_generation_tool.spec).expect("serialize image tool"), + serde_json::json!({ + "type": "image_generation", + "output_format": "png" + }) + ); + + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &unsupported_model_info, + available_models: &available_models, + features: &image_generation_features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + assert!( + !tools + .iter() + .any(|tool| tool.spec.name() == "image_generation"), + "image_generation should be disabled for unsupported models" + ); +} + +#[test] +fn web_search_mode_cached_sets_external_web_access_false() { + let model_info = model_info(); + let features = Features::with_defaults(); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + let tool = find_tool(&tools, "web_search"); + assert_eq!( + tool.spec, + ToolSpec::WebSearch { + external_web_access: Some(false), + filters: None, + user_location: None, + search_context_size: None, + search_content_types: None, + } + ); +} + +#[test] +fn web_search_mode_live_sets_external_web_access_true() { + let model_info = model_info(); + let features = Features::with_defaults(); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Live), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + let tool = find_tool(&tools, "web_search"); + assert_eq!( + tool.spec, + ToolSpec::WebSearch { + external_web_access: Some(true), + filters: None, + user_location: None, + search_context_size: None, + search_content_types: None, + } + ); +} + +#[test] +fn web_search_config_is_forwarded_to_tool_spec() { + let model_info = model_info(); + let features = Features::with_defaults(); + let web_search_config = WebSearchConfig { + filters: Some(codex_protocol::config_types::WebSearchFilters { + allowed_domains: Some(vec!["example.com".to_string()]), + }), + user_location: Some(codex_protocol::config_types::WebSearchUserLocation { + r#type: codex_protocol::config_types::WebSearchUserLocationType::Approximate, + country: Some("US".to_string()), + region: Some("California".to_string()), + city: Some("San Francisco".to_string()), + timezone: Some("America/Los_Angeles".to_string()), + }), + search_context_size: Some(codex_protocol::config_types::WebSearchContextSize::High), + }; + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Live), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }) + .with_web_search_config(Some(web_search_config.clone())); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + let tool = find_tool(&tools, "web_search"); + assert_eq!( + tool.spec, + ToolSpec::WebSearch { + external_web_access: Some(true), + filters: web_search_config + .filters + .map(ResponsesApiWebSearchFilters::from), + user_location: web_search_config + .user_location + .map(ResponsesApiWebSearchUserLocation::from), + search_context_size: web_search_config.search_context_size, + search_content_types: None, + } + ); +} + +#[test] +fn web_search_tool_type_text_and_image_sets_search_content_types() { + let mut model_info = model_info(); + model_info.web_search_tool_type = WebSearchToolType::TextAndImage; + let features = Features::with_defaults(); + + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Live), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + let tool = find_tool(&tools, "web_search"); + assert_eq!( + tool.spec, + ToolSpec::WebSearch { + external_web_access: Some(true), + filters: None, + user_location: None, + search_context_size: None, + search_content_types: Some(vec!["text".to_string(), "image".to_string()]), + } + ); +} + +#[test] +fn mcp_resource_tools_are_hidden_without_mcp_servers() { + let model_info = model_info(); + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert!( + !tools.iter().any(|tool| matches!( + tool.spec.name(), + "list_mcp_resources" | "list_mcp_resource_templates" | "read_mcp_resource" + )), + "MCP resource tools should be omitted when no MCP servers are configured" + ); +} + +#[test] +fn mcp_resource_tools_are_included_when_mcp_servers_are_present() { + let model_info = model_info(); + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + Some(HashMap::new()), + /*app_tools*/ None, + &[], + ); + + assert_contains_tool_names( + &tools, + &[ + "list_mcp_resources", + "list_mcp_resource_templates", + "read_mcp_resource", + ], + ); +} + +#[test] +#[ignore] +fn test_parallel_support_flags() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert!(find_tool(&tools, "exec_command").supports_parallel_tool_calls); + assert!(!find_tool(&tools, "write_stdin").supports_parallel_tool_calls); +} + +#[test] +fn test_test_model_info_includes_sync_tool() { + let mut model_info = model_info(); + model_info.experimental_supported_tools = vec!["test_sync_tool".to_string()]; + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + + assert!(tools.iter().any(|tool| tool.name() == "test_sync_tool")); +} + +#[test] +fn test_build_specs_mcp_tools_converted() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Live), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + Some(HashMap::from([( + "test_server/do_something_cool".to_string(), + mcp_tool( + "do_something_cool", + "Do something cool", + serde_json::json!({ + "type": "object", + "properties": { + "string_argument": { "type": "string" }, + "number_argument": { "type": "number" }, + "object_argument": { + "type": "object", + "properties": { + "string_property": { "type": "string" }, + "number_property": { "type": "number" }, + }, + "required": ["string_property", "number_property"], + "additionalProperties": false, + }, + }, + }), + ), + )])), + /*app_tools*/ None, + &[], + ); + + let tool = find_tool(&tools, "test_server/do_something_cool"); + assert_eq!( + &tool.spec, + &ToolSpec::Function(ResponsesApiTool { + name: "test_server/do_something_cool".to_string(), + parameters: JsonSchema::Object { + properties: BTreeMap::from([ + ( + "string_argument".to_string(), + JsonSchema::String { description: None } + ), + ( + "number_argument".to_string(), + JsonSchema::Number { description: None } + ), + ( + "object_argument".to_string(), + JsonSchema::Object { + properties: BTreeMap::from([ + ( + "string_property".to_string(), + JsonSchema::String { description: None } + ), + ( + "number_property".to_string(), + JsonSchema::Number { description: None } + ), + ]), + required: Some(vec![ + "string_property".to_string(), + "number_property".to_string(), + ]), + additional_properties: Some(false.into()), + }, + ), + ]), + required: None, + additional_properties: None, + }, + description: "Do something cool".to_string(), + strict: false, + output_schema: Some(mcp_call_tool_result_output_schema(serde_json::json!({}))), + defer_loading: None, + }) + ); +} + +#[test] +fn test_build_specs_mcp_tools_sorted_by_name() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let tools_map = HashMap::from([ + ( + "test_server/do".to_string(), + mcp_tool("a", "a", serde_json::json!({"type": "object"})), + ), + ( + "test_server/something".to_string(), + mcp_tool("b", "b", serde_json::json!({"type": "object"})), + ), + ( + "test_server/cool".to_string(), + mcp_tool("c", "c", serde_json::json!({"type": "object"})), + ), + ]); + + let (tools, _) = build_specs(&tools_config, Some(tools_map), /*app_tools*/ None, &[]); + + let mcp_names: Vec<_> = tools + .iter() + .map(|tool| tool.name().to_string()) + .filter(|name| name.starts_with("test_server/")) + .collect(); + let expected = vec![ + "test_server/cool".to_string(), + "test_server/do".to_string(), + "test_server/something".to_string(), + ]; + assert_eq!(mcp_names, expected); +} + +#[test] +fn search_tool_description_lists_each_codex_apps_connector_once() { + let model_info = search_capable_model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::Apps); + features.enable(Feature::ToolSearch); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (tools, _) = build_specs( + &tools_config, + Some(HashMap::from([ + ( + "mcp__codex_apps__calendar_create_event".to_string(), + mcp_tool( + "calendar_create_event", + "Create calendar event", + serde_json::json!({"type": "object"}), + ), + ), + ( + "mcp__rmcp__echo".to_string(), + mcp_tool("echo", "Echo", serde_json::json!({"type": "object"})), + ), + ])), + Some(vec![ + app_tool( + "_create_event", + "mcp__codex_apps__calendar", + CODEX_APPS_MCP_SERVER_NAME, + Some("Calendar"), + Some("Plan events and manage your calendar."), + ), + app_tool( + "_list_events", + "mcp__codex_apps__calendar", + CODEX_APPS_MCP_SERVER_NAME, + Some("Calendar"), + Some("Plan events and manage your calendar."), + ), + app_tool( + "_search_threads", + "mcp__codex_apps__gmail", + CODEX_APPS_MCP_SERVER_NAME, + Some("Gmail"), + Some("Find and summarize email threads."), + ), + app_tool( + "echo", "rmcp", "rmcp", /*connector_name*/ None, + /*connector_description*/ None, + ), + ]), + &[], + ); + + let search_tool = find_tool(&tools, TOOL_SEARCH_TOOL_NAME); + let ToolSpec::ToolSearch { description, .. } = &search_tool.spec else { + panic!("expected tool_search tool"); + }; + let description = description.as_str(); + assert!(description.contains("- Calendar: Plan events and manage your calendar.")); + assert!(description.contains("- Gmail: Find and summarize email threads.")); + assert_eq!( + description + .matches("- Calendar: Plan events and manage your calendar.") + .count(), + 1 + ); + assert!(!description.contains("mcp__rmcp__echo")); +} + +#[test] +fn search_tool_requires_model_capability_and_feature_flag() { + let model_info = search_capable_model_info(); + let app_tools = Some(vec![app_tool( + "calendar_create_event", + "mcp__codex_apps__calendar", + CODEX_APPS_MCP_SERVER_NAME, + Some("Calendar"), + /*connector_description*/ None, + )]); + + let features = Features::with_defaults(); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &ModelInfo { + supports_search_tool: false, + ..model_info.clone() + }, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + app_tools.clone(), + &[], + ); + assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); + + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + app_tools.clone(), + &[], + ); + assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); + + let mut features = Features::with_defaults(); + features.enable(Feature::ToolSearch); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs(&tools_config, /*mcp_tools*/ None, app_tools, &[]); + assert_contains_tool_names(&tools, &[TOOL_SEARCH_TOOL_NAME]); +} + +#[test] +fn tool_suggest_is_not_registered_without_feature_flag() { + let model_info = search_capable_model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::ToolSearch); + features.enable(Feature::Apps); + features.enable(Feature::Plugins); + features.disable(Feature::ToolSuggest); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs_with_discoverable_tools( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + Some(vec![discoverable_connector( + "connector_2128aebfecb84f64a069897515042a44", + "Google Calendar", + "Plan events and schedules.", + )]), + &[], + ); + + assert!( + !tools + .iter() + .any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME) + ); +} + +#[test] +fn tool_suggest_can_be_registered_without_search_tool() { + let model_info = ModelInfo { + supports_search_tool: false, + ..search_capable_model_info() + }; + let mut features = Features::with_defaults(); + features.enable(Feature::Apps); + features.enable(Feature::Plugins); + features.enable(Feature::ToolSuggest); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + let (tools, _) = build_specs_with_discoverable_tools( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + Some(vec![discoverable_connector( + "connector_2128aebfecb84f64a069897515042a44", + "Google Calendar", + "Plan events and schedules.", + )]), + &[], + ); + + assert_contains_tool_names(&tools, &[TOOL_SUGGEST_TOOL_NAME]); + assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); + + let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); + let ToolSpec::Function(ResponsesApiTool { description, .. }) = &tool_suggest.spec else { + panic!("expected function tool"); + }; + assert!(description.contains( + "Suggests a missing connector in an installed plugin, or in narrower cases a not installed but discoverable plugin" + )); + assert!(description.contains( + "You've already tried to find a matching available tool for the user's request but couldn't find a good match. This includes `tool_search` (if available) and other means." + )); +} + +#[test] +fn tool_suggest_description_lists_discoverable_tools() { + let model_info = search_capable_model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::Apps); + features.enable(Feature::Plugins); + features.enable(Feature::ToolSearch); + features.enable(Feature::ToolSuggest); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let discoverable_tools = vec![ + discoverable_connector( + "connector_2128aebfecb84f64a069897515042a44", + "Google Calendar", + "Plan events and schedules.", + ), + discoverable_connector( + "connector_68df038e0ba48191908c8434991bbac2", + "Gmail", + "Find and summarize email threads.", + ), + DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo { + id: "sample@test".to_string(), + name: "Sample Plugin".to_string(), + description: None, + has_skills: true, + mcp_server_names: vec!["sample-docs".to_string()], + app_connector_ids: vec!["connector_sample".to_string()], + })), + ]; + + let (tools, _) = build_specs_with_discoverable_tools( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + Some(discoverable_tools), + &[], + ); + + let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); + let ToolSpec::Function(ResponsesApiTool { + description, + parameters, + .. + }) = &tool_suggest.spec + else { + panic!("expected function tool"); + }; + assert!(description.contains( + "Suggests a missing connector in an installed plugin, or in narrower cases a not installed but discoverable plugin" + )); + assert!(description.contains("Google Calendar")); + assert!(description.contains("Gmail")); + assert!(description.contains("Sample Plugin")); + assert!(description.contains("Plan events and schedules.")); + assert!(description.contains("Find and summarize email threads.")); + assert!(description.contains("id: `sample@test`, type: plugin, action: install")); + assert!(description.contains("`action_type`: `install` or `enable`")); + assert!( + description.contains("skills; MCP servers: sample-docs; app connectors: connector_sample") + ); + assert!( + description.contains( + "You've already tried to find a matching available tool for the user's request but couldn't find a good match. This includes `tool_search` (if available) and other means." + ) + ); + assert!(description.contains( + "For connectors/apps that are not installed but needed for an installed plugin, suggest to install them if the task requirements match precisely." + )); + assert!(description.contains( + "For plugins that are not installed but discoverable, only suggest discoverable and installable plugins when the user's intent very explicitly and unambiguously matches that plugin itself." + )); + assert!(description.contains( + "Do not suggest a plugin just because one of its connectors or capabilities seems relevant." + )); + assert!(description.contains( + "Apply the stricter explicit-and-unambiguous rule for *discoverable tools* like plugin install suggestions; *missing tools* like connector install suggestions continue to use the normal clear-fit standard." + )); + assert!(description.contains("DO NOT explore or recommend tools that are not on this list.")); + assert!(!description.contains("{{discoverable_tools}}")); + assert!(!description.contains("tool_search fails to find a good match")); + let JsonSchema::Object { required, .. } = parameters else { + panic!("expected object parameters"); + }; + assert_eq!( + required.as_ref(), + Some(&vec![ + "tool_type".to_string(), + "action_type".to_string(), + "tool_id".to_string(), + "suggest_reason".to_string(), + ]) + ); +} + +#[test] +fn code_mode_augments_mcp_tool_descriptions_with_namespaced_sample() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::CodeMode); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (tools, _) = build_specs( + &tools_config, + Some(HashMap::from([( + "mcp__sample__echo".to_string(), + mcp_tool( + "echo", + "Echo text", + serde_json::json!({ + "type": "object", + "properties": { + "message": {"type": "string"} + }, + "required": ["message"], + "additionalProperties": false + }), + ), + )])), + /*app_tools*/ None, + &[], + ); + + let ToolSpec::Function(ResponsesApiTool { description, .. }) = + &find_tool(&tools, "mcp__sample__echo").spec + else { + panic!("expected function tool"); + }; + + assert_eq!( + description, + "Echo text\n\nexec tool declaration:\n```ts\ndeclare const tools: { mcp__sample__echo(args: { message: string; }): Promise<{ _meta?: unknown; content: Array; isError?: boolean; structuredContent?: unknown; }>; };\n```" + ); +} + +#[test] +fn code_mode_augments_builtin_tool_descriptions_with_typed_sample() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::CodeMode); + features.enable(Feature::UnifiedExec); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let ToolSpec::Function(ResponsesApiTool { description, .. }) = + &find_tool(&tools, VIEW_IMAGE_TOOL_NAME).spec + else { + panic!("expected function tool"); + }; + + assert_eq!( + description, + "View a local image from the filesystem (only use if given a full filepath by the user, and the image isn't already attached to the thread context within tags).\n\nexec tool declaration:\n```ts\ndeclare const tools: { view_image(args: { path: string; }): Promise<{ detail: string | null; image_url: string; }>; };\n```" + ); +} + +#[test] +fn code_mode_only_exec_description_includes_full_nested_tool_details() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::CodeMode); + features.enable(Feature::CodeModeOnly); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let ToolSpec::Freeform(FreeformTool { description, .. }) = &find_tool(&tools, "exec").spec + else { + panic!("expected freeform tool"); + }; + + assert!(!description.contains("Enabled nested tools:")); + assert!(!description.contains("Nested tool reference:")); + assert!(description.starts_with( + "Use `exec/wait` tool to run all other tools, do not attempt to use any other tools directly" + )); + assert!(description.contains("### `update_plan` (`update_plan`)")); + assert!(description.contains("### `view_image` (`view_image`)")); +} + +#[test] +fn code_mode_exec_description_omits_nested_tool_details_when_not_code_mode_only() { + let model_info = model_info(); + let mut features = Features::with_defaults(); + features.enable(Feature::CodeMode); + let available_models = Vec::new(); + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + available_models: &available_models, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + session_source: SessionSource::Cli, + sandbox_policy: &SandboxPolicy::DangerFullAccess, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + }); + + let (tools, _) = build_specs( + &tools_config, + /*mcp_tools*/ None, + /*app_tools*/ None, + &[], + ); + let ToolSpec::Freeform(FreeformTool { description, .. }) = &find_tool(&tools, "exec").spec + else { + panic!("expected freeform tool"); + }; + + assert!(!description.starts_with( + "Use `exec/wait` tool to run all other tools, do not attempt to use any other tools directly" + )); + assert!(!description.contains("### `update_plan` (`update_plan`)")); + assert!(!description.contains("### `view_image` (`view_image`)")); +} + +fn model_info() -> ModelInfo { + serde_json::from_value(json!({ + "slug": "gpt-5-codex", + "display_name": "GPT-5 Codex", + "description": null, + "supported_reasoning_levels": [], + "shell_type": "shell_command", + "visibility": "list", + "supported_in_api": true, + "priority": 1, + "availability_nux": null, + "upgrade": null, + "base_instructions": "base", + "model_messages": null, + "supports_reasoning_summaries": false, + "default_reasoning_summary": "auto", + "support_verbosity": false, + "default_verbosity": null, + "apply_patch_tool_type": "freeform", + "truncation_policy": { + "mode": "bytes", + "limit": 10000 + }, + "supports_parallel_tool_calls": false, + "supports_image_detail_original": false, + "context_window": null, + "auto_compact_token_limit": null, + "effective_context_window_percent": 95, + "experimental_supported_tools": [], + "input_modalities": ["text", "image"], + "supports_search_tool": false + })) + .expect("deserialize test model") +} + +fn search_capable_model_info() -> ModelInfo { + ModelInfo { + supports_search_tool: true, + ..model_info() + } +} + +fn build_specs<'a>( + config: &ToolsConfig, + mcp_tools: Option>, + app_tools: Option>>, + dynamic_tools: &[DynamicToolSpec], +) -> (Vec, Vec) { + build_specs_with_discoverable_tools( + config, + mcp_tools, + app_tools, + /*discoverable_tools*/ None, + dynamic_tools, + ) +} + +fn build_specs_with_discoverable_tools<'a>( + config: &ToolsConfig, + mcp_tools: Option>, + app_tools: Option>>, + discoverable_tools: Option>, + dynamic_tools: &[DynamicToolSpec], +) -> (Vec, Vec) { + let plan = build_tool_registry_plan( + config, + ToolRegistryPlanParams { + mcp_tools: mcp_tools.as_ref(), + app_tools: app_tools.as_deref(), + discoverable_tools: discoverable_tools.as_deref(), + dynamic_tools, + default_agent_type_description: DEFAULT_AGENT_TYPE_DESCRIPTION, + wait_agent_timeouts: wait_agent_timeout_options(), + codex_apps_mcp_server_name: CODEX_APPS_MCP_SERVER_NAME, + }, + ); + (plan.specs, plan.handlers) +} + +fn mcp_tool(name: &str, description: &str, input_schema: serde_json::Value) -> rmcp::model::Tool { + rmcp::model::Tool { + name: name.to_string().into(), + title: None, + description: Some(description.to_string().into()), + input_schema: std::sync::Arc::new(rmcp::model::object(input_schema)), + output_schema: None, + annotations: None, + execution: None, + icons: None, + meta: None, + } +} + +fn discoverable_connector(id: &str, name: &str, description: &str) -> DiscoverableTool { + let slug = name.replace(' ', "-").to_lowercase(); + DiscoverableTool::Connector(Box::new(AppInfo { + id: id.to_string(), + name: name.to_string(), + description: Some(description.to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: Some(format!("https://chatgpt.com/apps/{slug}/{id}")), + is_accessible: false, + is_enabled: true, + plugin_display_names: Vec::new(), + })) +} + +fn app_tool<'a>( + tool_name: &'a str, + tool_namespace: &'a str, + server_name: &'a str, + connector_name: Option<&'a str>, + connector_description: Option<&'a str>, +) -> ToolRegistryPlanAppTool<'a> { + ToolRegistryPlanAppTool { + tool_name, + tool_namespace, + server_name, + connector_name, + connector_description, + } +} + +fn assert_contains_tool_names(tools: &[ConfiguredToolSpec], expected_subset: &[&str]) { + use std::collections::HashSet; + + let mut names = HashSet::new(); + let mut duplicates = Vec::new(); + for name in tools.iter().map(ConfiguredToolSpec::name) { + if !names.insert(name) { + duplicates.push(name); + } + } + assert!( + duplicates.is_empty(), + "duplicate tool entries detected: {duplicates:?}" + ); + for expected in expected_subset { + assert!( + names.contains(expected), + "expected tool {expected} to be present; had: {names:?}" + ); + } +} + +fn assert_lacks_tool_name(tools: &[ConfiguredToolSpec], expected_absent: &str) { + let names = tools + .iter() + .map(ConfiguredToolSpec::name) + .collect::>(); + assert!( + !names.contains(&expected_absent), + "expected tool {expected_absent} to be absent; had: {names:?}" + ); +} + +fn request_user_input_tool_spec(default_mode_request_user_input: bool) -> ToolSpec { + create_request_user_input_tool(request_user_input_tool_description( + default_mode_request_user_input, + )) +} + +fn spawn_agent_tool_options(config: &ToolsConfig) -> SpawnAgentToolOptions<'_> { + SpawnAgentToolOptions { + available_models: &config.available_models, + agent_type_description: agent_type_description(config, DEFAULT_AGENT_TYPE_DESCRIPTION), + } +} + +fn wait_agent_timeout_options() -> WaitAgentTimeoutOptions { + WaitAgentTimeoutOptions { + default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS, + min_timeout_ms: MIN_WAIT_TIMEOUT_MS, + max_timeout_ms: MAX_WAIT_TIMEOUT_MS, + } +} + +fn find_tool<'a>(tools: &'a [ConfiguredToolSpec], expected_name: &str) -> &'a ConfiguredToolSpec { + tools + .iter() + .find(|tool| tool.name() == expected_name) + .unwrap_or_else(|| panic!("expected tool {expected_name}")) +} + +fn strip_descriptions_schema(schema: &mut JsonSchema) { + match schema { + JsonSchema::Boolean { description } + | JsonSchema::String { description } + | JsonSchema::Number { description } => { + *description = None; + } + JsonSchema::Array { items, description } => { + strip_descriptions_schema(items); + *description = None; + } + JsonSchema::Object { + properties, + required: _, + additional_properties, + } => { + for value in properties.values_mut() { + strip_descriptions_schema(value); + } + if let Some(AdditionalProperties::Schema(schema)) = additional_properties { + strip_descriptions_schema(schema); + } + } + } +} + +fn strip_descriptions_tool(spec: &mut ToolSpec) { + match spec { + ToolSpec::ToolSearch { parameters, .. } => strip_descriptions_schema(parameters), + ToolSpec::Function(ResponsesApiTool { parameters, .. }) => { + strip_descriptions_schema(parameters); + } + ToolSpec::Freeform(FreeformTool { .. }) + | ToolSpec::LocalShell {} + | ToolSpec::ImageGeneration { .. } + | ToolSpec::WebSearch { .. } => {} + } +} From f32a5e84bf925db613c1738052aa96bfc1f954f6 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Apr 2026 00:39:20 -0700 Subject: [PATCH 3/5] [codex] Move config types into codex-config (#16523) ## Why `codex-rs/core/src/config/types.rs` is a plain config-type module with no dependency on `codex-core`. Moving it into `codex-config` shrinks the core crate and gives config-only consumers a more natural dependency boundary. ## What Changed - Added `codex_config::types` with the moved structs, enums, constants, and unit tests. - Kept `codex_core::config::types` as a compatibility re-export to avoid a broad call-site migration in this PR. - Switched notice-table writes in `core/src/config/edit.rs` to a local `NOTICE_TABLE_KEY` constant. - Added the `wildmatch` runtime dependency and `tempfile` test dependency to `codex-config`. --- codex-rs/Cargo.lock | 3 +- codex-rs/config/Cargo.toml | 2 + codex-rs/config/src/lib.rs | 1 + codex-rs/config/src/types.rs | 687 +++++++++++++++++ .../src/config => config/src}/types_tests.rs | 0 codex-rs/core/Cargo.toml | 1 - codex-rs/core/src/config/edit.rs | 13 +- codex-rs/core/src/config/types.rs | 693 +----------------- 8 files changed, 700 insertions(+), 700 deletions(-) create mode 100644 codex-rs/config/src/types.rs rename codex-rs/{core/src/config => config/src}/types_tests.rs (100%) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 4cb526430f..d5bab66c66 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1803,11 +1803,13 @@ dependencies = [ "serde_json", "serde_path_to_error", "sha2", + "tempfile", "thiserror 2.0.18", "tokio", "toml 0.9.11+spec-1.1.0", "toml_edit 0.24.0+spec-1.1.0", "tracing", + "wildmatch", ] [[package]] @@ -1936,7 +1938,6 @@ dependencies = [ "uuid", "walkdir", "which 8.0.0", - "wildmatch", "windows-sys 0.52.0", "wiremock", "zip", diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.toml index f1bd2dba16..0b440263eb 100644 --- a/codex-rs/config/Cargo.toml +++ b/codex-rs/config/Cargo.toml @@ -24,8 +24,10 @@ tokio = { workspace = true, features = ["fs"] } toml = { workspace = true } toml_edit = { workspace = true } tracing = { workspace = true } +wildmatch = { workspace = true } [dev-dependencies] anyhow = { workspace = true } pretty_assertions = { workspace = true } +tempfile = { workspace = true } tokio = { workspace = true, features = ["full"] } diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs index f769f2496c..2196011323 100644 --- a/codex-rs/config/src/lib.rs +++ b/codex-rs/config/src/lib.rs @@ -11,6 +11,7 @@ mod project_root_markers; mod requirements_exec_policy; mod skills_config; mod state; +pub mod types; pub const CONFIG_TOML_FILE: &str = "config.toml"; diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs new file mode 100644 index 0000000000..c523833525 --- /dev/null +++ b/codex-rs/config/src/types.rs @@ -0,0 +1,687 @@ +//! Types used to define loaded and effective Codex configuration values. + +// Note this file should generally be restricted to simple struct/enum +// definitions that do not contain business logic. + +pub use crate::mcp_types::AppToolApproval; +pub use crate::mcp_types::McpServerConfig; +pub use crate::mcp_types::McpServerDisabledReason; +pub use crate::mcp_types::McpServerToolConfig; +pub use crate::mcp_types::McpServerTransportConfig; +pub use crate::mcp_types::RawMcpServerConfig; +pub use codex_protocol::config_types::AltScreenMode; +pub use codex_protocol::config_types::ApprovalsReviewer; +pub use codex_protocol::config_types::ModeKind; +pub use codex_protocol::config_types::Personality; +pub use codex_protocol::config_types::ServiceTier; +pub use codex_protocol::config_types::WebSearchMode; +use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::fmt; +use wildmatch::WildMatchPattern; + +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; + +pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev"; +pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 16; +pub const DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS: i64 = 30; +pub const DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS: i64 = 6; +pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION: usize = 256; +pub const DEFAULT_MEMORIES_MAX_UNUSED_DAYS: i64 = 30; + +const fn default_enabled() -> bool { + true +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum WindowsSandboxModeToml { + Elevated, + Unelevated, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct WindowsToml { + pub sandbox: Option, + /// Defaults to `true`. Set to `false` to launch the final sandboxed child + /// process on `Winsta0\\Default` instead of a private desktop. + pub sandbox_private_desktop: Option, +} + +#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, JsonSchema)] +pub enum UriBasedFileOpener { + #[serde(rename = "vscode")] + VsCode, + + #[serde(rename = "vscode-insiders")] + VsCodeInsiders, + + #[serde(rename = "windsurf")] + Windsurf, + + #[serde(rename = "cursor")] + Cursor, + + /// Option to disable the URI-based file opener. + #[serde(rename = "none")] + None, +} + +impl UriBasedFileOpener { + pub fn get_scheme(&self) -> Option<&str> { + match self { + UriBasedFileOpener::VsCode => Some("vscode"), + UriBasedFileOpener::VsCodeInsiders => Some("vscode-insiders"), + UriBasedFileOpener::Windsurf => Some("windsurf"), + UriBasedFileOpener::Cursor => Some("cursor"), + UriBasedFileOpener::None => None, + } + } +} + +/// Settings that govern if and what will be written to `~/.codex/history.jsonl`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct History { + /// If true, history entries will not be written to disk. + pub persistence: HistoryPersistence, + + /// If set, the maximum size of the history file in bytes. The oldest entries + /// are dropped once the file exceeds this limit. + pub max_bytes: Option, +} + +#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Default, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum HistoryPersistence { + /// Save all history entries to disk. + #[default] + SaveAll, + /// Do not write history to disk. + None, +} + +// ===== Analytics configuration ===== + +/// Analytics settings loaded from config.toml. Fields are optional so we can apply defaults. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AnalyticsConfigToml { + /// When `false`, disables analytics across Codex product surfaces in this profile. + pub enabled: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FeedbackConfigToml { + /// When `false`, disables the feedback flow across Codex product surfaces. + pub enabled: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ToolSuggestDiscoverableType { + Connector, + Plugin, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ToolSuggestDiscoverable { + #[serde(rename = "type")] + pub kind: ToolSuggestDiscoverableType, + pub id: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ToolSuggestConfig { + #[serde(default)] + pub discoverables: Vec, +} + +/// Memories settings loaded from config.toml. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct MemoriesToml { + /// When `true`, web searches and MCP tool calls mark the thread `memory_mode` as `"polluted"`. + pub no_memories_if_mcp_or_web_search: Option, + /// When `false`, newly created threads are stored with `memory_mode = "disabled"` in the state DB. + pub generate_memories: Option, + /// When `false`, skip injecting memory usage instructions into developer prompts. + pub use_memories: Option, + /// Maximum number of recent raw memories retained for global consolidation. + pub max_raw_memories_for_consolidation: Option, + /// Maximum number of days since a memory was last used before it becomes ineligible for phase 2 selection. + pub max_unused_days: Option, + /// Maximum age of the threads used for memories. + pub max_rollout_age_days: Option, + /// Maximum number of rollout candidates processed per pass. + pub max_rollouts_per_startup: Option, + /// Minimum idle time between last thread activity and memory creation (hours). > 12h recommended. + pub min_rollout_idle_hours: Option, + /// Model used for thread summarisation. + pub extract_model: Option, + /// Model used for memory consolidation. + pub consolidation_model: Option, +} + +/// Effective memories settings after defaults are applied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemoriesConfig { + pub no_memories_if_mcp_or_web_search: bool, + pub generate_memories: bool, + pub use_memories: bool, + pub max_raw_memories_for_consolidation: usize, + pub max_unused_days: i64, + pub max_rollout_age_days: i64, + pub max_rollouts_per_startup: usize, + pub min_rollout_idle_hours: i64, + pub extract_model: Option, + pub consolidation_model: Option, +} + +impl Default for MemoriesConfig { + fn default() -> Self { + Self { + no_memories_if_mcp_or_web_search: false, + generate_memories: true, + use_memories: true, + max_raw_memories_for_consolidation: DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, + max_unused_days: DEFAULT_MEMORIES_MAX_UNUSED_DAYS, + max_rollout_age_days: DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS, + max_rollouts_per_startup: DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP, + min_rollout_idle_hours: DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS, + extract_model: None, + consolidation_model: None, + } + } +} + +impl From for MemoriesConfig { + fn from(toml: MemoriesToml) -> Self { + let defaults = Self::default(); + Self { + no_memories_if_mcp_or_web_search: toml + .no_memories_if_mcp_or_web_search + .unwrap_or(defaults.no_memories_if_mcp_or_web_search), + generate_memories: toml.generate_memories.unwrap_or(defaults.generate_memories), + use_memories: toml.use_memories.unwrap_or(defaults.use_memories), + max_raw_memories_for_consolidation: toml + .max_raw_memories_for_consolidation + .unwrap_or(defaults.max_raw_memories_for_consolidation) + .min(4096), + max_unused_days: toml + .max_unused_days + .unwrap_or(defaults.max_unused_days) + .clamp(0, 365), + max_rollout_age_days: toml + .max_rollout_age_days + .unwrap_or(defaults.max_rollout_age_days) + .clamp(0, 90), + max_rollouts_per_startup: toml + .max_rollouts_per_startup + .unwrap_or(defaults.max_rollouts_per_startup) + .min(128), + min_rollout_idle_hours: toml + .min_rollout_idle_hours + .unwrap_or(defaults.min_rollout_idle_hours) + .clamp(1, 48), + extract_model: toml.extract_model, + consolidation_model: toml.consolidation_model, + } + } +} + +/// Default settings that apply to all apps. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppsDefaultConfig { + /// When `false`, apps are disabled unless overridden by per-app settings. + #[serde(default = "default_enabled")] + pub enabled: bool, + + /// Whether tools with `destructive_hint = true` are allowed by default. + #[serde( + default = "default_enabled", + skip_serializing_if = "std::clone::Clone::clone" + )] + pub destructive_enabled: bool, + + /// Whether tools with `open_world_hint = true` are allowed by default. + #[serde( + default = "default_enabled", + skip_serializing_if = "std::clone::Clone::clone" + )] + pub open_world_enabled: bool, +} + +/// Per-tool settings for a single app tool. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppToolConfig { + /// Whether this tool is enabled. `Some(true)` explicitly allows this tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enabled: Option, + + /// Approval mode for this tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approval_mode: Option, +} + +/// Tool settings for a single app. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppToolsConfig { + /// Per-tool overrides keyed by tool name (for example `repos/list`). + #[serde(default, flatten)] + pub tools: HashMap, +} + +/// Config values for a single app/connector. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppConfig { + /// When `false`, Codex does not surface this app. + #[serde(default = "default_enabled")] + pub enabled: bool, + + /// Whether tools with `destructive_hint = true` are allowed for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destructive_enabled: Option, + + /// Whether tools with `open_world_hint = true` are allowed for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_world_enabled: Option, + + /// Approval mode for tools in this app unless a tool override exists. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_tools_approval_mode: Option, + + /// Whether tools are enabled by default for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_tools_enabled: Option, + + /// Per-tool settings for this app. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tools: Option, +} + +/// App/connector settings loaded from `config.toml`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AppsConfigToml { + /// Default settings for all apps. + #[serde(default, rename = "_default", skip_serializing_if = "Option::is_none")] + pub default: Option, + + /// Per-app settings keyed by app ID (for example `[apps.google_drive]`). + #[serde(default, flatten)] + pub apps: HashMap, +} + +// ===== OTEL configuration ===== + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum OtelHttpProtocol { + /// Binary payload + Binary, + /// JSON payload + Json, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +#[serde(rename_all = "kebab-case")] +pub struct OtelTlsConfig { + pub ca_certificate: Option, + pub client_certificate: Option, + pub client_private_key: Option, +} + +/// Which OTEL exporter to use. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] +#[schemars(deny_unknown_fields)] +#[serde(rename_all = "kebab-case")] +pub enum OtelExporterKind { + None, + Statsig, + OtlpHttp { + endpoint: String, + #[serde(default)] + headers: HashMap, + protocol: OtelHttpProtocol, + #[serde(default)] + tls: Option, + }, + OtlpGrpc { + endpoint: String, + #[serde(default)] + headers: HashMap, + #[serde(default)] + tls: Option, + }, +} + +/// OTEL settings loaded from config.toml. Fields are optional so we can apply defaults. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct OtelConfigToml { + /// Log user prompt in traces + pub log_user_prompt: Option, + + /// Mark traces with environment (dev, staging, prod, test). Defaults to dev. + pub environment: Option, + + /// Optional log exporter + pub exporter: Option, + + /// Optional trace exporter + pub trace_exporter: Option, + + /// Optional metrics exporter + pub metrics_exporter: Option, +} + +/// Effective OTEL settings after defaults are applied. +#[derive(Debug, Clone, PartialEq)] +pub struct OtelConfig { + pub log_user_prompt: bool, + pub environment: String, + pub exporter: OtelExporterKind, + pub trace_exporter: OtelExporterKind, + pub metrics_exporter: OtelExporterKind, +} + +impl Default for OtelConfig { + fn default() -> Self { + OtelConfig { + log_user_prompt: false, + environment: DEFAULT_OTEL_ENVIRONMENT.to_owned(), + exporter: OtelExporterKind::None, + trace_exporter: OtelExporterKind::None, + metrics_exporter: OtelExporterKind::Statsig, + } + } +} + +#[derive(Serialize, Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum Notifications { + Enabled(bool), + Custom(Vec), +} + +impl Default for Notifications { + fn default() -> Self { + Self::Enabled(true) + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, Default)] +#[serde(rename_all = "lowercase")] +pub enum NotificationMethod { + #[default] + Auto, + Osc9, + Bel, +} + +impl fmt::Display for NotificationMethod { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + NotificationMethod::Auto => write!(f, "auto"), + NotificationMethod::Osc9 => write!(f, "osc9"), + NotificationMethod::Bel => write!(f, "bel"), + } + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ModelAvailabilityNuxConfig { + /// Number of times a startup availability NUX has been shown per model slug. + #[serde(default, flatten)] + pub shown_count: HashMap, +} + +/// Collection of settings that are specific to the TUI. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct Tui { + /// Enable desktop notifications from the TUI when the terminal is unfocused. + /// Defaults to `true`. + #[serde(default)] + pub notifications: Notifications, + + /// Notification method to use for unfocused terminal notifications. + /// Defaults to `auto`. + #[serde(default)] + pub notification_method: NotificationMethod, + + /// Enable animations (welcome screen, shimmer effects, spinners). + /// Defaults to `true`. + #[serde(default = "default_true")] + pub animations: bool, + + /// Show startup tooltips in the TUI welcome screen. + /// Defaults to `true`. + #[serde(default = "default_true")] + pub show_tooltips: bool, + + /// Controls whether the TUI uses the terminal's alternate screen buffer. + /// + /// - `auto` (default): Disable alternate screen in Zellij, enable elsewhere. + /// - `always`: Always use alternate screen (original behavior). + /// - `never`: Never use alternate screen (inline mode only, preserves scrollback). + /// + /// Using alternate screen provides a cleaner fullscreen experience but prevents + /// scrollback in terminal multiplexers like Zellij that follow the xterm spec. + #[serde(default)] + pub alternate_screen: AltScreenMode, + + /// Ordered list of status line item identifiers. + /// + /// When set, the TUI renders the selected items as the status line. + /// When unset, the TUI defaults to: `model-with-reasoning`, `context-remaining`, and + /// `current-dir`. + #[serde(default)] + pub status_line: Option>, + + /// Ordered list of terminal title item identifiers. + /// + /// When set, the TUI renders the selected items into the terminal window/tab title. + /// When unset, the TUI defaults to: `spinner` and `project`. + #[serde(default)] + pub terminal_title: Option>, + + /// Syntax highlighting theme name (kebab-case). + /// + /// When set, overrides automatic light/dark theme detection. + /// Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes. + #[serde(default)] + pub theme: Option, + + /// Startup tooltip availability NUX state persisted by the TUI. + #[serde(default)] + pub model_availability_nux: ModelAvailabilityNuxConfig, +} + +const fn default_true() -> bool { + true +} + +/// Settings for notices we display to users via the tui and app-server clients +/// (primarily the Codex IDE extension). NOTE: these are different from +/// notifications - notices are warnings, NUX screens, acknowledgements, etc. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +pub struct Notice { + /// Tracks whether the user has acknowledged the full access warning prompt. + pub hide_full_access_warning: Option, + /// Tracks whether the user has acknowledged the Windows world-writable directories warning. + pub hide_world_writable_warning: Option, + /// Tracks whether the user opted out of the rate limit model switch reminder. + pub hide_rate_limit_model_nudge: Option, + /// Tracks whether the user has seen the model migration prompt + pub hide_gpt5_1_migration_prompt: Option, + /// Tracks whether the user has seen the gpt-5.1-codex-max migration prompt + #[serde(rename = "hide_gpt-5.1-codex-max_migration_prompt")] + pub hide_gpt_5_1_codex_max_migration_prompt: Option, + /// Tracks acknowledged model migrations as old->new model slug mappings. + #[serde(default)] + pub model_migrations: BTreeMap, +} + +pub use crate::skills_config::BundledSkillsConfig; +pub use crate::skills_config::SkillConfig; +pub use crate::skills_config::SkillsConfig; + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct PluginConfig { + #[serde(default = "default_enabled")] + pub enabled: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SandboxWorkspaceWrite { + #[serde(default)] + pub writable_roots: Vec, + #[serde(default)] + pub network_access: bool, + #[serde(default)] + pub exclude_tmpdir_env_var: bool, + #[serde(default)] + pub exclude_slash_tmp: bool, +} + +impl From for codex_app_server_protocol::SandboxSettings { + fn from(sandbox_workspace_write: SandboxWorkspaceWrite) -> Self { + Self { + writable_roots: sandbox_workspace_write.writable_roots, + network_access: Some(sandbox_workspace_write.network_access), + exclude_tmpdir_env_var: Some(sandbox_workspace_write.exclude_tmpdir_env_var), + exclude_slash_tmp: Some(sandbox_workspace_write.exclude_slash_tmp), + } + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum ShellEnvironmentPolicyInherit { + /// "Core" environment variables for the platform. On UNIX, this would + /// include HOME, LOGNAME, PATH, SHELL, and USER, among others. + Core, + + /// Inherits the full environment from the parent process. + #[default] + All, + + /// Do not inherit any environment variables from the parent process. + None, +} + +/// Policy for building the `env` when spawning a process via either the +/// `shell` or `local_shell` tool. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ShellEnvironmentPolicyToml { + pub inherit: Option, + + pub ignore_default_excludes: Option, + + /// List of regular expressions. + pub exclude: Option>, + + pub r#set: Option>, + + /// List of regular expressions. + pub include_only: Option>, + + pub experimental_use_profile: Option, +} + +pub type EnvironmentVariablePattern = WildMatchPattern<'*', '?'>; + +/// Deriving the `env` based on this policy works as follows: +/// 1. Create an initial map based on the `inherit` policy. +/// 2. If `ignore_default_excludes` is false, filter the map using the default +/// exclude pattern(s), which are: `"*KEY*"`, `"*SECRET*"`, and `"*TOKEN*"`. +/// 3. If `exclude` is not empty, filter the map using the provided patterns. +/// 4. Insert any entries from `r#set` into the map. +/// 5. If non-empty, filter the map using the `include_only` patterns. +#[derive(Debug, Clone, PartialEq)] +pub struct ShellEnvironmentPolicy { + /// Starting point when building the environment. + pub inherit: ShellEnvironmentPolicyInherit, + + /// True to skip the check to exclude default environment variables that + /// contain "KEY", "SECRET", or "TOKEN" in their name. Defaults to true. + pub ignore_default_excludes: bool, + + /// Environment variable names to exclude from the environment. + pub exclude: Vec, + + /// (key, value) pairs to insert in the environment. + pub r#set: HashMap, + + /// Environment variable names to retain in the environment. + pub include_only: Vec, + + /// If true, the shell profile will be used to run the command. + pub use_profile: bool, +} + +impl From for ShellEnvironmentPolicy { + fn from(toml: ShellEnvironmentPolicyToml) -> Self { + // Default to inheriting the full environment when not specified. + let inherit = toml.inherit.unwrap_or(ShellEnvironmentPolicyInherit::All); + let ignore_default_excludes = toml.ignore_default_excludes.unwrap_or(true); + let exclude = toml + .exclude + .unwrap_or_default() + .into_iter() + .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) + .collect(); + let r#set = toml.r#set.unwrap_or_default(); + let include_only = toml + .include_only + .unwrap_or_default() + .into_iter() + .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) + .collect(); + let use_profile = toml.experimental_use_profile.unwrap_or(false); + + Self { + inherit, + ignore_default_excludes, + exclude, + r#set, + include_only, + use_profile, + } + } +} + +impl Default for ShellEnvironmentPolicy { + fn default() -> Self { + Self { + inherit: ShellEnvironmentPolicyInherit::All, + ignore_default_excludes: true, + exclude: Vec::new(), + r#set: HashMap::new(), + include_only: Vec::new(), + use_profile: false, + } + } +} + +#[cfg(test)] +#[path = "types_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/config/types_tests.rs b/codex-rs/config/src/types_tests.rs similarity index 100% rename from codex-rs/core/src/config/types_tests.rs rename to codex-rs/config/src/types_tests.rs diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index d576a7550c..ad82b6c086 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -115,7 +115,6 @@ tracing = { workspace = true, features = ["log"] } url = { workspace = true } uuid = { workspace = true, features = ["serde", "v4", "v5"] } which = { workspace = true } -wildmatch = { workspace = true } zip = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 370c46ce4c..761491eb6a 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -1,5 +1,4 @@ use crate::config::types::McpServerConfig; -use crate::config::types::Notice; use crate::path_utils::resolve_symlink_write_paths; use crate::path_utils::write_atomically; use anyhow::Context; @@ -20,6 +19,8 @@ use toml_edit::Item as TomlItem; use toml_edit::Table as TomlTable; use toml_edit::value; +const NOTICE_TABLE_KEY: &str = "notice"; + /// Discrete config mutations supported by the persistence engine. #[derive(Clone, Debug)] pub enum ConfigEdit { @@ -387,29 +388,29 @@ impl ConfigDocument { )), ConfigEdit::SetNoticeHideFullAccessWarning(acknowledged) => Ok(self.write_value( Scope::Global, - &[Notice::TABLE_KEY, "hide_full_access_warning"], + &[NOTICE_TABLE_KEY, "hide_full_access_warning"], value(*acknowledged), )), ConfigEdit::SetNoticeHideWorldWritableWarning(acknowledged) => Ok(self.write_value( Scope::Global, - &[Notice::TABLE_KEY, "hide_world_writable_warning"], + &[NOTICE_TABLE_KEY, "hide_world_writable_warning"], value(*acknowledged), )), ConfigEdit::SetNoticeHideRateLimitModelNudge(acknowledged) => Ok(self.write_value( Scope::Global, - &[Notice::TABLE_KEY, "hide_rate_limit_model_nudge"], + &[NOTICE_TABLE_KEY, "hide_rate_limit_model_nudge"], value(*acknowledged), )), ConfigEdit::SetNoticeHideModelMigrationPrompt(migration_config, acknowledged) => { Ok(self.write_value( Scope::Global, - &[Notice::TABLE_KEY, migration_config.as_str()], + &[NOTICE_TABLE_KEY, migration_config.as_str()], value(*acknowledged), )) } ConfigEdit::RecordModelMigrationSeen { from, to } => Ok(self.write_value( Scope::Global, - &[Notice::TABLE_KEY, "model_migrations", from.as_str()], + &[NOTICE_TABLE_KEY, "model_migrations", from.as_str()], value(to.clone()), )), ConfigEdit::SetWindowsWslSetupAcknowledged(acknowledged) => Ok(self.write_value( diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs index b83be53e03..9debd7d79e 100644 --- a/codex-rs/core/src/config/types.rs +++ b/codex-rs/core/src/config/types.rs @@ -1,692 +1 @@ -//! Types used to define the fields of [`crate::config::Config`]. - -// Note this file should generally be restricted to simple struct/enum -// definitions that do not contain business logic. - -pub use codex_config::AppToolApproval; -pub use codex_config::McpServerConfig; -pub use codex_config::McpServerDisabledReason; -pub use codex_config::McpServerToolConfig; -pub use codex_config::McpServerTransportConfig; -pub use codex_config::RawMcpServerConfig; -pub use codex_protocol::config_types::AltScreenMode; -pub use codex_protocol::config_types::ApprovalsReviewer; -pub use codex_protocol::config_types::ModeKind; -pub use codex_protocol::config_types::Personality; -pub use codex_protocol::config_types::ServiceTier; -pub use codex_protocol::config_types::WebSearchMode; -use codex_utils_absolute_path::AbsolutePathBuf; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::fmt; -use wildmatch::WildMatchPattern; - -use schemars::JsonSchema; -use serde::Deserialize; -use serde::Serialize; - -pub const DEFAULT_OTEL_ENVIRONMENT: &str = "dev"; -pub const DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP: usize = 16; -pub const DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS: i64 = 30; -pub const DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS: i64 = 6; -pub const DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION: usize = 256; -pub const DEFAULT_MEMORIES_MAX_UNUSED_DAYS: i64 = 30; - -const fn default_enabled() -> bool { - true -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "kebab-case")] -pub enum WindowsSandboxModeToml { - Elevated, - Unelevated, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct WindowsToml { - pub sandbox: Option, - /// Defaults to `true`. Set to `false` to launch the final sandboxed child - /// process on `Winsta0\\Default` instead of a private desktop. - pub sandbox_private_desktop: Option, -} - -#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, JsonSchema)] -pub enum UriBasedFileOpener { - #[serde(rename = "vscode")] - VsCode, - - #[serde(rename = "vscode-insiders")] - VsCodeInsiders, - - #[serde(rename = "windsurf")] - Windsurf, - - #[serde(rename = "cursor")] - Cursor, - - /// Option to disable the URI-based file opener. - #[serde(rename = "none")] - None, -} - -impl UriBasedFileOpener { - pub fn get_scheme(&self) -> Option<&str> { - match self { - UriBasedFileOpener::VsCode => Some("vscode"), - UriBasedFileOpener::VsCodeInsiders => Some("vscode-insiders"), - UriBasedFileOpener::Windsurf => Some("windsurf"), - UriBasedFileOpener::Cursor => Some("cursor"), - UriBasedFileOpener::None => None, - } - } -} - -/// Settings that govern if and what will be written to `~/.codex/history.jsonl`. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct History { - /// If true, history entries will not be written to disk. - pub persistence: HistoryPersistence, - - /// If set, the maximum size of the history file in bytes. The oldest entries - /// are dropped once the file exceeds this limit. - pub max_bytes: Option, -} - -#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Default, JsonSchema)] -#[serde(rename_all = "kebab-case")] -pub enum HistoryPersistence { - /// Save all history entries to disk. - #[default] - SaveAll, - /// Do not write history to disk. - None, -} - -// ===== Analytics configuration ===== - -/// Analytics settings loaded from config.toml. Fields are optional so we can apply defaults. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AnalyticsConfigToml { - /// When `false`, disables analytics across Codex product surfaces in this profile. - pub enabled: Option, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct FeedbackConfigToml { - /// When `false`, disables the feedback flow across Codex product surfaces. - pub enabled: Option, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum ToolSuggestDiscoverableType { - Connector, - Plugin, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct ToolSuggestDiscoverable { - #[serde(rename = "type")] - pub kind: ToolSuggestDiscoverableType, - pub id: String, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct ToolSuggestConfig { - #[serde(default)] - pub discoverables: Vec, -} - -/// Memories settings loaded from config.toml. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct MemoriesToml { - /// When `true`, web searches and MCP tool calls mark the thread `memory_mode` as `"polluted"`. - pub no_memories_if_mcp_or_web_search: Option, - /// When `false`, newly created threads are stored with `memory_mode = "disabled"` in the state DB. - pub generate_memories: Option, - /// When `false`, skip injecting memory usage instructions into developer prompts. - pub use_memories: Option, - /// Maximum number of recent raw memories retained for global consolidation. - pub max_raw_memories_for_consolidation: Option, - /// Maximum number of days since a memory was last used before it becomes ineligible for phase 2 selection. - pub max_unused_days: Option, - /// Maximum age of the threads used for memories. - pub max_rollout_age_days: Option, - /// Maximum number of rollout candidates processed per pass. - pub max_rollouts_per_startup: Option, - /// Minimum idle time between last thread activity and memory creation (hours). > 12h recommended. - pub min_rollout_idle_hours: Option, - /// Model used for thread summarisation. - pub extract_model: Option, - /// Model used for memory consolidation. - pub consolidation_model: Option, -} - -/// Effective memories settings after defaults are applied. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MemoriesConfig { - pub no_memories_if_mcp_or_web_search: bool, - pub generate_memories: bool, - pub use_memories: bool, - pub max_raw_memories_for_consolidation: usize, - pub max_unused_days: i64, - pub max_rollout_age_days: i64, - pub max_rollouts_per_startup: usize, - pub min_rollout_idle_hours: i64, - pub extract_model: Option, - pub consolidation_model: Option, -} - -impl Default for MemoriesConfig { - fn default() -> Self { - Self { - no_memories_if_mcp_or_web_search: false, - generate_memories: true, - use_memories: true, - max_raw_memories_for_consolidation: DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION, - max_unused_days: DEFAULT_MEMORIES_MAX_UNUSED_DAYS, - max_rollout_age_days: DEFAULT_MEMORIES_MAX_ROLLOUT_AGE_DAYS, - max_rollouts_per_startup: DEFAULT_MEMORIES_MAX_ROLLOUTS_PER_STARTUP, - min_rollout_idle_hours: DEFAULT_MEMORIES_MIN_ROLLOUT_IDLE_HOURS, - extract_model: None, - consolidation_model: None, - } - } -} - -impl From for MemoriesConfig { - fn from(toml: MemoriesToml) -> Self { - let defaults = Self::default(); - Self { - no_memories_if_mcp_or_web_search: toml - .no_memories_if_mcp_or_web_search - .unwrap_or(defaults.no_memories_if_mcp_or_web_search), - generate_memories: toml.generate_memories.unwrap_or(defaults.generate_memories), - use_memories: toml.use_memories.unwrap_or(defaults.use_memories), - max_raw_memories_for_consolidation: toml - .max_raw_memories_for_consolidation - .unwrap_or(defaults.max_raw_memories_for_consolidation) - .min(4096), - max_unused_days: toml - .max_unused_days - .unwrap_or(defaults.max_unused_days) - .clamp(0, 365), - max_rollout_age_days: toml - .max_rollout_age_days - .unwrap_or(defaults.max_rollout_age_days) - .clamp(0, 90), - max_rollouts_per_startup: toml - .max_rollouts_per_startup - .unwrap_or(defaults.max_rollouts_per_startup) - .min(128), - min_rollout_idle_hours: toml - .min_rollout_idle_hours - .unwrap_or(defaults.min_rollout_idle_hours) - .clamp(1, 48), - extract_model: toml.extract_model, - consolidation_model: toml.consolidation_model, - } - } -} - -/// Default settings that apply to all apps. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AppsDefaultConfig { - /// When `false`, apps are disabled unless overridden by per-app settings. - #[serde(default = "default_enabled")] - pub enabled: bool, - - /// Whether tools with `destructive_hint = true` are allowed by default. - #[serde( - default = "default_enabled", - skip_serializing_if = "std::clone::Clone::clone" - )] - pub destructive_enabled: bool, - - /// Whether tools with `open_world_hint = true` are allowed by default. - #[serde( - default = "default_enabled", - skip_serializing_if = "std::clone::Clone::clone" - )] - pub open_world_enabled: bool, -} - -/// Per-tool settings for a single app tool. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AppToolConfig { - /// Whether this tool is enabled. `Some(true)` explicitly allows this tool. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub enabled: Option, - - /// Approval mode for this tool. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub approval_mode: Option, -} - -/// Tool settings for a single app. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AppToolsConfig { - /// Per-tool overrides keyed by tool name (for example `repos/list`). - #[serde(default, flatten)] - pub tools: HashMap, -} - -/// Config values for a single app/connector. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AppConfig { - /// When `false`, Codex does not surface this app. - #[serde(default = "default_enabled")] - pub enabled: bool, - - /// Whether tools with `destructive_hint = true` are allowed for this app. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub destructive_enabled: Option, - - /// Whether tools with `open_world_hint = true` are allowed for this app. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub open_world_enabled: Option, - - /// Approval mode for tools in this app unless a tool override exists. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_tools_approval_mode: Option, - - /// Whether tools are enabled by default for this app. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub default_tools_enabled: Option, - - /// Per-tool settings for this app. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tools: Option, -} - -/// App/connector settings loaded from `config.toml`. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct AppsConfigToml { - /// Default settings for all apps. - #[serde(default, rename = "_default", skip_serializing_if = "Option::is_none")] - pub default: Option, - - /// Per-app settings keyed by app ID (for example `[apps.google_drive]`). - #[serde(default, flatten)] - pub apps: HashMap, -} - -// ===== OTEL configuration ===== - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] -#[serde(rename_all = "kebab-case")] -pub enum OtelHttpProtocol { - /// Binary payload - Binary, - /// JSON payload - Json, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -#[serde(rename_all = "kebab-case")] -pub struct OtelTlsConfig { - pub ca_certificate: Option, - pub client_certificate: Option, - pub client_private_key: Option, -} - -/// Which OTEL exporter to use. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)] -#[schemars(deny_unknown_fields)] -#[serde(rename_all = "kebab-case")] -pub enum OtelExporterKind { - None, - Statsig, - OtlpHttp { - endpoint: String, - #[serde(default)] - headers: HashMap, - protocol: OtelHttpProtocol, - #[serde(default)] - tls: Option, - }, - OtlpGrpc { - endpoint: String, - #[serde(default)] - headers: HashMap, - #[serde(default)] - tls: Option, - }, -} - -/// OTEL settings loaded from config.toml. Fields are optional so we can apply defaults. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct OtelConfigToml { - /// Log user prompt in traces - pub log_user_prompt: Option, - - /// Mark traces with environment (dev, staging, prod, test). Defaults to dev. - pub environment: Option, - - /// Optional log exporter - pub exporter: Option, - - /// Optional trace exporter - pub trace_exporter: Option, - - /// Optional metrics exporter - pub metrics_exporter: Option, -} - -/// Effective OTEL settings after defaults are applied. -#[derive(Debug, Clone, PartialEq)] -pub struct OtelConfig { - pub log_user_prompt: bool, - pub environment: String, - pub exporter: OtelExporterKind, - pub trace_exporter: OtelExporterKind, - pub metrics_exporter: OtelExporterKind, -} - -impl Default for OtelConfig { - fn default() -> Self { - OtelConfig { - log_user_prompt: false, - environment: DEFAULT_OTEL_ENVIRONMENT.to_owned(), - exporter: OtelExporterKind::None, - trace_exporter: OtelExporterKind::None, - metrics_exporter: OtelExporterKind::Statsig, - } - } -} - -#[derive(Serialize, Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)] -#[serde(untagged)] -pub enum Notifications { - Enabled(bool), - Custom(Vec), -} - -impl Default for Notifications { - fn default() -> Self { - Self::Enabled(true) - } -} - -#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "lowercase")] -pub enum NotificationMethod { - #[default] - Auto, - Osc9, - Bel, -} - -impl fmt::Display for NotificationMethod { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - NotificationMethod::Auto => write!(f, "auto"), - NotificationMethod::Osc9 => write!(f, "osc9"), - NotificationMethod::Bel => write!(f, "bel"), - } - } -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct ModelAvailabilityNuxConfig { - /// Number of times a startup availability NUX has been shown per model slug. - #[serde(default, flatten)] - pub shown_count: HashMap, -} - -/// Collection of settings that are specific to the TUI. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct Tui { - /// Enable desktop notifications from the TUI when the terminal is unfocused. - /// Defaults to `true`. - #[serde(default)] - pub notifications: Notifications, - - /// Notification method to use for unfocused terminal notifications. - /// Defaults to `auto`. - #[serde(default)] - pub notification_method: NotificationMethod, - - /// Enable animations (welcome screen, shimmer effects, spinners). - /// Defaults to `true`. - #[serde(default = "default_true")] - pub animations: bool, - - /// Show startup tooltips in the TUI welcome screen. - /// Defaults to `true`. - #[serde(default = "default_true")] - pub show_tooltips: bool, - - /// Controls whether the TUI uses the terminal's alternate screen buffer. - /// - /// - `auto` (default): Disable alternate screen in Zellij, enable elsewhere. - /// - `always`: Always use alternate screen (original behavior). - /// - `never`: Never use alternate screen (inline mode only, preserves scrollback). - /// - /// Using alternate screen provides a cleaner fullscreen experience but prevents - /// scrollback in terminal multiplexers like Zellij that follow the xterm spec. - #[serde(default)] - pub alternate_screen: AltScreenMode, - - /// Ordered list of status line item identifiers. - /// - /// When set, the TUI renders the selected items as the status line. - /// When unset, the TUI defaults to: `model-with-reasoning`, `context-remaining`, and - /// `current-dir`. - #[serde(default)] - pub status_line: Option>, - - /// Ordered list of terminal title item identifiers. - /// - /// When set, the TUI renders the selected items into the terminal window/tab title. - /// When unset, the TUI defaults to: `spinner` and `project`. - #[serde(default)] - pub terminal_title: Option>, - - /// Syntax highlighting theme name (kebab-case). - /// - /// When set, overrides automatic light/dark theme detection. - /// Use `/theme` in the TUI or see `$CODEX_HOME/themes` for custom themes. - #[serde(default)] - pub theme: Option, - - /// Startup tooltip availability NUX state persisted by the TUI. - #[serde(default)] - pub model_availability_nux: ModelAvailabilityNuxConfig, -} - -const fn default_true() -> bool { - true -} - -/// Settings for notices we display to users via the tui and app-server clients -/// (primarily the Codex IDE extension). NOTE: these are different from -/// notifications - notices are warnings, NUX screens, acknowledgements, etc. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -pub struct Notice { - /// Tracks whether the user has acknowledged the full access warning prompt. - pub hide_full_access_warning: Option, - /// Tracks whether the user has acknowledged the Windows world-writable directories warning. - pub hide_world_writable_warning: Option, - /// Tracks whether the user opted out of the rate limit model switch reminder. - pub hide_rate_limit_model_nudge: Option, - /// Tracks whether the user has seen the model migration prompt - pub hide_gpt5_1_migration_prompt: Option, - /// Tracks whether the user has seen the gpt-5.1-codex-max migration prompt - #[serde(rename = "hide_gpt-5.1-codex-max_migration_prompt")] - pub hide_gpt_5_1_codex_max_migration_prompt: Option, - /// Tracks acknowledged model migrations as old->new model slug mappings. - #[serde(default)] - pub model_migrations: BTreeMap, -} - -impl Notice { - /// referenced by config_edit helpers when writing notice flags - pub(crate) const TABLE_KEY: &'static str = "notice"; -} - -pub use codex_config::BundledSkillsConfig; -pub use codex_config::SkillConfig; -pub use codex_config::SkillsConfig; - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct PluginConfig { - #[serde(default = "default_enabled")] - pub enabled: bool, -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct SandboxWorkspaceWrite { - #[serde(default)] - pub writable_roots: Vec, - #[serde(default)] - pub network_access: bool, - #[serde(default)] - pub exclude_tmpdir_env_var: bool, - #[serde(default)] - pub exclude_slash_tmp: bool, -} - -impl From for codex_app_server_protocol::SandboxSettings { - fn from(sandbox_workspace_write: SandboxWorkspaceWrite) -> Self { - Self { - writable_roots: sandbox_workspace_write.writable_roots, - network_access: Some(sandbox_workspace_write.network_access), - exclude_tmpdir_env_var: Some(sandbox_workspace_write.exclude_tmpdir_env_var), - exclude_slash_tmp: Some(sandbox_workspace_write.exclude_slash_tmp), - } - } -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[serde(rename_all = "kebab-case")] -pub enum ShellEnvironmentPolicyInherit { - /// "Core" environment variables for the platform. On UNIX, this would - /// include HOME, LOGNAME, PATH, SHELL, and USER, among others. - Core, - - /// Inherits the full environment from the parent process. - #[default] - All, - - /// Do not inherit any environment variables from the parent process. - None, -} - -/// Policy for building the `env` when spawning a process via either the -/// `shell` or `local_shell` tool. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] -#[schemars(deny_unknown_fields)] -pub struct ShellEnvironmentPolicyToml { - pub inherit: Option, - - pub ignore_default_excludes: Option, - - /// List of regular expressions. - pub exclude: Option>, - - pub r#set: Option>, - - /// List of regular expressions. - pub include_only: Option>, - - pub experimental_use_profile: Option, -} - -pub type EnvironmentVariablePattern = WildMatchPattern<'*', '?'>; - -/// Deriving the `env` based on this policy works as follows: -/// 1. Create an initial map based on the `inherit` policy. -/// 2. If `ignore_default_excludes` is false, filter the map using the default -/// exclude pattern(s), which are: `"*KEY*"`, `"*SECRET*"`, and `"*TOKEN*"`. -/// 3. If `exclude` is not empty, filter the map using the provided patterns. -/// 4. Insert any entries from `r#set` into the map. -/// 5. If non-empty, filter the map using the `include_only` patterns. -#[derive(Debug, Clone, PartialEq)] -pub struct ShellEnvironmentPolicy { - /// Starting point when building the environment. - pub inherit: ShellEnvironmentPolicyInherit, - - /// True to skip the check to exclude default environment variables that - /// contain "KEY", "SECRET", or "TOKEN" in their name. Defaults to true. - pub ignore_default_excludes: bool, - - /// Environment variable names to exclude from the environment. - pub exclude: Vec, - - /// (key, value) pairs to insert in the environment. - pub r#set: HashMap, - - /// Environment variable names to retain in the environment. - pub include_only: Vec, - - /// If true, the shell profile will be used to run the command. - pub use_profile: bool, -} - -impl From for ShellEnvironmentPolicy { - fn from(toml: ShellEnvironmentPolicyToml) -> Self { - // Default to inheriting the full environment when not specified. - let inherit = toml.inherit.unwrap_or(ShellEnvironmentPolicyInherit::All); - let ignore_default_excludes = toml.ignore_default_excludes.unwrap_or(true); - let exclude = toml - .exclude - .unwrap_or_default() - .into_iter() - .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) - .collect(); - let r#set = toml.r#set.unwrap_or_default(); - let include_only = toml - .include_only - .unwrap_or_default() - .into_iter() - .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) - .collect(); - let use_profile = toml.experimental_use_profile.unwrap_or(false); - - Self { - inherit, - ignore_default_excludes, - exclude, - r#set, - include_only, - use_profile, - } - } -} - -impl Default for ShellEnvironmentPolicy { - fn default() -> Self { - Self { - inherit: ShellEnvironmentPolicyInherit::All, - ignore_default_excludes: true, - exclude: Vec::new(), - r#set: HashMap::new(), - include_only: Vec::new(), - use_profile: false, - } - } -} - -#[cfg(test)] -#[path = "types_tests.rs"] -mod tests; +pub use codex_config::types::*; From e846fed2b1755cab6c1d5a656a49db76b2778e91 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Apr 2026 00:49:37 -0700 Subject: [PATCH 4/5] fix: move some test utilities out of codex-rs/core/src/tools/spec.rs (#16524) The `#[cfg(test)]` in `codex-rs/core/src/tools/spec.rs` smelled funny to me and it turns out these members were straightforward to move. --- codex-rs/core/src/tools/spec.rs | 20 -------------------- codex-rs/core/src/tools/spec_tests.rs | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 86f4840a43..341db24767 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -19,9 +19,6 @@ use codex_tools::build_tool_registry_plan; use std::collections::HashMap; use std::sync::Arc; -#[cfg(test)] -pub(crate) use codex_tools::mcp_call_tool_result_output_schema; - pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType { match user_shell.shell_type { ShellType::Zsh => ToolUserShellType::Zsh, @@ -32,23 +29,6 @@ pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType { } } -/// Builds the tool registry builder while collecting tool specs for later serialization. -#[cfg(test)] -pub(crate) fn build_specs( - config: &ToolsConfig, - mcp_tools: Option>, - app_tools: Option>, - dynamic_tools: &[DynamicToolSpec], -) -> ToolRegistryBuilder { - build_specs_with_discoverable_tools( - config, - mcp_tools, - app_tools, - /*discoverable_tools*/ None, - dynamic_tools, - ) -} - pub(crate) fn build_specs_with_discoverable_tools( config: &ToolsConfig, mcp_tools: Option>, diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index 61cb494679..4e73be3502 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -29,6 +29,7 @@ use codex_tools::ToolsConfig; use codex_tools::ToolsConfigParams; use codex_tools::UnifiedExecShellMode; use codex_tools::ZshForkConfig; +use codex_tools::mcp_call_tool_result_output_schema; use codex_tools::mcp_tool_to_deferred_responses_api_tool; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -170,6 +171,22 @@ fn model_info_from_models_json(slug: &str) -> ModelInfo { with_config_overrides(model, &config) } +/// Builds the tool registry builder while collecting tool specs for later serialization. +fn build_specs( + config: &ToolsConfig, + mcp_tools: Option>, + app_tools: Option>, + dynamic_tools: &[DynamicToolSpec], +) -> ToolRegistryBuilder { + build_specs_with_discoverable_tools( + config, + mcp_tools, + app_tools, + /*discoverable_tools*/ None, + dynamic_tools, + ) +} + #[test] fn model_provided_unified_exec_is_blocked_for_windows_sandboxed_policies() { let mut model_info = model_info_from_models_json("gpt-5-codex"); From c1d18ceb6f22ae3acd67bbd6badad0f475b31dfc Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 2 Apr 2026 01:19:44 -0700 Subject: [PATCH 5/5] [codex] Remove codex-core config type shim (#16529) ## Why This finishes the config-type move out of `codex-core` by removing the temporary compatibility shim in `codex_core::config::types`. Callers now depend on `codex-config` directly, which keeps these config model types owned by the config crate instead of re-expanding `codex-core` as a transitive API surface. ## What Changed - Removed the `codex-rs/core/src/config/types.rs` re-export shim and the `core::config::ApprovalsReviewer` re-export. - Updated `codex-core`, `codex-cli`, `codex-tui`, `codex-app-server`, `codex-mcp-server`, and `codex-linux-sandbox` call sites to import `codex_config::types` directly. - Added explicit `codex-config` dependencies to downstream crates that previously relied on the `codex-core` re-export. - Regenerated `codex-rs/core/config.schema.json` after updating the config docs path reference. --- codex-rs/Cargo.lock | 4 ++ codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/codex_message_processor.rs | 2 +- .../plugin_mcp_oauth.rs | 2 +- .../app-server/tests/suite/v2/analytics.rs | 4 +- codex-rs/cli/src/mcp_cmd.rs | 4 +- codex-rs/cli/tests/mcp_add_remove.rs | 2 +- codex-rs/cli/tests/mcp_list.rs | 2 +- codex-rs/core/config.schema.json | 4 +- codex-rs/core/src/client_common.rs | 2 +- codex-rs/core/src/codex.rs | 4 +- codex-rs/core/src/codex_tests.rs | 6 +- codex-rs/core/src/config/config_tests.rs | 26 ++++---- codex-rs/core/src/config/edit.rs | 10 +-- codex-rs/core/src/config/edit_tests.rs | 6 +- codex-rs/core/src/config/mod.rs | 65 +++++++++---------- codex-rs/core/src/config/profile.rs | 8 +-- codex-rs/core/src/config/schema.rs | 2 +- codex-rs/core/src/config/types.rs | 1 - codex-rs/core/src/connectors.rs | 6 +- codex-rs/core/src/connectors_tests.rs | 8 +-- codex-rs/core/src/exec_env.rs | 6 +- codex-rs/core/src/exec_env_tests.rs | 2 +- codex-rs/core/src/guardian/review_session.rs | 2 +- codex-rs/core/src/mcp_tool_call.rs | 7 +- codex-rs/core/src/mcp_tool_call_tests.rs | 14 ++-- codex-rs/core/src/memories/phase1.rs | 2 +- codex-rs/core/src/memories/tests.rs | 2 +- codex-rs/core/src/message_history.rs | 2 +- codex-rs/core/src/otel_init.rs | 4 +- codex-rs/core/src/plugins/discoverable.rs | 2 +- codex-rs/core/src/plugins/manager.rs | 4 +- codex-rs/core/src/plugins/manager_tests.rs | 2 +- codex-rs/core/src/plugins/mod.rs | 2 +- .../src/tools/handlers/multi_agents_tests.rs | 2 +- codex-rs/core/src/windows_sandbox.rs | 2 +- codex-rs/core/src/windows_sandbox_tests.rs | 2 +- codex-rs/core/tests/suite/code_mode.rs | 4 +- codex-rs/core/tests/suite/model_switching.rs | 2 +- .../core/tests/suite/model_visible_layout.rs | 2 +- codex-rs/core/tests/suite/personality.rs | 2 +- codex-rs/core/tests/suite/rmcp_client.rs | 4 +- codex-rs/core/tests/suite/sqlite_state.rs | 4 +- codex-rs/core/tests/suite/tool_suggest.rs | 4 +- codex-rs/core/tests/suite/truncation.rs | 12 ++-- codex-rs/linux-sandbox/Cargo.toml | 1 + .../linux-sandbox/tests/suite/landlock.rs | 2 +- .../tests/suite/managed_proxy.rs | 2 +- codex-rs/mcp-server/Cargo.toml | 1 + codex-rs/mcp-server/src/lib.rs | 2 +- codex-rs/tui/Cargo.toml | 1 + codex-rs/tui/src/app.rs | 6 +- codex-rs/tui/src/app_command.rs | 2 +- codex-rs/tui/src/app_event.rs | 2 +- codex-rs/tui/src/chatwidget.rs | 6 +- codex-rs/tui/src/chatwidget/tests.rs | 8 +-- codex-rs/tui/src/history_cell.rs | 6 +- codex-rs/tui/src/notifications/mod.rs | 4 +- codex-rs/tui/src/tui.rs | 2 +- 59 files changed, 155 insertions(+), 150 deletions(-) delete mode 100644 codex-rs/core/src/config/types.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d5bab66c66..c59b8d9c4d 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1407,6 +1407,7 @@ dependencies = [ "codex-backend-client", "codex-chatgpt", "codex-cloud-requirements", + "codex-config", "codex-core", "codex-exec-server", "codex-features", @@ -2201,6 +2202,7 @@ version = "0.0.0" dependencies = [ "cc", "clap", + "codex-config", "codex-core", "codex-protocol", "codex-sandboxing", @@ -2304,6 +2306,7 @@ version = "0.0.0" dependencies = [ "anyhow", "codex-arg0", + "codex-config", "codex-core", "codex-exec-server", "codex-features", @@ -2694,6 +2697,7 @@ dependencies = [ "codex-chatgpt", "codex-cli", "codex-cloud-requirements", + "codex-config", "codex-core", "codex-features", "codex-feedback", diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 3d58bbe146..b0525685cd 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -32,6 +32,7 @@ axum = { workspace = true, default-features = false, features = [ codex-analytics = { workspace = true } codex-arg0 = { workspace = true } codex-cloud-requirements = { workspace = true } +codex-config = { workspace = true } codex-core = { workspace = true } codex-exec-server = { workspace = true } codex-features = { workspace = true } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index f833e5234f..2b9aa12ab4 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -181,6 +181,7 @@ use codex_arg0::Arg0DispatchPaths; use codex_backend_client::Client as BackendClient; use codex_chatgpt::connectors; use codex_cloud_requirements::cloud_requirements_loader; +use codex_config::types::McpServerTransportConfig; use codex_core::CodexThread; use codex_core::Cursor as RolloutCursor; use codex_core::ForkSnapshot; @@ -196,7 +197,6 @@ use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; -use codex_core::config::types::McpServerTransportConfig; use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoadErrorCode; use codex_core::config_loader::CloudRequirementsLoader; diff --git a/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs b/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs index eec359835f..58f4a5e8dd 100644 --- a/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs +++ b/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; use codex_app_server_protocol::ServerNotification; +use codex_config::types::McpServerConfig; use codex_core::config::Config; -use codex_core::config::types::McpServerConfig; use codex_mcp::mcp::auth::McpOAuthLoginSupport; use codex_mcp::mcp::auth::oauth_login_support; use codex_mcp::mcp::auth::resolve_oauth_scopes; diff --git a/codex-rs/app-server/tests/suite/v2/analytics.rs b/codex-rs/app-server/tests/suite/v2/analytics.rs index d4884d1337..8e8e328a84 100644 --- a/codex-rs/app-server/tests/suite/v2/analytics.rs +++ b/codex-rs/app-server/tests/suite/v2/analytics.rs @@ -2,9 +2,9 @@ use anyhow::Result; use app_test_support::ChatGptAuthFixture; use app_test_support::DEFAULT_CLIENT_NAME; use app_test_support::write_chatgpt_auth; +use codex_config::types::OtelExporterKind; +use codex_config::types::OtelHttpProtocol; use codex_core::config::ConfigBuilder; -use codex_core::config::types::OtelExporterKind; -use codex_core::config::types::OtelHttpProtocol; use codex_login::AuthCredentialsStoreMode; use pretty_assertions::assert_eq; use serde_json::Value; diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index ca89984337..144316b50e 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -6,12 +6,12 @@ use anyhow::Result; use anyhow::anyhow; use anyhow::bail; use clap::ArgGroup; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerTransportConfig; use codex_core::config::Config; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::find_codex_home; use codex_core::config::load_global_mcp_servers; -use codex_core::config::types::McpServerConfig; -use codex_core::config::types::McpServerTransportConfig; use codex_core::mcp::McpManager; use codex_core::plugins::PluginsManager; use codex_mcp::mcp::auth::McpOAuthLoginSupport; diff --git a/codex-rs/cli/tests/mcp_add_remove.rs b/codex-rs/cli/tests/mcp_add_remove.rs index bc3fedc2a7..15afaf0828 100644 --- a/codex-rs/cli/tests/mcp_add_remove.rs +++ b/codex-rs/cli/tests/mcp_add_remove.rs @@ -1,8 +1,8 @@ use std::path::Path; use anyhow::Result; +use codex_config::types::McpServerTransportConfig; use codex_core::config::load_global_mcp_servers; -use codex_core::config::types::McpServerTransportConfig; use predicates::str::contains; use pretty_assertions::assert_eq; use tempfile::TempDir; diff --git a/codex-rs/cli/tests/mcp_list.rs b/codex-rs/cli/tests/mcp_list.rs index cb78644b1b..d41a3cc62a 100644 --- a/codex-rs/cli/tests/mcp_list.rs +++ b/codex-rs/cli/tests/mcp_list.rs @@ -1,9 +1,9 @@ use std::path::Path; use anyhow::Result; +use codex_config::types::McpServerTransportConfig; use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config::load_global_mcp_servers; -use codex_core::config::types::McpServerTransportConfig; use predicates::prelude::PredicateBooleanExt; use predicates::str::contains; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 99a38edf47..a8f3229b54 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2396,7 +2396,7 @@ "$ref": "#/definitions/Notice" } ], - "description": "Collection of in-product notices (different from notifications) See [`crate::config::types::Notices`] for more details" + "description": "Collection of in-product notices (different from notifications) See [`codex_config::types::Notice`] for more details" }, "notify": { "default": null, @@ -2627,4 +2627,4 @@ }, "title": "ConfigToml", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index ccc2f62975..8a6c42bb96 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -1,6 +1,6 @@ -use crate::config::types::Personality; use crate::error::Result; pub use codex_api::common::ResponseEvent; +use codex_config::types::Personality; use codex_protocol::models::BaseInstructions; use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::ResponseItem; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 47c6cf8600..92d75390d4 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -181,8 +181,6 @@ use crate::config::ConstraintResult; use crate::config::GhostSnapshotConfig; use crate::config::StartedNetworkProxy; use crate::config::resolve_web_search_mode_for_turn; -use crate::config::types::McpServerConfig; -use crate::config::types::ShellEnvironmentPolicy; use crate::context_manager::ContextManager; use crate::context_manager::TotalTokenUsageBreakdown; use crate::environment_context::EnvironmentContext; @@ -191,6 +189,8 @@ use crate::error::Result as CodexResult; #[cfg(test)] use crate::exec::StreamOutput; use codex_config::CONFIG_TOML_FILE; +use codex_config::types::McpServerConfig; +use codex_config::types::ShellEnvironmentPolicy; mod rollout_reconstruction; #[cfg(test)] diff --git a/codex-rs/core/src/codex_tests.rs b/codex-rs/core/src/codex_tests.rs index 24c24eb935..8f1bba647c 100644 --- a/codex-rs/core/src/codex_tests.rs +++ b/codex-rs/core/src/codex_tests.rs @@ -604,7 +604,7 @@ async fn reload_user_config_layer_updates_effective_apps_config() { .and_then(|table| table.get("apps")) .cloned() .expect("apps table"); - let apps = crate::config::types::AppsConfigToml::deserialize(apps_toml) + let apps = codex_config::types::AppsConfigToml::deserialize(apps_toml) .expect("deserialize apps config"); let app = apps .apps @@ -3091,7 +3091,7 @@ async fn user_turn_updates_approvals_reviewer() { }], cwd: config.cwd.to_path_buf(), approval_policy: config.permissions.approval_policy.value(), - approvals_reviewer: Some(crate::config::types::ApprovalsReviewer::GuardianSubagent), + approvals_reviewer: Some(codex_config::types::ApprovalsReviewer::GuardianSubagent), sandbox_policy: config.permissions.sandbox_policy.get().clone(), model: turn_context.model_info.slug.clone(), effort: config.model_reasoning_effort, @@ -3107,7 +3107,7 @@ async fn user_turn_updates_approvals_reviewer() { let state = session.state.lock().await; assert_eq!( state.session_configuration.approvals_reviewer, - crate::config::types::ApprovalsReviewer::GuardianSubagent + codex_config::types::ApprovalsReviewer::GuardianSubagent ); } diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 80e369f696..02f9582561 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1,23 +1,23 @@ use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; use crate::config::edit::apply_blocking; -use crate::config::types::AppToolApproval; -use crate::config::types::ApprovalsReviewer; -use crate::config::types::BundledSkillsConfig; -use crate::config::types::FeedbackConfigToml; -use crate::config::types::HistoryPersistence; -use crate::config::types::McpServerToolConfig; -use crate::config::types::McpServerTransportConfig; -use crate::config::types::MemoriesConfig; -use crate::config::types::MemoriesToml; -use crate::config::types::ModelAvailabilityNuxConfig; -use crate::config::types::NotificationMethod; -use crate::config::types::Notifications; -use crate::config::types::ToolSuggestDiscoverableType; use crate::config_loader::RequirementSource; use crate::plugins::PluginsManager; use assert_matches::assert_matches; use codex_config::CONFIG_TOML_FILE; +use codex_config::types::AppToolApproval; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::BundledSkillsConfig; +use codex_config::types::FeedbackConfigToml; +use codex_config::types::HistoryPersistence; +use codex_config::types::McpServerToolConfig; +use codex_config::types::McpServerTransportConfig; +use codex_config::types::MemoriesConfig; +use codex_config::types::MemoriesToml; +use codex_config::types::ModelAvailabilityNuxConfig; +use codex_config::types::NotificationMethod; +use codex_config::types::Notifications; +use codex_config::types::ToolSuggestDiscoverableType; use codex_features::Feature; use codex_features::FeaturesToml; use codex_protocol::permissions::FileSystemAccessMode; diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 761491eb6a..1b3d700ab7 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -1,8 +1,8 @@ -use crate::config::types::McpServerConfig; use crate::path_utils::resolve_symlink_write_paths; use crate::path_utils::write_atomically; use anyhow::Context; use codex_config::CONFIG_TOML_FILE; +use codex_config::types::McpServerConfig; use codex_features::FEATURES; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ServiceTier; @@ -126,10 +126,10 @@ pub fn model_availability_nux_count_edits(shown_count: &HashMap) -> // TODO(jif) move to a dedicated file mod document_helpers { - use crate::config::types::AppToolApproval; - use crate::config::types::McpServerConfig; - use crate::config::types::McpServerToolConfig; - use crate::config::types::McpServerTransportConfig; + use codex_config::types::AppToolApproval; + use codex_config::types::McpServerConfig; + use codex_config::types::McpServerToolConfig; + use codex_config::types::McpServerTransportConfig; use toml_edit::Array as TomlArray; use toml_edit::InlineTable; use toml_edit::Item as TomlItem; diff --git a/codex-rs/core/src/config/edit_tests.rs b/codex-rs/core/src/config/edit_tests.rs index e27add0054..314d8badb3 100644 --- a/codex-rs/core/src/config/edit_tests.rs +++ b/codex-rs/core/src/config/edit_tests.rs @@ -1,7 +1,7 @@ use super::*; -use crate::config::types::AppToolApproval; -use crate::config::types::McpServerToolConfig; -use crate::config::types::McpServerTransportConfig; +use codex_config::types::AppToolApproval; +use codex_config::types::McpServerToolConfig; +use codex_config::types::McpServerTransportConfig; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; #[cfg(unix)] diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 67b6afc857..f22258dfb9 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -1,31 +1,5 @@ use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; -use crate::config::types::AppsConfigToml; -use crate::config::types::DEFAULT_OTEL_ENVIRONMENT; -use crate::config::types::History; -use crate::config::types::McpServerConfig; -use crate::config::types::McpServerDisabledReason; -use crate::config::types::McpServerTransportConfig; -use crate::config::types::MemoriesConfig; -use crate::config::types::MemoriesToml; -use crate::config::types::ModelAvailabilityNuxConfig; -use crate::config::types::Notice; -use crate::config::types::NotificationMethod; -use crate::config::types::Notifications; -use crate::config::types::OtelConfig; -use crate::config::types::OtelConfigToml; -use crate::config::types::OtelExporterKind; -use crate::config::types::PluginConfig; -use crate::config::types::SandboxWorkspaceWrite; -use crate::config::types::ShellEnvironmentPolicy; -use crate::config::types::ShellEnvironmentPolicyToml; -use crate::config::types::SkillsConfig; -use crate::config::types::ToolSuggestConfig; -use crate::config::types::ToolSuggestDiscoverable; -use crate::config::types::Tui; -use crate::config::types::UriBasedFileOpener; -use crate::config::types::WindowsSandboxModeToml; -use crate::config::types::WindowsToml; use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigLayerStackOrdering; @@ -56,6 +30,33 @@ use crate::windows_sandbox::resolve_windows_sandbox_mode; use crate::windows_sandbox::resolve_windows_sandbox_private_desktop; use codex_app_server_protocol::Tools; use codex_app_server_protocol::UserSavedConfig; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::AppsConfigToml; +use codex_config::types::DEFAULT_OTEL_ENVIRONMENT; +use codex_config::types::History; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerDisabledReason; +use codex_config::types::McpServerTransportConfig; +use codex_config::types::MemoriesConfig; +use codex_config::types::MemoriesToml; +use codex_config::types::ModelAvailabilityNuxConfig; +use codex_config::types::Notice; +use codex_config::types::NotificationMethod; +use codex_config::types::Notifications; +use codex_config::types::OtelConfig; +use codex_config::types::OtelConfigToml; +use codex_config::types::OtelExporterKind; +use codex_config::types::PluginConfig; +use codex_config::types::SandboxWorkspaceWrite; +use codex_config::types::ShellEnvironmentPolicy; +use codex_config::types::ShellEnvironmentPolicyToml; +use codex_config::types::SkillsConfig; +use codex_config::types::ToolSuggestConfig; +use codex_config::types::ToolSuggestDiscoverable; +use codex_config::types::Tui; +use codex_config::types::UriBasedFileOpener; +use codex_config::types::WindowsSandboxModeToml; +use codex_config::types::WindowsToml; use codex_features::Feature; use codex_features::FeatureConfigSource; use codex_features::FeatureOverrides; @@ -113,7 +114,6 @@ mod permissions; pub mod profile; pub mod schema; pub mod service; -pub mod types; pub use codex_config::Constrained; pub use codex_config::ConstraintError; pub use codex_config::ConstraintResult; @@ -135,7 +135,6 @@ pub(crate) use permissions::overlay_network_domain_permissions; pub(crate) use permissions::resolve_permission_profile; pub use service::ConfigService; pub use service::ConfigServiceError; -pub use types::ApprovalsReviewer; pub use codex_git_utils::GhostSnapshotConfig; @@ -582,7 +581,7 @@ pub struct Config { pub tool_suggest: ToolSuggestConfig, /// OTEL configuration (exporter type, endpoint, headers, etc.). - pub otel: crate::config::types::OtelConfig, + pub otel: codex_config::types::OtelConfig, } #[derive(Debug, Clone, Default)] @@ -1393,18 +1392,18 @@ pub struct ConfigToml { /// When `false`, disables analytics across Codex product surfaces in this machine. /// Defaults to `true`. - pub analytics: Option, + pub analytics: Option, /// When `false`, disables feedback collection across Codex product surfaces. /// Defaults to `true`. - pub feedback: Option, + pub feedback: Option, /// Settings for app-specific controls. #[serde(default)] pub apps: Option, /// OTEL configuration. - pub otel: Option, + pub otel: Option, /// Windows-specific configuration. #[serde(default)] @@ -1414,7 +1413,7 @@ pub struct ConfigToml { pub windows_wsl_setup_acknowledged: Option, /// Collection of in-product notices (different from notifications) - /// See [`crate::config::types::Notices`] for more details + /// See [`codex_config::types::Notice`] for more details pub notice: Option, /// Legacy, now use features diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index fcfda644e0..7dd8598c0b 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -4,9 +4,9 @@ use serde::Deserialize; use serde::Serialize; use crate::config::ToolsToml; -use crate::config::types::ApprovalsReviewer; -use crate::config::types::Personality; -use crate::config::types::WindowsToml; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::Personality; +use codex_config::types::WindowsToml; use codex_features::FeaturesToml; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::SandboxMode; @@ -54,7 +54,7 @@ pub struct ConfigProfile { pub tools_view_image: Option, pub tools: Option, pub web_search: Option, - pub analytics: Option, + pub analytics: Option, #[serde(default)] pub windows: Option, /// Optional feature toggles scoped to this profile. diff --git a/codex-rs/core/src/config/schema.rs b/codex-rs/core/src/config/schema.rs index 53e0f7f028..bde38f7eb5 100644 --- a/codex-rs/core/src/config/schema.rs +++ b/codex-rs/core/src/config/schema.rs @@ -1,5 +1,5 @@ use crate::config::ConfigToml; -use crate::config::types::RawMcpServerConfig; +use codex_config::types::RawMcpServerConfig; use codex_features::FEATURES; use codex_features::legacy_feature_keys; use schemars::r#gen::SchemaGenerator; diff --git a/codex-rs/core/src/config/types.rs b/codex-rs/core/src/config/types.rs deleted file mode 100644 index 9debd7d79e..0000000000 --- a/codex-rs/core/src/config/types.rs +++ /dev/null @@ -1 +0,0 @@ -pub use codex_config::types::*; diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index e02a6fc227..10e10e99fc 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -26,14 +26,14 @@ use tracing::warn; use crate::codex::INITIAL_SUBMIT_ID; use crate::config::Config; -use crate::config::types::AppToolApproval; -use crate::config::types::AppsConfigToml; -use crate::config::types::ToolSuggestDiscoverableType; use crate::config_loader::AppsRequirementsToml; use crate::mcp::McpManager; use crate::plugins::AppConnectorId; use crate::plugins::PluginsManager; use crate::plugins::list_tool_suggest_discoverable_plugins; +use codex_config::types::AppToolApproval; +use codex_config::types::AppsConfigToml; +use codex_config::types::ToolSuggestDiscoverableType; use codex_features::Feature; use codex_login::AuthManager; use codex_login::CodexAuth; diff --git a/codex-rs/core/src/connectors_tests.rs b/codex-rs/core/src/connectors_tests.rs index 11ec4b6ca5..893ab243ca 100644 --- a/codex-rs/core/src/connectors_tests.rs +++ b/codex-rs/core/src/connectors_tests.rs @@ -1,16 +1,16 @@ use super::*; use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; -use crate::config::types::AppConfig; -use crate::config::types::AppToolConfig; -use crate::config::types::AppToolsConfig; -use crate::config::types::AppsDefaultConfig; use crate::config_loader::AppRequirementToml; use crate::config_loader::AppsRequirementsToml; use crate::config_loader::CloudRequirementsLoader; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigRequirements; use crate::config_loader::ConfigRequirementsToml; +use codex_config::types::AppConfig; +use codex_config::types::AppToolConfig; +use codex_config::types::AppToolsConfig; +use codex_config::types::AppsDefaultConfig; use codex_features::Feature; use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::mcp_connection_manager::ToolInfo; diff --git a/codex-rs/core/src/exec_env.rs b/codex-rs/core/src/exec_env.rs index 83ac8ad379..4dd5532d51 100644 --- a/codex-rs/core/src/exec_env.rs +++ b/codex-rs/core/src/exec_env.rs @@ -1,6 +1,6 @@ -use crate::config::types::EnvironmentVariablePattern; -use crate::config::types::ShellEnvironmentPolicy; -use crate::config::types::ShellEnvironmentPolicyInherit; +use codex_config::types::EnvironmentVariablePattern; +use codex_config::types::ShellEnvironmentPolicy; +use codex_config::types::ShellEnvironmentPolicyInherit; use codex_protocol::ThreadId; use std::collections::HashMap; use std::collections::HashSet; diff --git a/codex-rs/core/src/exec_env_tests.rs b/codex-rs/core/src/exec_env_tests.rs index ec6b5b5bb5..1b486834e9 100644 --- a/codex-rs/core/src/exec_env_tests.rs +++ b/codex-rs/core/src/exec_env_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::config::types::ShellEnvironmentPolicyInherit; +use codex_config::types::ShellEnvironmentPolicyInherit; use maplit::hashmap; fn make_vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> { diff --git a/codex-rs/core/src/guardian/review_session.rs b/codex-rs/core/src/guardian/review_session.rs index 88bc795c16..2a63e5b547 100644 --- a/codex-rs/core/src/guardian/review_session.rs +++ b/codex-rs/core/src/guardian/review_session.rs @@ -34,9 +34,9 @@ use crate::config::Constrained; use crate::config::ManagedFeatures; use crate::config::NetworkProxySpec; use crate::config::Permissions; -use crate::config::types::McpServerConfig; use crate::model_provider_info::ModelProviderInfo; use crate::rollout::recorder::RolloutRecorder; +use codex_config::types::McpServerConfig; use codex_features::Feature; use super::GUARDIAN_REVIEW_TIMEOUT; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 994f9586d9..344e46d0be 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -19,7 +19,6 @@ use crate::config::Config; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; use crate::config::load_global_mcp_servers; -use crate::config::types::AppToolApproval; use crate::connectors; use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; @@ -31,6 +30,7 @@ use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template; use codex_analytics::AppInvocation; use codex_analytics::InvocationType; use codex_analytics::build_track_events_context; +use codex_config::types::AppToolApproval; use codex_features::Feature; use codex_mcp::mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_otel::sanitize_metric_tag_value; @@ -583,7 +583,7 @@ fn custom_mcp_tool_approval_mode( .and_then(|table| table.get("mcp_servers")) .cloned() .and_then(|value| { - HashMap::::deserialize(value).ok() + HashMap::::deserialize(value).ok() }) .and_then(|servers| servers.get(server).cloned()) .and_then(|server| server.tools.get(tool_name).cloned()) @@ -1541,8 +1541,7 @@ fn project_mcp_tool_approval_config_folder(config: &Config, server: &str) -> Opt .and_then(|table| table.get("mcp_servers")) .cloned() .and_then(|value| { - HashMap::::deserialize(value) - .ok() + HashMap::::deserialize(value).ok() })?; if servers.contains_key(server) { layer diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 8acdf917e5..5bb9194857 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1,17 +1,17 @@ use super::*; use crate::codex::make_session_and_context; use crate::codex::make_session_and_context_with_rx; -use crate::config::ApprovalsReviewer; use crate::config::ConfigBuilder; use crate::config::ConfigToml; -use crate::config::types::AppConfig; -use crate::config::types::AppToolConfig; -use crate::config::types::AppToolsConfig; -use crate::config::types::AppsConfigToml; -use crate::config::types::McpServerConfig; -use crate::config::types::McpServerToolConfig; use crate::state::ActiveTurn; use codex_config::CONFIG_TOML_FILE; +use codex_config::types::AppConfig; +use codex_config::types::AppToolConfig; +use codex_config::types::AppToolsConfig; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::AppsConfigToml; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerToolConfig; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_response_created; diff --git a/codex-rs/core/src/memories/phase1.rs b/codex-rs/core/src/memories/phase1.rs index 921bc9953c..ff050ac5b6 100644 --- a/codex-rs/core/src/memories/phase1.rs +++ b/codex-rs/core/src/memories/phase1.rs @@ -3,7 +3,6 @@ use crate::RolloutRecorder; use crate::codex::Session; use crate::codex::TurnContext; use crate::config::Config; -use crate::config::types::MemoriesConfig; use crate::contextual_user_message::is_memory_excluded_contextual_user_fragment; use crate::error::CodexErr; use crate::memories::metrics; @@ -13,6 +12,7 @@ use crate::memories::prompts::build_stage_one_input_message; use crate::rollout::INTERACTIVE_SESSION_SOURCES; use crate::rollout::policy::should_persist_response_item_for_memories; use codex_api::ResponseEvent; +use codex_config::types::MemoriesConfig; use codex_otel::SessionTelemetry; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; use codex_protocol::config_types::ServiceTier; diff --git a/codex-rs/core/src/memories/tests.rs b/codex-rs/core/src/memories/tests.rs index 783bac3c37..6255eacdeb 100644 --- a/codex-rs/core/src/memories/tests.rs +++ b/codex-rs/core/src/memories/tests.rs @@ -1,6 +1,5 @@ use super::storage::rebuild_raw_memories_file_from_memories; use super::storage::sync_rollout_summaries_from_memories; -use crate::config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION; use crate::memories::clear_memory_root_contents; use crate::memories::ensure_layout; use crate::memories::memory_root; @@ -8,6 +7,7 @@ use crate::memories::raw_memories_file; use crate::memories::rollout_summaries_dir; use chrono::TimeZone; use chrono::Utc; +use codex_config::types::DEFAULT_MEMORIES_MAX_RAW_MEMORIES_FOR_CONSOLIDATION; use codex_protocol::ThreadId; use codex_state::Stage1Output; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/src/message_history.rs b/codex-rs/core/src/message_history.rs index d9613e4b8b..e2d5510857 100644 --- a/codex-rs/core/src/message_history.rs +++ b/codex-rs/core/src/message_history.rs @@ -36,7 +36,7 @@ use tokio::fs; use tokio::io::AsyncReadExt; use crate::config::Config; -use crate::config::types::HistoryPersistence; +use codex_config::types::HistoryPersistence; use codex_protocol::ThreadId; #[cfg(unix)] diff --git a/codex-rs/core/src/otel_init.rs b/codex-rs/core/src/otel_init.rs index 9e38cea52d..c732692d62 100644 --- a/codex-rs/core/src/otel_init.rs +++ b/codex-rs/core/src/otel_init.rs @@ -1,6 +1,6 @@ use crate::config::Config; -use crate::config::types::OtelExporterKind as Kind; -use crate::config::types::OtelHttpProtocol as Protocol; +use codex_config::types::OtelExporterKind as Kind; +use codex_config::types::OtelHttpProtocol as Protocol; use codex_features::Feature; use codex_login::default_client::originator; use codex_otel::OtelProvider; diff --git a/codex-rs/core/src/plugins/discoverable.rs b/codex-rs/core/src/plugins/discoverable.rs index f7006185bf..8c630619b2 100644 --- a/codex-rs/core/src/plugins/discoverable.rs +++ b/codex-rs/core/src/plugins/discoverable.rs @@ -7,7 +7,7 @@ use super::PluginCapabilitySummary; use super::PluginReadRequest; use super::PluginsManager; use crate::config::Config; -use crate::config::types::ToolSuggestDiscoverableType; +use codex_config::types::ToolSuggestDiscoverableType; use codex_features::Feature; use codex_tools::DiscoverablePluginInfo; diff --git a/codex-rs/core/src/plugins/manager.rs b/codex-rs/core/src/plugins/manager.rs index 9147675e2f..2b21a23703 100644 --- a/codex-rs/core/src/plugins/manager.rs +++ b/codex-rs/core/src/plugins/manager.rs @@ -33,8 +33,6 @@ use crate::config::ConfigService; use crate::config::ConfigServiceError; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; -use crate::config::types::McpServerConfig; -use crate::config::types::PluginConfig; use crate::config_loader::ConfigLayerStack; use crate::config_rules::SkillConfigRules; use crate::config_rules::resolve_disabled_skill_paths; @@ -44,6 +42,8 @@ use crate::loader::load_skills_from_roots; use codex_analytics::AnalyticsEventsClient; use codex_app_server_protocol::ConfigValueWriteParams; use codex_app_server_protocol::MergeStrategy; +use codex_config::types::McpServerConfig; +use codex_config::types::PluginConfig; use codex_features::Feature; use codex_login::AuthManager; use codex_login::CodexAuth; diff --git a/codex-rs/core/src/plugins/manager_tests.rs b/codex-rs/core/src/plugins/manager_tests.rs index 2089670d73..a9f455bbc4 100644 --- a/codex-rs/core/src/plugins/manager_tests.rs +++ b/codex-rs/core/src/plugins/manager_tests.rs @@ -1,7 +1,6 @@ use super::*; use crate::config::CONFIG_TOML_FILE; use crate::config::ConfigBuilder; -use crate::config::types::McpServerTransportConfig; use crate::config_loader::ConfigLayerEntry; use crate::config_loader::ConfigLayerStack; use crate::config_loader::ConfigRequirements; @@ -14,6 +13,7 @@ use crate::plugins::test_support::write_curated_plugin_sha_with as write_curated use crate::plugins::test_support::write_file; use crate::plugins::test_support::write_openai_curated_marketplace; use codex_app_server_protocol::ConfigLayerSource; +use codex_config::types::McpServerTransportConfig; use codex_login::CodexAuth; use codex_protocol::protocol::Product; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/src/plugins/mod.rs b/codex-rs/core/src/plugins/mod.rs index 3e4902214c..a86502c28c 100644 --- a/codex-rs/core/src/plugins/mod.rs +++ b/codex-rs/core/src/plugins/mod.rs @@ -1,4 +1,4 @@ -use crate::config::types::McpServerConfig; +use codex_config::types::McpServerConfig; mod discoverable; mod injection; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index bb94085876..4fe6ac0e90 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -3,7 +3,6 @@ use crate::ThreadManager; use crate::built_in_model_providers; use crate::codex::make_session_and_context; use crate::config::DEFAULT_AGENT_MAX_DEPTH; -use crate::config::types::ShellEnvironmentPolicy; use crate::function_tool::FunctionCallError; use crate::session_prefix::format_subagent_notification_message; use crate::state::TaskKind; @@ -17,6 +16,7 @@ use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHa use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2; use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2; use crate::turn_diff_tracker::TurnDiffTracker; +use codex_config::types::ShellEnvironmentPolicy; use codex_features::Feature; use codex_login::AuthManager; use codex_login::CodexAuth; diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index 391c59d250..0def23d00c 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -2,7 +2,7 @@ use crate::config::Config; use crate::config::ConfigToml; use crate::config::edit::ConfigEditsBuilder; use crate::config::profile::ConfigProfile; -use crate::config::types::WindowsSandboxModeToml; +use codex_config::types::WindowsSandboxModeToml; use codex_features::Feature; use codex_features::Features; use codex_features::FeaturesToml; diff --git a/codex-rs/core/src/windows_sandbox_tests.rs b/codex-rs/core/src/windows_sandbox_tests.rs index d0ffa07b80..3fa3968389 100644 --- a/codex-rs/core/src/windows_sandbox_tests.rs +++ b/codex-rs/core/src/windows_sandbox_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::config::types::WindowsToml; +use codex_config::types::WindowsToml; use codex_features::Features; use codex_features::FeaturesToml; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 9b69149e9b..37ee27dd68 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -3,8 +3,8 @@ use anyhow::Result; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use codex_core::config::types::McpServerConfig; -use codex_core::config::types::McpServerTransportConfig; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerTransportConfig; use codex_features::Feature; use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem; use codex_protocol::dynamic_tools::DynamicToolResponse; diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index de88455484..4cb84e8b66 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use codex_core::config::types::Personality; +use codex_config::types::Personality; use codex_core::models_manager::manager::RefreshStrategy; use codex_features::Feature; use codex_login::CodexAuth; diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index 49f635432f..13e2819141 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -4,7 +4,7 @@ use std::fs; use std::sync::Arc; use anyhow::Result; -use codex_core::config::types::Personality; +use codex_config::types::Personality; use codex_features::Feature; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index a51a398264..22870cae73 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -1,4 +1,4 @@ -use codex_core::config::types::Personality; +use codex_config::types::Personality; use codex_core::models_manager::manager::ModelsManager; use codex_core::models_manager::manager::RefreshStrategy; use codex_features::Feature; diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 5b942c201a..4262a6aab0 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -9,8 +9,8 @@ use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; -use codex_core::config::types::McpServerConfig; -use codex_core::config::types::McpServerTransportConfig; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerTransportConfig; use codex_core::models_manager::manager::RefreshStrategy; use codex_login::CodexAuth; diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index d955f342ad..f35152e185 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -1,6 +1,6 @@ use anyhow::Result; -use codex_core::config::types::McpServerConfig; -use codex_core::config::types::McpServerTransportConfig; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerTransportConfig; use codex_features::Feature; use codex_protocol::ThreadId; use codex_protocol::dynamic_tools::DynamicToolSpec; diff --git a/codex-rs/core/tests/suite/tool_suggest.rs b/codex-rs/core/tests/suite/tool_suggest.rs index 09c29cb1f6..a65c58587d 100644 --- a/codex-rs/core/tests/suite/tool_suggest.rs +++ b/codex-rs/core/tests/suite/tool_suggest.rs @@ -2,9 +2,9 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use anyhow::Result; +use codex_config::types::ToolSuggestDiscoverable; +use codex_config::types::ToolSuggestDiscoverableType; use codex_core::config::Config; -use codex_core::config::types::ToolSuggestDiscoverable; -use codex_core::config::types::ToolSuggestDiscoverableType; use codex_features::Feature; use codex_login::CodexAuth; use codex_protocol::openai_models::ModelsResponse; diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index c3f019dd33..3f4a9e5a64 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -3,8 +3,8 @@ use anyhow::Context; use anyhow::Result; -use codex_core::config::types::McpServerConfig; -use codex_core::config::types::McpServerTransportConfig; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerTransportConfig; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; @@ -354,8 +354,8 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> let mut servers = config.mcp_servers.get().clone(); servers.insert( server_name.to_string(), - codex_core::config::types::McpServerConfig { - transport: codex_core::config::types::McpServerTransportConfig::Stdio { + codex_config::types::McpServerConfig { + transport: codex_config::types::McpServerTransportConfig::Stdio { command: rmcp_test_server_bin, args: Vec::new(), env: None, @@ -719,8 +719,8 @@ async fn mcp_tool_call_output_not_truncated_with_custom_limit() -> Result<()> { let mut servers = config.mcp_servers.get().clone(); servers.insert( server_name.to_string(), - codex_core::config::types::McpServerConfig { - transport: codex_core::config::types::McpServerTransportConfig::Stdio { + codex_config::types::McpServerConfig { + transport: codex_config::types::McpServerTransportConfig::Stdio { command: rmcp_test_server_bin, args: Vec::new(), env: None, diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index c0bfc7aca2..524c574fb0 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -17,6 +17,7 @@ workspace = true [target.'cfg(target_os = "linux")'.dependencies] clap = { workspace = true, features = ["derive"] } +codex-config = { workspace = true } codex-core = { workspace = true } codex-protocol = { workspace = true } codex-sandboxing = { workspace = true } diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index ba26c7e221..bb214905f2 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -1,6 +1,6 @@ #![cfg(target_os = "linux")] #![allow(clippy::unwrap_used)] -use codex_core::config::types::ShellEnvironmentPolicy; +use codex_config::types::ShellEnvironmentPolicy; use codex_core::error::CodexErr; use codex_core::error::Result; use codex_core::error::SandboxErr; diff --git a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs index 53d1852c93..256373953e 100644 --- a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs +++ b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs @@ -1,7 +1,7 @@ #![cfg(target_os = "linux")] #![allow(clippy::unwrap_used)] -use codex_core::config::types::ShellEnvironmentPolicy; +use codex_config::types::ShellEnvironmentPolicy; use codex_core::exec_env::create_env; use codex_protocol::protocol::SandboxPolicy; use pretty_assertions::assert_eq; diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index 5de2a9e5a3..a463d9bbe2 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [dependencies] anyhow = { workspace = true } codex-arg0 = { workspace = true } +codex-config = { workspace = true } codex-core = { workspace = true } codex-exec-server = { workspace = true } codex-features = { workspace = true } diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index e435eab0c9..2596339acd 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -181,8 +181,8 @@ pub async fn run_main( #[cfg(test)] mod tests { use super::*; + use codex_config::types::OtelExporterKind; use codex_core::config::ConfigBuilder; - use codex_core::config::types::OtelExporterKind; use pretty_assertions::assert_eq; use std::collections::HashMap; use tempfile::TempDir; diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 590257609e..814a7a783b 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -31,6 +31,7 @@ codex-app-server-protocol = { workspace = true } codex-arg0 = { workspace = true } codex-chatgpt = { workspace = true } codex-cloud-requirements = { workspace = true } +codex-config = { workspace = true } codex-core = { workspace = true } codex-features = { workspace = true } codex-feedback = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 89f5916e11..6e2e89e195 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -82,13 +82,13 @@ use codex_app_server_protocol::ThreadRollbackResponse; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnError as AppServerTurnError; use codex_app_server_protocol::TurnStatus; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::ModelAvailabilityNuxConfig; use codex_core::config::Config; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; use codex_core::config::edit::ConfigEdit; use codex_core::config::edit::ConfigEditsBuilder; -use codex_core::config::types::ApprovalsReviewer; -use codex_core::config::types::ModelAvailabilityNuxConfig; use codex_core::config_loader::ConfigLayerStackOrdering; use codex_core::message_history; use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig; @@ -6188,9 +6188,9 @@ mod tests { use codex_app_server_protocol::TurnStartedNotification; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as AppServerUserInput; + use codex_config::types::ModelAvailabilityNuxConfig; use codex_core::config::ConfigBuilder; use codex_core::config::ConfigOverrides; - use codex_core::config::types::ModelAvailabilityNuxConfig; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationMode; diff --git a/codex-rs/tui/src/app_command.rs b/codex-rs/tui/src/app_command.rs index 3c43c61862..0646cc297d 100644 --- a/codex-rs/tui/src/app_command.rs +++ b/codex-rs/tui/src/app_command.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use codex_core::config::types::ApprovalsReviewer; +use codex_config::types::ApprovalsReviewer; use codex_protocol::approvals::ElicitationAction; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::Personality; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 77a8c6748a..d727963f0d 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -31,7 +31,7 @@ use crate::bottom_pane::StatusLineItem; use crate::bottom_pane::TerminalTitleItem; use crate::history_cell::HistoryCell; -use codex_core::config::types::ApprovalsReviewer; +use codex_config::types::ApprovalsReviewer; use codex_features::Feature; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::config_types::Personality; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 3c8d068f9b..02429e9d9b 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -92,12 +92,12 @@ use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnPlanStepStatus; use codex_app_server_protocol::TurnStatus; use codex_chatgpt::connectors; +use codex_config::types::ApprovalsReviewer; +use codex_config::types::Notifications; +use codex_config::types::WindowsSandboxModeToml; use codex_core::config::Config; use codex_core::config::Constrained; use codex_core::config::ConstraintResult; -use codex_core::config::types::ApprovalsReviewer; -use codex_core::config::types::Notifications; -use codex_core::config::types::WindowsSandboxModeToml; use codex_core::config_loader::ConfigLayerStackOrdering; use codex_core::find_thread_name_by_id; use codex_core::plugins::PluginsManager; diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index e87634aea5..9af2cd30a7 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -79,14 +79,14 @@ pub(super) use codex_app_server_protocol::TurnError as AppServerTurnError; pub(super) use codex_app_server_protocol::TurnStartedNotification; pub(super) use codex_app_server_protocol::TurnStatus as AppServerTurnStatus; pub(super) use codex_app_server_protocol::UserInput as AppServerUserInput; -pub(super) use codex_core::config::ApprovalsReviewer; +pub(super) use codex_config::types::ApprovalsReviewer; +pub(super) use codex_config::types::Notifications; +#[cfg(target_os = "windows")] +pub(super) use codex_config::types::WindowsSandboxModeToml; pub(super) use codex_core::config::Config; pub(super) use codex_core::config::ConfigBuilder; pub(super) use codex_core::config::Constrained; pub(super) use codex_core::config::ConstraintError; -pub(super) use codex_core::config::types::Notifications; -#[cfg(target_os = "windows")] -pub(super) use codex_core::config::types::WindowsSandboxModeToml; pub(super) use codex_core::config_loader::AppRequirementToml; pub(super) use codex_core::config_loader::AppsRequirementsToml; pub(super) use codex_core::config_loader::ConfigLayerStack; diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index badd43b674..cf65f918e5 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -40,8 +40,8 @@ use crate::wrapping::adaptive_wrap_line; use crate::wrapping::adaptive_wrap_lines; use base64::Engine; use codex_app_server_protocol::McpServerStatus; +use codex_config::types::McpServerTransportConfig; use codex_core::config::Config; -use codex_core::config::types::McpServerTransportConfig; #[cfg(test)] use codex_core::mcp::McpManager; #[cfg(test)] @@ -2768,10 +2768,10 @@ mod tests { use crate::exec_cell::CommandOutput; use crate::exec_cell::ExecCall; use crate::exec_cell::ExecCell; + use codex_config::types::McpServerConfig; + use codex_config::types::McpServerDisabledReason; use codex_core::config::Config; use codex_core::config::ConfigBuilder; - use codex_core::config::types::McpServerConfig; - use codex_core::config::types::McpServerDisabledReason; use codex_otel::RuntimeMetricTotals; use codex_otel::RuntimeMetricsSummary; use codex_protocol::ThreadId; diff --git a/codex-rs/tui/src/notifications/mod.rs b/codex-rs/tui/src/notifications/mod.rs index e9a7ac1ddf..ff5e3defae 100644 --- a/codex-rs/tui/src/notifications/mod.rs +++ b/codex-rs/tui/src/notifications/mod.rs @@ -5,7 +5,7 @@ use std::env; use std::io; use bel::BelBackend; -use codex_core::config::types::NotificationMethod; +use codex_config::types::NotificationMethod; use osc9::Osc9Backend; #[derive(Debug)] @@ -74,7 +74,7 @@ fn supports_osc9() -> bool { #[cfg(test)] mod tests { use super::detect_backend; - use codex_core::config::types::NotificationMethod; + use codex_config::types::NotificationMethod; use serial_test::serial; use std::ffi::OsString; diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 9d521d1aa6..0877835ba8 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -45,7 +45,7 @@ use crate::tui::event_stream::EventBroker; use crate::tui::event_stream::TuiEventStream; #[cfg(unix)] use crate::tui::job_control::SuspendContext; -use codex_core::config::types::NotificationMethod; +use codex_config::types::NotificationMethod; mod event_stream; mod frame_rate_limiter;