Finalize model-specific tool plans in ToolRouter (#41195)

## Why

Planning tools for a candidate model must not change the selected model or its
Responses Lite tool inventory. Otherwise, preparing a fallback can overwrite
metadata before the current model's request is sent.

## What changed

- Build tool registries and visible specs from an explicit `ModelInfo`.
- Store the finalized tool mode, code-mode names, namespace inventory, and
  terminal and child-management capabilities on `ToolRouter`.
- Publish namespace inventory only after selecting the step's router, and use
  that router's mode when dispatching and recording tool calls.

## Testing

Added coverage for candidate-model isolation, fallback compaction metadata,
code-mode worker selection, normalized tool names, and router capabilities.

GitOrigin-RevId: 56df2de8f42c7e93a4c4dcd117720e40a0cca3db
This commit is contained in:
Abhinav authored and copyberry committed 2026-08-27 20:01:39 +00:00
1 parent 8aea62b2d8
commit 0182ff3480
13 files changed
+532 -127

No files matched your search

+101 -3
View File
@@ -1,4 +1,5 @@
use crate::function_tool::FunctionCallError;
use crate::responses_metadata::TurnToolNamespacesInfo;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
#[cfg(test)]
@@ -16,7 +17,11 @@ use crate::tools::registry::ToolRegistry;
use crate::tools::spec_plan::finalize_tool_router;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::SearchToolCallParams;
#[cfg(test)]
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ToolMode;
use codex_tools::DiscoverableTool;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use std::borrow::Cow;
@@ -65,9 +70,14 @@ pub(crate) fn tool_log_payload<'a>(
payload.log_payload()
}
/// One finalized tool plan: its advertised surfaces and matching executable runtimes.
pub struct ToolRouter {
registry: ToolRegistry,
model_visible_specs: Arc<[ToolSpec]>,
tool_mode: ToolMode,
code_mode_tool_names: BTreeMap<String, ToolName>,
tool_namespaces_info: Option<TurnToolNamespacesInfo>,
can_manage_children: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -86,12 +96,14 @@ impl ToolRouter {
#[cfg(test)]
pub(crate) fn from_registry(
turn_context: &TurnContext,
model_info: &ModelInfo,
registry: ToolRegistry,
hosted_specs: Vec<ToolSpec>,
tool_search_handler_cache: &ToolSearchHandlerCache,
) -> Self {
finalize_tool_router(
turn_context,
model_info,
registry,
hosted_specs,
tool_search_handler_cache,
@@ -99,17 +111,103 @@ impl ToolRouter {
.expect("test tool registry should not contain duplicate tools")
}
pub(crate) fn from_parts(registry: ToolRegistry, model_visible_specs: Vec<ToolSpec>) -> Self {
Self {
pub(crate) fn from_parts(
registry: ToolRegistry,
model_visible_specs: Vec<ToolSpec>,
tool_mode: ToolMode,
code_mode_tool_names: BTreeMap<String, ToolName>,
tool_namespaces_info: Option<TurnToolNamespacesInfo>,
child_management_tools: &[ToolName],
) -> Self {
let mut router = Self {
registry,
model_visible_specs: model_visible_specs.into(),
}
tool_mode,
code_mode_tool_names,
tool_namespaces_info,
can_manage_children: false,
};
router.can_manage_children = !child_management_tools.is_empty()
&& child_management_tools
.iter()
.all(|name| router.exposes_tool(name));
router
}
pub(crate) fn model_visible_specs(&self) -> Arc<[ToolSpec]> {
Arc::clone(&self.model_visible_specs)
}
pub(crate) fn tool_mode(&self) -> ToolMode {
self.tool_mode
}
/// Code Mode still needs its dispatcher when the nested tool set is empty.
pub(crate) fn requires_code_mode_worker(&self) -> bool {
matches!(self.tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly)
}
/// The normalized nested identities chosen after exclusions and collisions.
// Consumed by the follow-up cell-origin migration.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn code_mode_tool_names(&self) -> &BTreeMap<String, ToolName> {
&self.code_mode_tool_names
}
/// Optional request inventory for this exact plan, without publishing it to turn state.
pub(crate) fn tool_namespaces_info(&self) -> Option<&TurnToolNamespacesInfo> {
self.tool_namespaces_info.as_ref()
}
/// Whether the model can both start and interact with a terminal process.
// Consumed by the follow-up live tool-plan selection.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn has_terminal_controls(&self) -> bool {
self.exposes_tool(&ToolName::plain("exec_command"))
&& self.exposes_tool(&ToolName::plain("write_stdin"))
}
/// Whether the configured collaboration backend's child-management tools remain exposed.
// Consumed by the follow-up live tool-plan selection.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn can_manage_children(&self) -> bool {
self.can_manage_children
}
// Answers if the tool plan lets the model invoke the tool directly, through code mode, or deferred tool search.
fn exposes_tool(&self, name: &ToolName) -> bool {
let name = name.clone().with_default_namespace();
if self
.code_mode_tool_names
.values()
.any(|nested| nested.clone().with_default_namespace() == name)
|| self.model_visible_specs.iter().any(|spec| match spec {
ToolSpec::Function(_) | ToolSpec::Freeform(_) => {
name.is_default_namespace() && spec.name() == name.name
}
ToolSpec::Namespace(namespace) => {
name.namespace.as_deref() == Some(namespace.name.as_str())
&& namespace.tools.iter().any(|tool| match tool {
ResponsesApiNamespaceTool::Function(tool) => tool.name == name.name,
ResponsesApiNamespaceTool::Custom(tool) => tool.name == name.name,
})
}
ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => false,
})
{
return true;
}
self.model_visible_specs
.iter()
.any(|spec| matches!(spec, ToolSpec::ToolSearch { .. }))
&& self.registry.entries().any(|tool| {
tool.exposure.is_deferred()
&& tool.runtime.tool_name().with_default_namespace() == name
&& (tool.runtime.immutable_spec().is_some()
|| tool.runtime.search_info().is_some())
})
}
pub(crate) fn deferred_tool_namespaces(&self) -> BTreeMap<String, String> {
self.registry.deferred_tool_namespaces()
}