File size: 13,070 Bytes
52a9af3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | use crate::function_tool::FunctionCallError;
use crate::responses_metadata::TurnToolNamespacesInfo;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
#[cfg(test)]
use crate::session::turn_context::TurnContext;
use crate::tools::context::SharedTurnDiffTracker;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
#[cfg(test)]
use crate::tools::handlers::ToolSearchHandlerCache;
use crate::tools::registry::AnyToolResult;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolArgumentDiffConsumer;
use crate::tools::registry::ToolRegistry;
#[cfg(test)]
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;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use tokio_util::sync::CancellationToken;
use tracing::instrument;
pub use crate::tools::context::ToolCallSource;
#[derive(Clone, Debug, PartialEq)]
pub struct ToolCall {
pub tool_name: ToolName,
pub call_id: String,
pub payload: ToolPayload,
pub encrypted_function_args: Option<Vec<String>>,
}
impl ToolCall {
pub(crate) fn direct_source(&self) -> ToolCallSource {
if self.tool_name.namespace.as_deref() == Some("collaboration")
&& matches!(
self.tool_name.name.as_str(),
"spawn_agent" | "send_message" | "followup_task"
)
&& self
.encrypted_function_args
.as_ref()
.is_some_and(Vec::is_empty)
{
ToolCallSource::DirectPlaintextMessage
} else {
ToolCallSource::Direct
}
}
}
pub(crate) fn tool_log_payload<'a>(
payload: &'a ToolPayload,
source: &ToolCallSource,
) -> Cow<'a, str> {
if matches!(source, ToolCallSource::DirectPlaintextMessage) {
return Cow::Borrowed("[plaintext arguments]");
}
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)]
pub(crate) enum ToolSuggestPresentation {
ListTool,
RecommendationContext,
}
#[derive(Clone, Debug)]
pub(crate) struct ToolSuggestCandidates {
pub(crate) tools: Vec<DiscoverableTool>,
pub(crate) presentation: ToolSuggestPresentation,
}
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,
)
.expect("test tool registry should not contain duplicate tools")
}
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.
#[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.
#[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()
}
#[cfg(test)]
pub(crate) fn registered_tool_names_for_test(&self) -> Vec<ToolName> {
self.registry.tool_names_for_test()
}
#[cfg(test)]
pub(crate) fn tool_exposure_for_test(
&self,
name: &ToolName,
) -> Option<crate::tools::registry::ToolExposure> {
self.registry.tool_exposure(name)
}
pub(crate) fn create_diff_consumer(
&self,
tool_name: &ToolName,
) -> Option<Box<dyn ToolArgumentDiffConsumer>> {
self.registry.create_diff_consumer(tool_name)
}
pub fn tool_supports_parallel(&self, call: &ToolCall) -> bool {
self.registry
.supports_parallel_tool_calls(&call.tool_name)
.unwrap_or(false)
}
pub(crate) fn tool_runtime(&self, tool_name: &ToolName) -> Option<Arc<dyn CoreToolRuntime>> {
self.registry.tool(tool_name)
}
#[instrument(level = "trace", skip_all, err)]
pub fn build_tool_call(item: ResponseItem) -> Result<Option<ToolCall>, FunctionCallError> {
match item {
ResponseItem::FunctionCall {
name,
namespace,
arguments,
encrypted_function_args,
call_id,
..
} => {
let tool_name = ToolName::new(namespace, name).with_default_namespace();
Ok(Some(ToolCall {
tool_name,
call_id,
payload: ToolPayload::Function { arguments },
encrypted_function_args,
}))
}
ResponseItem::ToolSearchCall {
call_id: Some(call_id),
execution,
arguments,
..
} if execution == "client" => {
let arguments: SearchToolCallParams =
serde_json::from_value(arguments).map_err(|err| {
FunctionCallError::RespondToModel(format!(
"failed to parse tool_search arguments: {err}"
))
})?;
Ok(Some(ToolCall {
tool_name: ToolName::plain("tool_search"),
call_id,
payload: ToolPayload::ToolSearch { arguments },
encrypted_function_args: None,
}))
}
ResponseItem::ToolSearchCall { .. } => Ok(None),
ResponseItem::CustomToolCall {
name,
namespace,
input,
call_id,
..
} => Ok(Some(ToolCall {
tool_name: ToolName::new(namespace, name).with_default_namespace(),
call_id,
payload: ToolPayload::Custom { input },
encrypted_function_args: None,
})),
_ => Ok(None),
}
}
#[allow(dead_code)]
#[instrument(level = "trace", skip_all, err)]
pub async fn dispatch_tool_call_with_code_mode_result(
&self,
session: Arc<Session>,
step_context: Arc<StepContext>,
cancellation_token: CancellationToken,
tracker: SharedTurnDiffTracker,
call: ToolCall,
source: ToolCallSource,
) -> Result<AnyToolResult, FunctionCallError> {
self.dispatch_tool_call_with_code_mode_result_inner(
session,
step_context,
cancellation_token,
tracker,
call,
source,
/*terminal_outcome_reached*/ None,
)
.await
}
#[instrument(level = "trace", skip_all, err)]
#[allow(clippy::too_many_arguments)]
pub(crate) async fn dispatch_tool_call_with_terminal_outcome(
&self,
session: Arc<Session>,
step_context: Arc<StepContext>,
cancellation_token: CancellationToken,
tracker: SharedTurnDiffTracker,
call: ToolCall,
source: ToolCallSource,
terminal_outcome_reached: Arc<AtomicBool>,
) -> Result<AnyToolResult, FunctionCallError> {
self.dispatch_tool_call_with_code_mode_result_inner(
session,
step_context,
cancellation_token,
tracker,
call,
source,
Some(terminal_outcome_reached),
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn dispatch_tool_call_with_code_mode_result_inner(
&self,
session: Arc<Session>,
step_context: Arc<StepContext>,
cancellation_token: CancellationToken,
tracker: SharedTurnDiffTracker,
call: ToolCall,
source: ToolCallSource,
terminal_outcome_reached: Option<Arc<AtomicBool>>,
) -> Result<AnyToolResult, FunctionCallError> {
let ToolCall {
tool_name,
call_id,
payload,
..
} = call;
// Keep the legacy ToolInvocation.turn field tied to the same request state until handlers migrate.
let turn = Arc::clone(&step_context.turn);
let invocation = ToolInvocation {
session,
turn,
step_context,
cancellation_token,
tracker,
call_id,
tool_name,
source,
payload,
};
self.registry
.dispatch_any_with_terminal_outcome(invocation, terminal_outcome_reached)
.await
}
}
#[cfg(test)]
#[path = "router_tests.rs"]
mod tests;
|