| 1 | //! Deferred tool catalog and built-in advanced tool helpers. |
| 2 | //! |
| 3 | //! The streaming turn loop owns when tools are offered or executed. This module |
| 4 | //! owns the catalog-level policy around deferred loading, tool search, missing |
| 5 | //! tool suggestions, and the small set of built-in advanced tools that are not |
| 6 | //! registered by the normal runtime tool registry. |
| 7 | |
| 8 | use crate::tools::execution_envelope::{holds_bounded_verification, tool_call_denied_for}; |
| 9 | use codewhale_tools::names::{ |
| 10 | TERMINAL_CANCEL_NAME, TERMINAL_RESET_NAME, TERMINAL_RUN_NAME, TERMINAL_SEND_NAME, |
| 11 | TERMINAL_WAIT_NAME, TOOL_SEARCH_NAME, is_tool_search_tool, |
| 12 | }; |
| 13 | use std::collections::HashSet; |
| 14 | use std::path::Path; |
| 15 | use std::time::Duration; |
| 16 | |
| 17 | use serde_json::{Value, json}; |
| 18 | |
| 19 | #[cfg(test)] |
| 20 | use crate::mcp::McpPool; |
| 21 | use crate::model_profile::ToolSurfaceBudget; |
| 22 | use crate::tools::spec::{ |
| 23 | ToolContext, ToolError, ToolResult, optional_bool, optional_str, optional_u64, required_str, |
| 24 | }; |
| 25 | use codewhale_config::AppMode; |
| 26 | use codewhale_execpolicy::tool_rules::{tool_denied, tool_matches_any_rule}; |
| 27 | use codewhale_models::Tool; |
| 28 | |
| 29 | use crate::core::session::ToolActivationCache; |
| 30 | use codewhale_dependencies::ExternalTool; |
| 31 | use codewhale_runtime::features::{Feature, Features}; |
| 32 | use codewhale_runtime::regex_cache::compile_user_regex_case_insensitive; |
| 33 | pub const CODE_EXECUTION_TOOL_NAME: &str = "code_execution"; |
| 34 | const CODE_EXECUTION_TOOL_TYPE: &str = "code_execution_20250825"; |
| 35 | const CODE_EXECUTION_DESCRIPTION: &str = "Execute Python code with the local Python interpreter using this call's execution policy and return stdout/stderr/return_code as JSON."; |
| 36 | pub(super) use crate::tools::codemode::EXECUTE_TOOLS_TOOL_NAME; |
| 37 | const TOOL_RESULT_RETRIEVAL_NAME: &str = "retrieve_tool_result"; |
| 38 | const TOOL_SEARCH_TYPE: &str = "tool_search_20251119"; |
| 39 | const TOOL_SEARCH_DEFAULT_MAX_RESULTS: usize = 4; |
| 40 | const TOOL_SEARCH_MAX_RESULTS_LIMIT: usize = 8; |
| 41 | |
| 42 | // Crate-visible so the hook gate tests the real eager names instead of a copy. |
| 43 | #[rustfmt::skip] |
| 44 | pub const DEFAULT_ACTIVE_NATIVE_TOOLS: &[&str] = &[ |
| 45 | // Core work controls are eager; specialized tools stay searchable. |
| 46 | "read", "write", "edit", "list_dir", "file_search", "grep_files", "bash", "agent", "todo_write", |
| 47 | // Starting a goal stays eager; follow-up goal and background-shell controls auto-activate on demand. |
| 48 | "create_goal", |
| 49 | "present", |
| 50 | // The prompt core tells the model to discover skills through |
| 51 | // `load_skill`, so the tool has to be on the wire for that instruction |
| 52 | // to be true. |
| 53 | "load_skill", |
| 54 | ]; |
| 55 | |
| 56 | pub const GOAL_FOLLOWUP_TOOLS: &[&str] = &["get_goal", "update_goal"]; |
| 57 | pub const TASK_SHELL_WAIT_NAME: &str = "task_shell_wait"; |
| 58 | |
| 59 | const CORE_ACTION_TOOL_FALLBACKS: &[CoreActionToolFallback] = &[ |
| 60 | CoreActionToolFallback { |
| 61 | name: "bash", |
| 62 | description: "Run shell commands in the workspace.", |
| 63 | unavailable_reason: "Not present in the current model-visible catalog. The session profile, feature availability, or a command tool allow/deny gate can remove shell access. Plan keeps the same primitive identity but centrally refuses execution.", |
| 64 | }, |
| 65 | CoreActionToolFallback { |
| 66 | name: "read", |
| 67 | description: "Read workspace files.", |
| 68 | unavailable_reason: "Not present in the current model-visible catalog. File reads are available in Plan and executable modes unless a command allow/deny gate removes them.", |
| 69 | }, |
| 70 | CoreActionToolFallback { |
| 71 | name: "write", |
| 72 | description: "Create or replace workspace files.", |
| 73 | unavailable_reason: "Not present in the current model-visible catalog. Plan mode has no file-writing authority; the user can change modes with /mode.", |
| 74 | }, |
| 75 | CoreActionToolFallback { |
| 76 | name: "edit", |
| 77 | description: "Apply exact replacements to workspace files.", |
| 78 | unavailable_reason: "Not present in the current model-visible catalog. Plan mode has no file-writing authority; the user can change modes with /mode.", |
| 79 | }, |
| 80 | ]; |
| 81 | |
| 82 | #[derive(Debug, Clone, Copy)] |
| 83 | struct CoreActionToolFallback { |
| 84 | name: &'static str, |
| 85 | description: &'static str, |
| 86 | unavailable_reason: &'static str, |
| 87 | } |
| 88 | |
| 89 | /// Pre-computed lowercased haystack + name for each fallback; built once. |
| 90 | struct CachedFallback { |
| 91 | fallback: CoreActionToolFallback, |
| 92 | haystack: String, |
| 93 | name_lower: String, |
| 94 | } |
| 95 | |
| 96 | static CACHED_FALLBACKS: std::sync::OnceLock<Vec<CachedFallback>> = std::sync::OnceLock::new(); |
| 97 | |
| 98 | fn cached_fallbacks() -> &'static [CachedFallback] { |
| 99 | CACHED_FALLBACKS.get_or_init(|| { |
| 100 | CORE_ACTION_TOOL_FALLBACKS |
| 101 | .iter() |
| 102 | .map(|f| CachedFallback { |
| 103 | fallback: *f, |
| 104 | haystack: format!( |
| 105 | "{}\n{}\n{}", |
| 106 | f.name.to_lowercase(), |
| 107 | f.description.to_lowercase(), |
| 108 | f.unavailable_reason.to_lowercase(), |
| 109 | ), |
| 110 | name_lower: f.name.to_lowercase(), |
| 111 | }) |
| 112 | .collect() |
| 113 | }) |
| 114 | } |
| 115 | |
| 116 | /// Membership index over [`DEFAULT_ACTIVE_NATIVE_TOOLS`], built once for the |
| 117 | /// process lifetime. The array stays the source of truth for ordered |
| 118 | /// inspection; this set only accelerates the |
| 119 | /// hot membership check in [`should_default_defer_tool`], which runs once per |
| 120 | /// catalog tool on every catalog rebuild (i.e. per turn) — an O(n·m) linear |
| 121 | /// scan over the array collapses to O(1) hashed lookups. |
| 122 | static DEFAULT_ACTIVE_NATIVE_TOOLS_SET: std::sync::OnceLock<HashSet<&'static str>> = |
| 123 | std::sync::OnceLock::new(); |
| 124 | |
| 125 | fn default_active_native_tools_set() -> &'static HashSet<&'static str> { |
| 126 | DEFAULT_ACTIVE_NATIVE_TOOLS_SET |
| 127 | .get_or_init(|| DEFAULT_ACTIVE_NATIVE_TOOLS.iter().copied().collect()) |
| 128 | } |
| 129 | |
| 130 | pub(super) fn is_wildcard_tool_rule(rule: &str) -> bool { |
| 131 | rule.contains('*') || rule.contains('?') |
| 132 | } |
| 133 | |
| 134 | pub(super) fn extend_always_load_from_exact_rules( |
| 135 | always_load: &mut HashSet<String>, |
| 136 | rules: &[String], |
| 137 | ) { |
| 138 | for rule in rules { |
| 139 | let trimmed = rule.trim(); |
| 140 | if !trimmed.is_empty() && !is_wildcard_tool_rule(trimmed) { |
| 141 | always_load.insert(trimmed.to_string()); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | pub(super) fn always_load_matches(always_load: &HashSet<String>, name: &str) -> bool { |
| 147 | always_load.contains(name) |
| 148 | || always_load.iter().any(|entry| { |
| 149 | entry |
| 150 | .strip_suffix('*') |
| 151 | .is_some_and(|prefix| !prefix.is_empty() && name.starts_with(prefix)) |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | pub(super) fn should_default_defer_tool(name: &str, always_load: &HashSet<String>) -> bool { |
| 156 | if always_load_matches(always_load, name) { |
| 157 | return false; |
| 158 | } |
| 159 | |
| 160 | // Membership-only test (no ordering dependency): the side set built from |
| 161 | // DEFAULT_ACTIVE_NATIVE_TOOLS returns identical hit/miss results as the |
| 162 | // former `.iter().any(...)` linear scan. |
| 163 | !default_active_native_tools_set().contains(name) |
| 164 | } |
| 165 | |
| 166 | pub fn apply_native_tool_deferral(catalog: &mut [Tool], always_load: &HashSet<String>) { |
| 167 | for tool in catalog { |
| 168 | tool.defer_loading = Some(should_default_defer_tool(&tool.name, always_load)); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | pub(super) fn apply_mcp_tool_deferral( |
| 173 | catalog: &mut [Tool], |
| 174 | _mode: AppMode, |
| 175 | always_load: &HashSet<String>, |
| 176 | ) { |
| 177 | for tool in catalog { |
| 178 | if always_load_matches(always_load, &tool.name) { |
| 179 | tool.defer_loading = Some(false); |
| 180 | continue; |
| 181 | } |
| 182 | tool.defer_loading = Some(true); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// Build the model tool catalog from native and MCP tool lists. |
| 187 | /// |
| 188 | /// **Catalog-head stability invariant.** The head of the catalog (all |
| 189 | /// non-deferred tools) must remain byte-identical across mode toggles |
| 190 | /// (Plan ↔ Agent ↔ YOLO) for tools that are common to both modes. |
| 191 | /// Deferred tool activations append to the tail and never reorder the |
| 192 | /// head. This invariant is critical for DeepSeek's KV prefix cache: |
| 193 | /// the tools array is part of the immutable prefix, and any byte-level |
| 194 | /// change in the head forces a full re-prefill on the next turn. |
| 195 | #[cfg(any(test, feature = "test-support"))] |
| 196 | pub(super) fn build_model_tool_catalog( |
| 197 | native_tools: Vec<Tool>, |
| 198 | mcp_tools: Vec<Tool>, |
| 199 | mode: AppMode, |
| 200 | always_load: &HashSet<String>, |
| 201 | ) -> Vec<Tool> { |
| 202 | build_model_tool_catalog_with_surface( |
| 203 | native_tools, |
| 204 | mcp_tools, |
| 205 | mode, |
| 206 | always_load, |
| 207 | ToolSurfaceBudget::Standard, |
| 208 | ) |
| 209 | } |
| 210 | |
| 211 | pub(super) fn build_model_tool_catalog_with_surface( |
| 212 | mut native_tools: Vec<Tool>, |
| 213 | mut mcp_tools: Vec<Tool>, |
| 214 | mode: AppMode, |
| 215 | always_load: &HashSet<String>, |
| 216 | surface_budget: ToolSurfaceBudget, |
| 217 | ) -> Vec<Tool> { |
| 218 | apply_native_tool_deferral(&mut native_tools, always_load); |
| 219 | apply_mcp_tool_deferral(&mut mcp_tools, mode, always_load); |
| 220 | apply_tool_surface_budget(&mut native_tools, surface_budget, always_load); |
| 221 | apply_tool_surface_budget(&mut mcp_tools, surface_budget, always_load); |
| 222 | // Sort each partition by name for prefix-cache stability (#263). The |
| 223 | // upstream `to_api_tools()` already sorts the registry's HashMap output; |
| 224 | // this catalog is built from caller-supplied Vecs which the test harness |
| 225 | // and (future) caller refactors may not pre-sort. Built-ins stay as a |
| 226 | // contiguous prefix ahead of MCP tools so adding/removing an MCP tool |
| 227 | // never shifts a built-in's position. |
| 228 | native_tools.sort_by(|a, b| a.name.cmp(&b.name)); |
| 229 | mcp_tools.sort_by(|a, b| a.name.cmp(&b.name)); |
| 230 | native_tools.extend(mcp_tools); |
| 231 | native_tools |
| 232 | } |
| 233 | |
| 234 | // A second Registry authority used to live here: it appended a "call |
| 235 | // registry_sync before this tool" paragraph to a model-visible `exec_shell` |
| 236 | // description. The model-visible shell tool is `bash` — `exec_shell` is only a |
| 237 | // canonical *action* name (see `codewhale_execpolicy::canonical_action`) — so the hook never |
| 238 | // fired on a live catalog, and its own test pinned that it must not touch |
| 239 | // `bash`. The Registry instruction in `Engine::new` is the single prompt |
| 240 | // authority for this decision; a per-tool copy of it is not revived here. |
| 241 | |
| 242 | pub(super) fn apply_tool_surface_budget( |
| 243 | catalog: &mut [Tool], |
| 244 | surface_budget: ToolSurfaceBudget, |
| 245 | always_load: &HashSet<String>, |
| 246 | ) { |
| 247 | if !matches!(surface_budget, ToolSurfaceBudget::Compact) { |
| 248 | return; |
| 249 | } |
| 250 | for tool in catalog { |
| 251 | if always_load_matches(always_load, &tool.name) { |
| 252 | continue; |
| 253 | } |
| 254 | if matches!(tool.name.as_str(), "Run" | "tasks" | "Web") { |
| 255 | tool.defer_loading = Some(true); |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | /// Whether two tool-surface budgets currently produce the same catalog. |
| 261 | /// |
| 262 | /// Runs [`apply_tool_surface_budget`] over `catalog` under both budgets and |
| 263 | /// compares the results. `/preview-request` publishes the Standard-vs-Full |
| 264 | /// answer as a derived field so the truthful "these are currently collapsed" |
| 265 | /// disclosure cannot drift from the code: the day the shaper narrows Standard |
| 266 | /// differently from Full, this starts returning `false` on its own. |
| 267 | pub(super) fn surface_budgets_produce_same_catalog( |
| 268 | catalog: &[Tool], |
| 269 | always_load: &HashSet<String>, |
| 270 | left_budget: ToolSurfaceBudget, |
| 271 | right_budget: ToolSurfaceBudget, |
| 272 | ) -> bool { |
| 273 | let mut left = catalog.to_vec(); |
| 274 | let mut right = catalog.to_vec(); |
| 275 | apply_tool_surface_budget(&mut left, left_budget, always_load); |
| 276 | apply_tool_surface_budget(&mut right, right_budget, always_load); |
| 277 | serde_json::to_string(&left).ok() == serde_json::to_string(&right).ok() |
| 278 | } |
| 279 | |
| 280 | /// How the harness exposes tool-calling to the model, resolved per turn. |
| 281 | /// |
| 282 | /// Mirrors Codex's `ToolMode`: the model's own metadata wins, `[features]` |
| 283 | /// flags override the default, and anything else is [`ToolMode::Direct`]. |
| 284 | /// There is no user-facing mode to enter — the catalog shape is the whole |
| 285 | /// mechanism. Code mode exposes the VM with at most one named batch shortcut. (A `CodeModeOnly` restriction needs dispatch enforcement and is a |
| 286 | /// later slice, not a third variant here.) |
| 287 | /// |
| 288 | /// KV-cache effect: the inputs are session config (plus future per-model |
| 289 | /// metadata), so the resolved mode is prefix-stable within a session; a flag |
| 290 | /// flip refreshes the prefix under an explicit config-change reason like any |
| 291 | /// other catalog reshape. |
| 292 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 293 | pub enum ToolMode { |
| 294 | /// Composition by choice: `execute_tools` is deferred and `tool_search` stays offered. |
| 295 | Direct, |
| 296 | /// Composition by default: `execute_tools` is eager alongside direct tools. |
| 297 | CodeMode, |
| 298 | } |
| 299 | |
| 300 | /// Resolve the turn's tool mode: model hint first, `[features] code_mode` |
| 301 | /// second, [`ToolMode::Direct`] otherwise. The engine passes `None` for the |
| 302 | /// hint until per-model metadata is wired. |
| 303 | pub fn requested_tool_mode(model_hint: Option<ToolMode>, features: &Features) -> ToolMode { |
| 304 | model_hint.unwrap_or_else(|| { |
| 305 | if features.enabled(Feature::CodeMode) { |
| 306 | ToolMode::CodeMode |
| 307 | } else { |
| 308 | ToolMode::Direct |
| 309 | } |
| 310 | }) |
| 311 | } |
| 312 | |
| 313 | pub fn ensure_advanced_tooling( |
| 314 | catalog: &mut Vec<Tool>, |
| 315 | mode: AppMode, |
| 316 | always_load: &HashSet<String>, |
| 317 | tool_mode: ToolMode, |
| 318 | ) { |
| 319 | let had_cache_control = catalog.iter().any(|tool| tool.cache_control.is_some()); |
| 320 | // code_execution depends on a locally-installed Python interpreter |
| 321 | // (python3 / python / py -3). Before v0.8.31, the tool was always |
| 322 | // advertised and would fail at execution time on Windows where |
| 323 | // `python3` isn't on PATH — the model treated the tool as reliable |
| 324 | // once it appeared in the catalog. We now probe at catalog-build |
| 325 | // time and only advertise when an interpreter resolves. See |
| 326 | // `codewhale_dependencies::resolve_python_interpreter` for the probe. |
| 327 | if mode != AppMode::Plan |
| 328 | && !catalog.iter().any(|t| t.name == CODE_EXECUTION_TOOL_NAME) |
| 329 | && codewhale_dependencies::host_tool_available(CODE_EXECUTION_TOOL_NAME, || { |
| 330 | codewhale_dependencies::resolve_python_interpreter().is_some() |
| 331 | }) |
| 332 | { |
| 333 | catalog.push(Tool { |
| 334 | tool_type: Some(CODE_EXECUTION_TOOL_TYPE.to_string()), |
| 335 | name: CODE_EXECUTION_TOOL_NAME.to_string(), |
| 336 | description: CODE_EXECUTION_DESCRIPTION.to_string(), |
| 337 | input_schema: json!({ |
| 338 | "type": "object", |
| 339 | "properties": { |
| 340 | "code": { "type": "string", "description": "Python source code to execute." }, |
| 341 | "sandbox_permissions": { |
| 342 | "type": "string", |
| 343 | "enum": ["workspace-write", "danger-full-access"], |
| 344 | "description": "Request a wider policy for this exact execution after a sandbox denial; requires justification and explicit user approval." |
| 345 | }, |
| 346 | "justification": { |
| 347 | "type": "string", |
| 348 | "description": "Required with sandbox_permissions: why this exact code needs wider access." |
| 349 | } |
| 350 | }, |
| 351 | "required": ["code"] |
| 352 | }), |
| 353 | allowed_callers: Some(vec!["direct".to_string()]), |
| 354 | defer_loading: Some(should_default_defer_tool( |
| 355 | CODE_EXECUTION_TOOL_NAME, |
| 356 | always_load, |
| 357 | )), |
| 358 | input_examples: None, |
| 359 | strict: None, |
| 360 | cache_control: None, |
| 361 | }); |
| 362 | } |
| 363 | |
| 364 | // execute_tools needs no dependency probe: QuickJS is compiled in. |
| 365 | // Under CodeMode it is eager (including Plan, where every nested call |
| 366 | // still takes Plan's gates); under Direct it stays deferred. |
| 367 | if !catalog.iter().any(|t| t.name == EXECUTE_TOOLS_TOOL_NAME) { |
| 368 | let mut tool = crate::tools::codemode::execute_tools_tool_definition(); |
| 369 | tool.defer_loading = Some( |
| 370 | tool_mode == ToolMode::Direct && should_default_defer_tool(&tool.name, always_load), |
| 371 | ); |
| 372 | catalog.push(tool); |
| 373 | } |
| 374 | |
| 375 | if !catalog.iter().any(|t| t.name == TOOL_SEARCH_NAME) { |
| 376 | catalog.push(tool_search_tool()); |
| 377 | } |
| 378 | if had_cache_control { |
| 379 | crate::tools::registry::apply_tool_cache_breakpoint(catalog); |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | fn tool_search_tool() -> Tool { |
| 384 | Tool { |
| 385 | tool_type: Some(TOOL_SEARCH_TYPE.to_string()), |
| 386 | name: TOOL_SEARCH_NAME.to_string(), |
| 387 | description: "Search deferred tool definitions, including tools from connected MCP servers, and return matching references; matches load into your next step. Calling a deferred tool by name also loads it.".to_string(), |
| 388 | input_schema: json!({ |
| 389 | "type": "object", |
| 390 | "properties": { |
| 391 | "query": { "type": "string", "description": "Search query for tool discovery." }, |
| 392 | "match": { |
| 393 | "type": "string", |
| 394 | "enum": ["bm25", "regex"], |
| 395 | "default": "bm25", |
| 396 | "description": "Matching algorithm: bm25 for natural-language matching, regex for a regular expression over tool names/descriptions/schema." |
| 397 | }, |
| 398 | "max_results": { |
| 399 | "type": "integer", |
| 400 | "minimum": 1, |
| 401 | "maximum": TOOL_SEARCH_MAX_RESULTS_LIMIT, |
| 402 | "default": TOOL_SEARCH_DEFAULT_MAX_RESULTS, |
| 403 | "description": "Maximum number of matching tool references to return." |
| 404 | } |
| 405 | }, |
| 406 | "required": ["query"] |
| 407 | }), |
| 408 | allowed_callers: Some(vec!["direct".to_string()]), |
| 409 | defer_loading: Some(false), |
| 410 | input_examples: None, |
| 411 | strict: None, |
| 412 | cache_control: None, |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | pub(super) fn settle_discovery_surface( |
| 417 | catalog: &mut Vec<Tool>, |
| 418 | restore_tool_search: bool, |
| 419 | had_cache_control: bool, |
| 420 | ) { |
| 421 | if composition_eager(catalog) { |
| 422 | catalog.retain(|tool| !is_tool_search_tool(&tool.name)); |
| 423 | } else if restore_tool_search && !catalog.iter().any(|tool| tool.name == TOOL_SEARCH_NAME) { |
| 424 | catalog.push(tool_search_tool()); |
| 425 | } |
| 426 | if had_cache_control { |
| 427 | crate::tools::registry::apply_tool_cache_breakpoint(catalog); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | pub(super) fn unique_named_batch(catalog: &[Tool]) -> Option<usize> { |
| 432 | let mut batches = catalog.iter().enumerate().filter(|(_, tool)| { |
| 433 | crate::mcp::McpPool::is_mcp_tool(&tool.name) |
| 434 | && crate::mcp::named_batch_members(&tool.input_schema).is_some() |
| 435 | }); |
| 436 | let (index, tool) = batches.next()?; |
| 437 | (batches.next().is_none() |
| 438 | && tool.name.len() <= 128 |
| 439 | && tool |
| 440 | .name |
| 441 | .bytes() |
| 442 | .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') |
| 443 | && tool.description.len() <= 2048 |
| 444 | && tool.input_schema.to_string().len() + tool.description.len() <= 8192) |
| 445 | .then_some(index) |
| 446 | } |
| 447 | |
| 448 | pub(super) fn composition_eager(catalog: &[Tool]) -> bool { |
| 449 | catalog |
| 450 | .iter() |
| 451 | .any(|t| t.name == EXECUTE_TOOLS_TOOL_NAME && !t.defer_loading.unwrap_or(false)) |
| 452 | } |
| 453 | |
| 454 | pub(super) fn configure_composition_entry( |
| 455 | catalog: &mut [Tool], |
| 456 | name: Option<&str>, |
| 457 | members: &[String], |
| 458 | ) -> bool { |
| 459 | if !composition_eager(catalog) { |
| 460 | return false; |
| 461 | } |
| 462 | let mut definition = crate::tools::codemode::execute_tools_tool_definition(); |
| 463 | if !members.is_empty() |
| 464 | && let Some(batch) = catalog.iter().find(|tool| Some(tool.name.as_str()) == name) |
| 465 | && let Some((field, _)) = crate::mcp::named_batch_members(&batch.input_schema) |
| 466 | { |
| 467 | let deferred = batch.defer_loading.unwrap_or(false); |
| 468 | let bounds = &batch.input_schema["properties"][field]; |
| 469 | let (arguments_description, batch_description) = if deferred { |
| 470 | ( |
| 471 | format!( |
| 472 | "Step arguments follow `{}`; inspect its schema with tools.describe before the first batch.", |
| 473 | batch.name |
| 474 | ), |
| 475 | format!("Named step batch for `{}`.", batch.name), |
| 476 | ) |
| 477 | } else { |
| 478 | ( |
| 479 | "Use the named batch schema shown in this request; only these step tools are offered here.".to_string(), |
| 480 | batch.description.clone(), |
| 481 | ) |
| 482 | }; |
| 483 | let arguments = json!({"type":"object", "description":arguments_description, |
| 484 | "required":[field], "properties":{(field):{"type":"array","minItems":bounds["minItems"].as_u64().unwrap_or(1),"maxItems":bounds["maxItems"], |
| 485 | "items":{"type":"object","required":["tool"],"properties":{"arguments":{"type":"object"}, |
| 486 | "tool":{"type":"string","enum":members}}}}}}); |
| 487 | definition.description.push_str(" For a known sequence, pass batch instead of code. It runs that server's named steps in one gated call and returns a bounded result. Group known steps, including setup and their verification, in one batch. Use code if later actions depend on reading an intermediate result."); |
| 488 | definition.input_schema["properties"]["batch"] = json!({ |
| 489 | "type":"object", "description":batch_description, |
| 490 | "required":["tool","arguments"], "additionalProperties":false, |
| 491 | "properties":{ |
| 492 | "tool":{"type":"string","enum":[batch.name]}, |
| 493 | "arguments": arguments |
| 494 | } |
| 495 | }); |
| 496 | definition |
| 497 | .input_schema |
| 498 | .as_object_mut() |
| 499 | .expect("object schema") |
| 500 | .remove("required"); |
| 501 | definition.input_schema["oneOf"] = json!([{"required":["code"]},{"required":["batch"]}]); |
| 502 | } |
| 503 | if let Some(tool) = catalog |
| 504 | .iter_mut() |
| 505 | .find(|t| t.name == EXECUTE_TOOLS_TOOL_NAME) |
| 506 | { |
| 507 | let mut changed = false; |
| 508 | if tool.description != definition.description { |
| 509 | tool.description = definition.description; |
| 510 | changed = true; |
| 511 | } |
| 512 | if tool.input_schema != definition.input_schema { |
| 513 | tool.input_schema = definition.input_schema; |
| 514 | changed = true; |
| 515 | } |
| 516 | changed |
| 517 | } else { |
| 518 | false |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | pub(super) fn offered_batch(catalog: &[Tool]) -> Option<&Value> { |
| 523 | catalog |
| 524 | .iter() |
| 525 | .find(|tool| tool.name == EXECUTE_TOOLS_TOOL_NAME)? |
| 526 | .input_schema |
| 527 | .pointer("/properties/batch/properties") |
| 528 | } |
| 529 | |
| 530 | pub(super) fn offered_batch_allows(catalog: &[Tool], name: &str, input: &Value) -> bool { |
| 531 | let Some(schema) = offered_batch(catalog) |
| 532 | .filter(|s| s.pointer("/tool/enum/0").and_then(Value::as_str) == Some(name)) |
| 533 | else { |
| 534 | return false; |
| 535 | }; |
| 536 | let Some((field, members)) = schema |
| 537 | .get("arguments") |
| 538 | .and_then(crate::mcp::named_batch_members) |
| 539 | else { |
| 540 | return false; |
| 541 | }; |
| 542 | let bounds = &schema["arguments"]["properties"][field]; |
| 543 | let min = bounds["minItems"].as_u64().unwrap_or(1).max(1); |
| 544 | let max = bounds["maxItems"].as_u64().unwrap_or(0); |
| 545 | input |
| 546 | .get(field) |
| 547 | .and_then(Value::as_array) |
| 548 | .is_some_and(|steps| { |
| 549 | (min..=max).contains(&(steps.len() as u64)) |
| 550 | && steps |
| 551 | .iter() |
| 552 | .all(|step| step.get("tool").is_some_and(|tool| members.contains(tool))) |
| 553 | }) |
| 554 | } |
| 555 | |
| 556 | pub fn initial_active_tools(catalog: &[Tool]) -> HashSet<String> { |
| 557 | let mut active = HashSet::new(); |
| 558 | for tool in catalog { |
| 559 | if !tool.defer_loading.unwrap_or(false) { |
| 560 | active.insert(tool.name.clone()); |
| 561 | } |
| 562 | } |
| 563 | if active.is_empty() |
| 564 | && !catalog.is_empty() |
| 565 | && let Some(first) = catalog.first() |
| 566 | { |
| 567 | active.insert(first.name.clone()); |
| 568 | } |
| 569 | active |
| 570 | } |
| 571 | |
| 572 | /// Remove schemas evicted from the conversation cache without hiding tools |
| 573 | /// that the current catalog now exposes eagerly. |
| 574 | /// |
| 575 | /// A cached tool can become eager after an explicit `tools_always_load` |
| 576 | /// change or another policy update. Cache revalidation correctly forgets the |
| 577 | /// old deferred entry, but the eager catalog entry must remain active. |
| 578 | pub fn remove_evicted_cache_activations( |
| 579 | catalog: &[Tool], |
| 580 | active: &mut HashSet<String>, |
| 581 | evicted: impl IntoIterator<Item = String>, |
| 582 | ) { |
| 583 | for name in evicted { |
| 584 | let is_eager_now = catalog |
| 585 | .iter() |
| 586 | .any(|tool| tool.name == name && !tool.defer_loading.unwrap_or(false)); |
| 587 | if !is_eager_now { |
| 588 | active.remove(&name); |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | fn activate_deferred_tools( |
| 594 | catalog: &[Tool], |
| 595 | active: &mut HashSet<String>, |
| 596 | cache: &mut ToolActivationCache, |
| 597 | names: &[&str], |
| 598 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 599 | ) -> Result<bool, ToolError> { |
| 600 | let mut to_activate = Vec::new(); |
| 601 | for name in names { |
| 602 | let is_deferred = catalog |
| 603 | .iter() |
| 604 | .any(|tool| tool.name == *name && tool.defer_loading.unwrap_or(false)); |
| 605 | if !is_deferred { |
| 606 | continue; |
| 607 | } |
| 608 | if active.contains(*name) { |
| 609 | cache.record_use(name); |
| 610 | continue; |
| 611 | } |
| 612 | to_activate.push((*name).to_string()); |
| 613 | } |
| 614 | if to_activate.is_empty() { |
| 615 | return Ok(false); |
| 616 | } |
| 617 | let active_before = active.clone(); |
| 618 | let delta = cache.activate_measured(catalog, &to_activate, measure)?; |
| 619 | remove_evicted_cache_activations(catalog, active, delta.evicted.iter().cloned()); |
| 620 | active.extend(delta.admitted.iter().cloned()); |
| 621 | for name in &delta.admitted { |
| 622 | cache.record_use(name); |
| 623 | } |
| 624 | Ok(*active != active_before) |
| 625 | } |
| 626 | |
| 627 | pub(crate) fn result_started_background_shell_job(metadata: Option<&Value>) -> bool { |
| 628 | let Some(metadata) = metadata else { |
| 629 | return false; |
| 630 | }; |
| 631 | if metadata.get("backgrounded").and_then(Value::as_bool) == Some(true) { |
| 632 | return true; |
| 633 | } |
| 634 | let running_task = metadata |
| 635 | .get("status") |
| 636 | .and_then(Value::as_str) |
| 637 | .is_some_and(|status| status.eq_ignore_ascii_case("running")) |
| 638 | && metadata |
| 639 | .get("task_id") |
| 640 | .and_then(Value::as_str) |
| 641 | .is_some_and(|id| !id.is_empty()); |
| 642 | if running_task { |
| 643 | return true; |
| 644 | } |
| 645 | if metadata |
| 646 | .get("poll_with") |
| 647 | .and_then(Value::as_array) |
| 648 | .is_some_and(|tools| { |
| 649 | tools |
| 650 | .iter() |
| 651 | .any(|tool| tool.as_str() == Some(TASK_SHELL_WAIT_NAME)) |
| 652 | }) |
| 653 | { |
| 654 | return true; |
| 655 | } |
| 656 | metadata |
| 657 | .get("shell_jobs") |
| 658 | .and_then(Value::as_array) |
| 659 | .is_some_and(|jobs| { |
| 660 | jobs.iter().any(|job| { |
| 661 | job.get("status") |
| 662 | .and_then(Value::as_str) |
| 663 | .is_some_and(|status| status.eq_ignore_ascii_case("running")) |
| 664 | }) |
| 665 | }) |
| 666 | } |
| 667 | |
| 668 | /// Make result-dependent deferred schemas visible on the next provider step |
| 669 | /// when a tool result publishes retrievable evidence or starts a background |
| 670 | /// shell job. |
| 671 | pub fn activate_result_dependencies( |
| 672 | catalog: &[Tool], |
| 673 | active: &mut HashSet<String>, |
| 674 | cache: &mut ToolActivationCache, |
| 675 | result: &ToolResult, |
| 676 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 677 | ) -> Result<bool, ToolError> { |
| 678 | let mut names = Vec::new(); |
| 679 | let needs_retrieval = result |
| 680 | .metadata |
| 681 | .as_ref() |
| 682 | .and_then(|metadata| metadata.get("evidence_available")) |
| 683 | .and_then(Value::as_bool) |
| 684 | == Some(true) |
| 685 | || super::context::offers_retrieval(result.metadata.as_ref()); |
| 686 | if needs_retrieval { |
| 687 | names.push(TOOL_RESULT_RETRIEVAL_NAME); |
| 688 | } |
| 689 | if result_started_background_shell_job(result.metadata.as_ref()) { |
| 690 | names.push(TASK_SHELL_WAIT_NAME); |
| 691 | } |
| 692 | if names.is_empty() { |
| 693 | return Ok(false); |
| 694 | } |
| 695 | activate_deferred_tools(catalog, active, cache, &names, measure) |
| 696 | } |
| 697 | |
| 698 | pub fn activate_goal_followup_tools( |
| 699 | catalog: &[Tool], |
| 700 | active: &mut HashSet<String>, |
| 701 | cache: &mut ToolActivationCache, |
| 702 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 703 | ) -> Result<bool, ToolError> { |
| 704 | activate_deferred_tools(catalog, active, cache, GOAL_FOLLOWUP_TOOLS, measure) |
| 705 | } |
| 706 | |
| 707 | pub fn activate_background_shell_tools( |
| 708 | catalog: &[Tool], |
| 709 | active: &mut HashSet<String>, |
| 710 | cache: &mut ToolActivationCache, |
| 711 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 712 | ) -> Result<bool, ToolError> { |
| 713 | activate_deferred_tools(catalog, active, cache, &[TASK_SHELL_WAIT_NAME], measure) |
| 714 | } |
| 715 | |
| 716 | fn active_tool_list_from_catalog(catalog: &[Tool], active: &HashSet<String>) -> Vec<Tool> { |
| 717 | // Two-pass for prefix-cache stability (#263). Always-loaded tools come |
| 718 | // first in their stable catalog order; tools that started life deferred |
| 719 | // and were activated mid-conversation by ToolSearch get appended at the |
| 720 | // tail. Otherwise activating a deferred tool shifts every later tool's |
| 721 | // byte offset and busts the cached prefix from that point onwards. |
| 722 | let preserve_cache_control = catalog.iter().any(|tool| tool.cache_control.is_some()); |
| 723 | let catalog_len = catalog.len(); |
| 724 | let mut head: Vec<Tool> = Vec::with_capacity(catalog_len); |
| 725 | let mut tail: Vec<Tool> = Vec::with_capacity(catalog_len); |
| 726 | for tool in catalog { |
| 727 | if !active.contains(&tool.name) { |
| 728 | continue; |
| 729 | } |
| 730 | if tool.defer_loading.unwrap_or(false) { |
| 731 | tail.push(tool.clone()); |
| 732 | } else { |
| 733 | head.push(tool.clone()); |
| 734 | } |
| 735 | } |
| 736 | if preserve_cache_control { |
| 737 | for tool in &mut tail { |
| 738 | tool.cache_control = None; |
| 739 | } |
| 740 | crate::tools::registry::apply_tool_cache_breakpoint(&mut head); |
| 741 | } |
| 742 | head.extend(tail); |
| 743 | head |
| 744 | } |
| 745 | |
| 746 | pub(super) fn active_tools_for_step(catalog: &[Tool], active: &HashSet<String>) -> Vec<Tool> { |
| 747 | active_tool_list_from_catalog(catalog, active) |
| 748 | } |
| 749 | |
| 750 | /// One turn's executable and model-visible tool contract. |
| 751 | /// |
| 752 | /// The catalog is also the prompt's only availability taxonomy: stable prompt |
| 753 | /// prose deliberately does not enumerate tool names. Keeping the concrete |
| 754 | /// registry, searchable catalog, initial request subset, and command gates in |
| 755 | /// one value prevents preview, dispatch, and execution from reconstructing |
| 756 | /// different surfaces from mutable engine configuration. |
| 757 | pub(super) struct ToolSurfacePolicy { |
| 758 | /// Runtime registry that executes native and plugin tools. |
| 759 | pub(super) registry: crate::tools::ToolRegistry, |
| 760 | /// Complete turn catalog before applying the current mode, including deferred entries. |
| 761 | pub(super) catalog: Vec<Tool>, |
| 762 | /// Names active at the start of the turn. |
| 763 | pub(super) active_names: HashSet<String>, |
| 764 | /// Exact initial `tools` field. `None` means no field is sent. |
| 765 | pub(super) active: Option<Vec<Tool>>, |
| 766 | pub(super) mode: AppMode, |
| 767 | pub(super) strict_tool_mode: bool, |
| 768 | allowed_tools: Option<Vec<String>>, |
| 769 | disallowed_tools: Option<Vec<String>>, |
| 770 | holds_bounded_verification: bool, |
| 771 | pub(super) extension_tool_names: HashSet<String>, |
| 772 | /// Hard per-turn cap on admitted tool calls (#4415). The turn loop copies |
| 773 | /// this limit into its own admission counter at turn start; `None` means |
| 774 | /// unlimited (the default), which keeps the admission gate inert. |
| 775 | pub(super) max_tool_calls: Option<u32>, |
| 776 | } |
| 777 | |
| 778 | impl ToolSurfacePolicy { |
| 779 | #[allow(clippy::too_many_arguments)] |
| 780 | pub(super) fn new( |
| 781 | registry: crate::tools::ToolRegistry, |
| 782 | tools: Option<Vec<Tool>>, |
| 783 | mode: AppMode, |
| 784 | always_load: &HashSet<String>, |
| 785 | strict_tool_mode: bool, |
| 786 | allowed_tools: Option<Vec<String>>, |
| 787 | disallowed_tools: Option<Vec<String>>, |
| 788 | max_tool_calls: Option<u32>, |
| 789 | tool_mode: ToolMode, |
| 790 | ) -> Self { |
| 791 | let holds_bounded_verification = holds_bounded_verification(registry.context()); |
| 792 | let mut catalog = tools.unwrap_or_default(); |
| 793 | if !registry |
| 794 | .context() |
| 795 | .lsp_manager |
| 796 | .as_ref() |
| 797 | .is_some_and(|manager| manager.config().enabled) |
| 798 | { |
| 799 | catalog.retain(|tool| tool.name != "lsp"); |
| 800 | } |
| 801 | if !catalog.is_empty() { |
| 802 | ensure_advanced_tooling(&mut catalog, mode, always_load, tool_mode); |
| 803 | } |
| 804 | if registry.context().tool_authority.is_some() { |
| 805 | catalog.retain(|tool| tool.name != EXECUTE_TOOLS_TOOL_NAME); |
| 806 | } |
| 807 | let had_cache_control = catalog.iter().any(|tool| tool.cache_control.is_some()); |
| 808 | |
| 809 | // Synthetic tools are injected before narrowing. Doing this after the |
| 810 | // retain would re-advertise tool_search/code execution despite an |
| 811 | // explicit command gate. |
| 812 | catalog.retain(|tool| { |
| 813 | !tool_denied(disallowed_tools.as_deref(), &tool.name) |
| 814 | && (tool_allowed(allowed_tools.as_deref(), &tool.name) |
| 815 | || retrieval_available_beside_an_allowlist( |
| 816 | allowed_tools.as_deref(), |
| 817 | disallowed_tools.as_deref(), |
| 818 | &tool.name, |
| 819 | )) |
| 820 | }); |
| 821 | for tool in &mut catalog { |
| 822 | if let Some(actions) = tool |
| 823 | .input_schema |
| 824 | .pointer_mut("/properties/action/enum") |
| 825 | .and_then(Value::as_array_mut) |
| 826 | { |
| 827 | actions.retain(|action| { |
| 828 | !tool_call_denied_for( |
| 829 | disallowed_tools.as_deref(), |
| 830 | &tool.name, |
| 831 | &json!({"action": action}), |
| 832 | holds_bounded_verification, |
| 833 | ) |
| 834 | }); |
| 835 | } |
| 836 | } |
| 837 | catalog.retain(|tool| { |
| 838 | tool.input_schema |
| 839 | .pointer("/properties/action/enum") |
| 840 | .and_then(Value::as_array) |
| 841 | .is_none_or(|actions| !actions.is_empty()) |
| 842 | }); |
| 843 | if let Some(allowed) = allowed_tools.as_deref() { |
| 844 | let mut exact = HashSet::new(); |
| 845 | extend_always_load_from_exact_rules(&mut exact, allowed); |
| 846 | if !exact.is_empty() { |
| 847 | for tool in &mut catalog { |
| 848 | if always_load_matches(&exact, &tool.name) { |
| 849 | tool.defer_loading = Some(false); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | } |
| 854 | settle_discovery_surface(&mut catalog, false, had_cache_control); |
| 855 | let mut active_names = initial_active_tools(&catalog); |
| 856 | active_names.retain(|name| catalog.iter().any(|tool| tool.name == *name)); |
| 857 | let active = active_tools_for_request( |
| 858 | &mode_visible_catalog(&catalog, mode), |
| 859 | &active_names, |
| 860 | strict_tool_mode, |
| 861 | ); |
| 862 | |
| 863 | Self { |
| 864 | registry, |
| 865 | catalog, |
| 866 | active_names, |
| 867 | active, |
| 868 | mode, |
| 869 | strict_tool_mode, |
| 870 | allowed_tools, |
| 871 | disallowed_tools, |
| 872 | holds_bounded_verification, |
| 873 | extension_tool_names: HashSet::new(), |
| 874 | max_tool_calls, |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | pub(super) fn with_extension_tool_names(mut self, names: HashSet<String>) -> Self { |
| 879 | self.extension_tool_names = names; |
| 880 | self |
| 881 | } |
| 882 | |
| 883 | pub(super) fn allows_tool(&self, name: &str) -> bool { |
| 884 | !self.denies_tool(name) && self.passes_allow_list(name) |
| 885 | } |
| 886 | |
| 887 | pub(super) fn passes_allow_list(&self, name: &str) -> bool { |
| 888 | tool_allowed(self.allowed_tools.as_deref(), name) |
| 889 | || retrieval_available_beside_an_allowlist( |
| 890 | self.allowed_tools.as_deref(), |
| 891 | self.disallowed_tools.as_deref(), |
| 892 | name, |
| 893 | ) |
| 894 | } |
| 895 | |
| 896 | /// A configured-server handshake may only serve this captured turn's |
| 897 | /// MCP namespace. Do not replace the command-scoped ceiling with config. |
| 898 | pub(super) fn mcp_discovery_filter(&self) -> impl Fn(&str) -> bool + Send + 'static + use<> { |
| 899 | let denied = self.disallowed_tools.clone().unwrap_or_default(); |
| 900 | let allowed = self.allowed_tools.as_ref().map(|rules| { |
| 901 | rules |
| 902 | .iter() |
| 903 | .map(|rule| rule.to_ascii_lowercase()) |
| 904 | .collect::<Vec<_>>() |
| 905 | }); |
| 906 | move |server| { |
| 907 | !crate::mcp::McpPool::server_denied_by(&denied, server) |
| 908 | && allowed |
| 909 | .as_ref() |
| 910 | .is_none_or(|rules| crate::mcp::tool_selection_covers_server(rules, server)) |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | pub(super) fn denies_tool(&self, name: &str) -> bool { |
| 915 | tool_denied(self.disallowed_tools.as_deref(), name) |
| 916 | } |
| 917 | |
| 918 | pub(super) fn denies_call(&self, name: &str, input: &Value) -> bool { |
| 919 | tool_call_denied_for( |
| 920 | self.disallowed_tools.as_deref(), |
| 921 | name, |
| 922 | input, |
| 923 | self.holds_bounded_verification, |
| 924 | ) |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | pub(super) fn tool_allowed(allowed_tools: Option<&[String]>, tool_name: &str) -> bool { |
| 929 | let Some(allowed_tools) = allowed_tools else { |
| 930 | return true; |
| 931 | }; |
| 932 | tool_matches_any_rule(allowed_tools, tool_name) |
| 933 | } |
| 934 | |
| 935 | /// Retrieval stays off the initial `tools` field but must survive an allow-list |
| 936 | /// narrowing, or a result that names a saved copy advertises a route the turn |
| 937 | /// cannot call. |
| 938 | /// |
| 939 | /// This is deliberately not a branch inside [`tool_allowed`]: that answer is |
| 940 | /// "does this name match the allow-list", and an empty allow-list means no |
| 941 | /// tools, which `exec` relies on. Keeping the tool in the catalog lets |
| 942 | /// [`activate_result_dependencies`] admit it later, only after a result really |
| 943 | /// publishes retrievable evidence, and an explicit deny still removes it. |
| 944 | fn retrieval_available_beside_an_allowlist( |
| 945 | allowed_tools: Option<&[String]>, |
| 946 | disallowed_tools: Option<&[String]>, |
| 947 | tool_name: &str, |
| 948 | ) -> bool { |
| 949 | tool_name == TOOL_RESULT_RETRIEVAL_NAME |
| 950 | && disallowed_tools.is_none_or(|rules| !tool_denied(Some(rules), tool_name)) |
| 951 | && allowed_tools.is_some_and(|rules| !rules.is_empty()) |
| 952 | } |
| 953 | |
| 954 | /// Whether an explicit tool allowlist is provably limited to the native file |
| 955 | /// and shell primitives. Unknown names and wildcards remain conservative |
| 956 | /// because a configured MCP server may own them. |
| 957 | pub fn allowlist_is_native_file_and_shell_only(allowed_tools: Option<&[String]>) -> bool { |
| 958 | let Some(rules) = allowed_tools else { |
| 959 | return false; |
| 960 | }; |
| 961 | const NATIVE_NAMES: &[&str] = &[ |
| 962 | "bash", |
| 963 | "exec_shell", |
| 964 | "read", |
| 965 | "read_file", |
| 966 | "write", |
| 967 | "write_file", |
| 968 | "edit", |
| 969 | "edit_file", |
| 970 | "file", |
| 971 | ]; |
| 972 | rules.iter().all(|rule| { |
| 973 | let rule = rule.trim(); |
| 974 | !rule.is_empty() |
| 975 | && !rule.ends_with('*') |
| 976 | && NATIVE_NAMES.contains(&rule.to_ascii_lowercase().as_str()) |
| 977 | }) |
| 978 | } |
| 979 | |
| 980 | pub(super) fn mode_visible_catalog( |
| 981 | catalog: &[Tool], |
| 982 | mode: AppMode, |
| 983 | ) -> std::borrow::Cow<'_, [Tool]> { |
| 984 | if mode != AppMode::Plan { |
| 985 | return std::borrow::Cow::Borrowed(catalog); |
| 986 | } |
| 987 | let visible: Vec<_> = catalog |
| 988 | .iter() |
| 989 | .filter(|tool| { |
| 990 | !is_shell_tool_name(&tool.name) |
| 991 | && !super::turn_loop::mode_blocks_command_execution(mode, &tool.name) |
| 992 | }) |
| 993 | .cloned() |
| 994 | .collect(); |
| 995 | std::borrow::Cow::Owned(visible) |
| 996 | } |
| 997 | |
| 998 | /// The `tools` field of one outbound request, from a catalog and the set of |
| 999 | /// currently-active tool names. |
| 1000 | /// |
| 1001 | /// Shared by [`ToolSurfacePolicy`] and the per-step rebuild inside the turn |
| 1002 | /// loop, so activating a deferred tool mid-turn goes through one code path. |
| 1003 | pub fn active_tools_for_request( |
| 1004 | catalog: &[Tool], |
| 1005 | active: &HashSet<String>, |
| 1006 | strict_tool_mode: bool, |
| 1007 | ) -> Option<Vec<Tool>> { |
| 1008 | if catalog.is_empty() { |
| 1009 | return None; |
| 1010 | } |
| 1011 | let mut tools = active_tools_for_step(catalog, active); |
| 1012 | if strict_tool_mode { |
| 1013 | prepare_tools_for_strict_mode(&mut tools); |
| 1014 | } |
| 1015 | Some(tools) |
| 1016 | } |
| 1017 | |
| 1018 | pub fn default_tool_choice(strict_tool_mode: bool) -> Value { |
| 1019 | if strict_tool_mode { |
| 1020 | json!("required") |
| 1021 | } else { |
| 1022 | json!({"type": "auto"}) |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | pub fn measure_deferred_tools( |
| 1027 | client: &dyn crate::core::model_client::ModelClient, |
| 1028 | model: &str, |
| 1029 | reasoning_effort: Option<&str>, |
| 1030 | strict_tool_mode: bool, |
| 1031 | catalog: &[Tool], |
| 1032 | names: &[String], |
| 1033 | ) -> Result<crate::core::session::ToolActivationMeasurement, ToolError> { |
| 1034 | let eager = catalog |
| 1035 | .iter() |
| 1036 | .filter(|tool| !tool.defer_loading.unwrap_or(false)) |
| 1037 | .map(|tool| tool.name.clone()) |
| 1038 | .collect::<HashSet<_>>(); |
| 1039 | let prepare = |active: &HashSet<String>| { |
| 1040 | let tools = active_tools_for_request(catalog, active, strict_tool_mode); |
| 1041 | let tool_choice = tools |
| 1042 | .as_ref() |
| 1043 | .map(|_| default_tool_choice(strict_tool_mode)); |
| 1044 | codewhale_core::request::prepare_primary_turn_request( |
| 1045 | codewhale_core::request::PrimaryTurnRequest { |
| 1046 | model: model.to_string(), |
| 1047 | messages: Vec::new(), |
| 1048 | max_tokens: client.effective_max_output_tokens(model), |
| 1049 | system: None, |
| 1050 | tools, |
| 1051 | tool_choice, |
| 1052 | reasoning_effort: reasoning_effort.map(str::to_string), |
| 1053 | }, |
| 1054 | ) |
| 1055 | }; |
| 1056 | let baseline = client |
| 1057 | .measure_outbound_tools(prepare(&eager)) |
| 1058 | .map_err(|_| { |
| 1059 | ToolError::not_available( |
| 1060 | "Unable to measure the provider tool surface; toolbox admission was not changed", |
| 1061 | ) |
| 1062 | })?; |
| 1063 | let mut active = eager; |
| 1064 | active.extend(names.iter().cloned()); |
| 1065 | let measured = client |
| 1066 | .measure_outbound_tools(prepare(&active)) |
| 1067 | .map_err(|_| { |
| 1068 | ToolError::not_available( |
| 1069 | "Unable to measure the provider tool surface; toolbox admission was not changed", |
| 1070 | ) |
| 1071 | })?; |
| 1072 | Ok(crate::core::session::ToolActivationMeasurement { |
| 1073 | schema_bytes: baseline |
| 1074 | .as_ref() |
| 1075 | .zip(measured.as_ref()) |
| 1076 | .map(|(base, all)| all.tool_schema_bytes.saturating_sub(base.tool_schema_bytes)), |
| 1077 | unavailable: measured.map_or_else(Vec::new, |wire| { |
| 1078 | names |
| 1079 | .iter() |
| 1080 | .filter(|name| { |
| 1081 | wire.omitted_tool_names.iter().any(|omitted| { |
| 1082 | omitted == *name |
| 1083 | || crate::client::wire::from_api_tool_name(omitted) == **name |
| 1084 | }) |
| 1085 | }) |
| 1086 | .cloned() |
| 1087 | .collect() |
| 1088 | }), |
| 1089 | }) |
| 1090 | } |
| 1091 | |
| 1092 | /// Reusable scratch for one `tool_search` catalog scan. |
| 1093 | /// |
| 1094 | /// Each deferred tool needs a lowercased `name\ndescription\ninput_schema` blob |
| 1095 | /// that is compared once and dropped. Building it with `format!` also copied all |
| 1096 | /// three pieces a second time into the concatenation, and the bm25 scorer then |
| 1097 | /// re-lowered `tool.name` once per query term for a value that does not vary |
| 1098 | /// across terms. Reusing one set of buffers across the scan removes the |
| 1099 | /// concatenation copy and the per-term lowering, and keeps the buffers' capacity |
| 1100 | /// instead of reallocating per tool (#6213 T5). |
| 1101 | /// |
| 1102 | /// This is the same precomputed-index idiom `CachedFallback` already uses for |
| 1103 | /// the static core-action fallbacks in this file; it is not a new pattern. |
| 1104 | /// |
| 1105 | /// Lowercasing deliberately stays `str::to_lowercase`, matching the original |
| 1106 | /// exactly. A per-`char` fold would allocate less but is not the same function — |
| 1107 | /// it differs on Greek final sigma — and this path runs a handful of times per |
| 1108 | /// turn beside a multi-second provider call, so it is not worth a semantic |
| 1109 | /// change. |
| 1110 | #[derive(Default)] |
| 1111 | struct ToolSearchScratch { |
| 1112 | /// `tool.name`, lowercased. Loop-invariant across query terms, so the bm25 |
| 1113 | /// scorer reads this instead of re-lowering the name once per term. |
| 1114 | name_lower: String, |
| 1115 | name_tokens: Vec<String>, |
| 1116 | /// Compact JSON of `tool.input_schema`, before lowercasing. |
| 1117 | schema_json: String, |
| 1118 | /// The match target: `name\ndescription\nschema`, all lowercased. |
| 1119 | hay: String, |
| 1120 | hay_tokens: HashSet<String>, |
| 1121 | } |
| 1122 | |
| 1123 | impl ToolSearchScratch { |
| 1124 | fn load(&mut self, tool: &Tool) { |
| 1125 | use std::fmt::Write as _; |
| 1126 | |
| 1127 | self.name_lower.clear(); |
| 1128 | self.name_lower.push_str(&tool.name.to_lowercase()); |
| 1129 | self.name_tokens = split_identifier_tokens(&tool.name); |
| 1130 | |
| 1131 | self.schema_json.clear(); |
| 1132 | // `Value`'s `Display` is what `to_string()` calls, so this is the same |
| 1133 | // text without materializing an owned copy first. Infallible for a |
| 1134 | // `String` sink; a formatting error could only shorten the schema, |
| 1135 | // which weakens matching and never breaks correctness. |
| 1136 | let _ = write!(self.schema_json, "{}", tool.input_schema); |
| 1137 | |
| 1138 | self.hay.clear(); |
| 1139 | self.hay.push_str(&self.name_lower); |
| 1140 | self.hay.push('\n'); |
| 1141 | self.hay.push_str(&tool.description.to_lowercase()); |
| 1142 | self.hay.push('\n'); |
| 1143 | self.hay.push_str(&self.schema_json.to_lowercase()); |
| 1144 | |
| 1145 | self.hay_tokens.clear(); |
| 1146 | self.hay_tokens.extend(self.name_tokens.iter().cloned()); |
| 1147 | self.hay_tokens |
| 1148 | .extend(split_identifier_tokens(&tool.description)); |
| 1149 | self.hay_tokens |
| 1150 | .extend(split_identifier_tokens(&self.schema_json)); |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | pub(crate) fn split_identifier_tokens(text: &str) -> Vec<String> { |
| 1155 | let mut tokens = Vec::new(); |
| 1156 | let chars: Vec<char> = text.chars().collect(); |
| 1157 | let mut start: Option<usize> = None; |
| 1158 | let flush = |slice: &[char], out: &mut Vec<String>| { |
| 1159 | if slice.is_empty() { |
| 1160 | return; |
| 1161 | } |
| 1162 | let token: String = slice.iter().collect::<String>().to_lowercase(); |
| 1163 | if !token.is_empty() { |
| 1164 | out.push(token); |
| 1165 | } |
| 1166 | }; |
| 1167 | for i in 0..chars.len() { |
| 1168 | let ch = chars[i]; |
| 1169 | if !ch.is_alphanumeric() { |
| 1170 | if let Some(s) = start.take() { |
| 1171 | flush(&chars[s..i], &mut tokens); |
| 1172 | } |
| 1173 | continue; |
| 1174 | } |
| 1175 | if let Some(s) = start { |
| 1176 | let prev = chars[i - 1]; |
| 1177 | let next = chars.get(i + 1).copied(); |
| 1178 | let camel_boundary = (prev.is_lowercase() && ch.is_uppercase()) |
| 1179 | || (prev.is_uppercase() |
| 1180 | && ch.is_uppercase() |
| 1181 | && next.is_some_and(char::is_lowercase)) |
| 1182 | || (prev.is_ascii_digit() && ch.is_alphabetic()) |
| 1183 | || (prev.is_alphabetic() && ch.is_ascii_digit()); |
| 1184 | if camel_boundary { |
| 1185 | flush(&chars[s..i], &mut tokens); |
| 1186 | start = Some(i); |
| 1187 | } |
| 1188 | } else { |
| 1189 | start = Some(i); |
| 1190 | } |
| 1191 | } |
| 1192 | if let Some(s) = start { |
| 1193 | flush(&chars[s..], &mut tokens); |
| 1194 | } |
| 1195 | tokens |
| 1196 | } |
| 1197 | |
| 1198 | fn token_matches(token: &str, term: &str) -> bool { |
| 1199 | token == term |
| 1200 | || (term.len() >= 3 && token.strip_suffix('s') == Some(term)) |
| 1201 | || (token.len() >= 3 && term.strip_suffix('s') == Some(token)) |
| 1202 | } |
| 1203 | |
| 1204 | fn compile_tool_search_regex(query: &str) -> Result<regex::Regex, ToolError> { |
| 1205 | compile_user_regex_case_insensitive(query) |
| 1206 | .map_err(|err| ToolError::invalid_input(format!("Invalid regex query: {err}"))) |
| 1207 | } |
| 1208 | |
| 1209 | fn catalog_contains_tool(catalog: &[Tool], name: &str) -> bool { |
| 1210 | catalog.iter().any(|tool| tool.name == name) |
| 1211 | } |
| 1212 | |
| 1213 | fn unavailable_core_action_tools_with_regex( |
| 1214 | catalog: &[Tool], |
| 1215 | query: &str, |
| 1216 | max_results: usize, |
| 1217 | ) -> Result<Vec<CoreActionToolFallback>, ToolError> { |
| 1218 | if max_results == 0 { |
| 1219 | return Ok(Vec::new()); |
| 1220 | } |
| 1221 | let regex = compile_tool_search_regex(query)?; |
| 1222 | Ok(cached_fallbacks() |
| 1223 | .iter() |
| 1224 | .filter(|cf| !catalog_contains_tool(catalog, cf.fallback.name)) |
| 1225 | .filter(|cf| regex.is_match(&cf.name_lower) || regex.is_match(&cf.haystack)) |
| 1226 | .take(max_results) |
| 1227 | .map(|cf| cf.fallback) |
| 1228 | .collect()) |
| 1229 | } |
| 1230 | |
| 1231 | fn unavailable_core_action_tools_with_bm25_like( |
| 1232 | catalog: &[Tool], |
| 1233 | query: &str, |
| 1234 | max_results: usize, |
| 1235 | ) -> Vec<CoreActionToolFallback> { |
| 1236 | if max_results == 0 { |
| 1237 | return Vec::new(); |
| 1238 | } |
| 1239 | let terms: Vec<String> = query |
| 1240 | .split_whitespace() |
| 1241 | .map(|term| term.trim().to_lowercase()) |
| 1242 | .filter(|term| !term.is_empty()) |
| 1243 | .collect(); |
| 1244 | if terms.is_empty() { |
| 1245 | return Vec::new(); |
| 1246 | } |
| 1247 | |
| 1248 | let mut scored: Vec<(i64, CoreActionToolFallback)> = Vec::new(); |
| 1249 | for cf in cached_fallbacks() { |
| 1250 | if catalog_contains_tool(catalog, cf.fallback.name) { |
| 1251 | continue; |
| 1252 | } |
| 1253 | let hay = &cf.haystack; |
| 1254 | let name = &cf.name_lower; |
| 1255 | let mut score = 0i64; |
| 1256 | for term in &terms { |
| 1257 | if hay.contains(term) { |
| 1258 | score += 1; |
| 1259 | } |
| 1260 | if name.contains(term) { |
| 1261 | score += 2; |
| 1262 | } |
| 1263 | } |
| 1264 | if score > 0 { |
| 1265 | scored.push((score, cf.fallback)); |
| 1266 | } |
| 1267 | } |
| 1268 | scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(b.1.name))); |
| 1269 | scored |
| 1270 | .into_iter() |
| 1271 | .take(max_results) |
| 1272 | .map(|(_, fallback)| fallback) |
| 1273 | .collect() |
| 1274 | } |
| 1275 | |
| 1276 | fn is_eager_wire_tool( |
| 1277 | tool: &Tool, |
| 1278 | active_tools: &HashSet<String>, |
| 1279 | cache: Option<&ToolActivationCache>, |
| 1280 | ) -> bool { |
| 1281 | !tool.defer_loading.unwrap_or(false) |
| 1282 | || (active_tools.contains(&tool.name) |
| 1283 | && cache.is_some_and(|cache| !cache.names().any(|cached| cached == tool.name))) |
| 1284 | } |
| 1285 | |
| 1286 | fn discover_tools_with_regex( |
| 1287 | catalog: &[Tool], |
| 1288 | query: &str, |
| 1289 | max_results: usize, |
| 1290 | active_tools: &HashSet<String>, |
| 1291 | cache: Option<&ToolActivationCache>, |
| 1292 | ) -> Result<Vec<String>, ToolError> { |
| 1293 | discover_tools_with_regex_in( |
| 1294 | catalog |
| 1295 | .iter() |
| 1296 | .filter(|tool| !is_eager_wire_tool(tool, active_tools, cache)), |
| 1297 | query, |
| 1298 | max_results, |
| 1299 | ) |
| 1300 | } |
| 1301 | |
| 1302 | fn discover_tools_with_regex_in<'a>( |
| 1303 | tools: impl Iterator<Item = &'a Tool>, |
| 1304 | query: &str, |
| 1305 | max_results: usize, |
| 1306 | ) -> Result<Vec<String>, ToolError> { |
| 1307 | let regex = compile_tool_search_regex(query)?; |
| 1308 | |
| 1309 | let mut matches = Vec::new(); |
| 1310 | let mut scratch = ToolSearchScratch::default(); |
| 1311 | for tool in tools { |
| 1312 | scratch.load(tool); |
| 1313 | if regex.is_match(&scratch.name_lower) || regex.is_match(&scratch.hay) { |
| 1314 | matches.push(tool.name.clone()); |
| 1315 | } |
| 1316 | if matches.len() >= max_results { |
| 1317 | break; |
| 1318 | } |
| 1319 | } |
| 1320 | Ok(matches) |
| 1321 | } |
| 1322 | |
| 1323 | const TOOL_SEARCH_SYNONYM_GROUPS: &[(&[&str], &[&str])] = &[ |
| 1324 | ( |
| 1325 | &[ |
| 1326 | "pdf", |
| 1327 | "image", |
| 1328 | "images", |
| 1329 | "screenshot", |
| 1330 | "screenshots", |
| 1331 | "photo", |
| 1332 | "picture", |
| 1333 | "audio", |
| 1334 | "video", |
| 1335 | "media", |
| 1336 | ], |
| 1337 | &["read", "read_media", "media"], |
| 1338 | ), |
| 1339 | ( |
| 1340 | &[ |
| 1341 | "git", "diff", "commit", "branch", "blame", "status", "stash", "merge", "log", |
| 1342 | ], |
| 1343 | &["git"], |
| 1344 | ), |
| 1345 | ( |
| 1346 | &[ |
| 1347 | "test", "tests", "lint", "check", "build", "verify", "verifier", "cargo", "pytest", |
| 1348 | ], |
| 1349 | &["run", "verify", "run_tests"], |
| 1350 | ), |
| 1351 | ( |
| 1352 | &[ |
| 1353 | "shell", |
| 1354 | "pty", |
| 1355 | "terminal", |
| 1356 | "tty", |
| 1357 | "bg", |
| 1358 | "background", |
| 1359 | "interactive", |
| 1360 | "process", |
| 1361 | ], |
| 1362 | &[ |
| 1363 | "bash", |
| 1364 | "terminal_run", |
| 1365 | "terminal_wait", |
| 1366 | "terminal_send", |
| 1367 | "terminal_cancel", |
| 1368 | "task_shell_wait", |
| 1369 | ], |
| 1370 | ), |
| 1371 | ( |
| 1372 | &[ |
| 1373 | "subagent", "delegate", "worker", "spawn", "child", "parallel", |
| 1374 | ], |
| 1375 | &["agent", "workflow"], |
| 1376 | ), |
| 1377 | ( |
| 1378 | &["memory", "note", "notes", "remember", "recall", "save"], |
| 1379 | &["remember", "memory_search"], |
| 1380 | ), |
| 1381 | ( |
| 1382 | &[ |
| 1383 | "web", "url", "http", "https", "fetch", "browse", "internet", "search", |
| 1384 | ], |
| 1385 | &["web", "web.run", "fetch_url", "web_search"], |
| 1386 | ), |
| 1387 | ( |
| 1388 | &[ |
| 1389 | "lsp", |
| 1390 | "definition", |
| 1391 | "references", |
| 1392 | "diagnostics", |
| 1393 | "symbol", |
| 1394 | "symbols", |
| 1395 | "hover", |
| 1396 | "typecheck", |
| 1397 | ], |
| 1398 | &["lsp"], |
| 1399 | ), |
| 1400 | ( |
| 1401 | &["todo", "checklist", "plan", "task", "tasks"], |
| 1402 | &["todo_write", "tasks"], |
| 1403 | ), |
| 1404 | ]; |
| 1405 | |
| 1406 | fn expand_bm25_synonyms(terms: &[String]) -> Vec<&'static str> { |
| 1407 | let mut expanded = Vec::new(); |
| 1408 | for term in terms { |
| 1409 | let normalized = term.trim_matches(|c: char| !c.is_alphanumeric() && c != '_' && c != '.'); |
| 1410 | if normalized.is_empty() { |
| 1411 | continue; |
| 1412 | } |
| 1413 | for (triggers, targets) in TOOL_SEARCH_SYNONYM_GROUPS { |
| 1414 | if triggers.contains(&normalized) { |
| 1415 | for target in *targets { |
| 1416 | if !terms.iter().any(|existing| existing == target) |
| 1417 | && !expanded.contains(target) |
| 1418 | { |
| 1419 | expanded.push(*target); |
| 1420 | } |
| 1421 | } |
| 1422 | } |
| 1423 | } |
| 1424 | } |
| 1425 | expanded |
| 1426 | } |
| 1427 | |
| 1428 | fn name_has_token(name_lower: &str, token: &str) -> bool { |
| 1429 | name_lower |
| 1430 | .split(['_', '-', '.', '/', ':']) |
| 1431 | .any(|part| part == token) |
| 1432 | } |
| 1433 | |
| 1434 | fn collect_query_terms(query: &str) -> Vec<String> { |
| 1435 | let mut terms = Vec::new(); |
| 1436 | for raw in query.split_whitespace() { |
| 1437 | let lower = raw.trim().to_lowercase(); |
| 1438 | if !lower.is_empty() && !terms.contains(&lower) { |
| 1439 | terms.push(lower); |
| 1440 | } |
| 1441 | for tok in split_identifier_tokens(raw) { |
| 1442 | if !terms.contains(&tok) { |
| 1443 | terms.push(tok); |
| 1444 | } |
| 1445 | } |
| 1446 | } |
| 1447 | terms |
| 1448 | } |
| 1449 | |
| 1450 | fn discover_tools_with_bm25_like_in<'a>( |
| 1451 | tools: impl Iterator<Item = &'a Tool>, |
| 1452 | query: &str, |
| 1453 | max_results: usize, |
| 1454 | ) -> Vec<String> { |
| 1455 | let terms = collect_query_terms(query); |
| 1456 | if terms.is_empty() { |
| 1457 | return Vec::new(); |
| 1458 | } |
| 1459 | |
| 1460 | let synonym_targets = expand_bm25_synonyms(&terms); |
| 1461 | let mut scored: Vec<(i64, String)> = Vec::new(); |
| 1462 | let mut scratch = ToolSearchScratch::default(); |
| 1463 | for tool in tools { |
| 1464 | scratch.load(tool); |
| 1465 | let body_weight = if crate::mcp::McpPool::is_mcp_tool(&tool.name) { |
| 1466 | 3 |
| 1467 | } else { |
| 1468 | 10 |
| 1469 | }; |
| 1470 | let mut score = 0i64; |
| 1471 | for term in &terms { |
| 1472 | // Loop-invariant: lowered once by `load`, not once per term. |
| 1473 | if scratch.name_lower == *term { |
| 1474 | score += 40; |
| 1475 | } else if scratch |
| 1476 | .name_tokens |
| 1477 | .iter() |
| 1478 | .any(|tok| token_matches(tok, term)) |
| 1479 | { |
| 1480 | score += 25; |
| 1481 | } else if term.len() >= 3 && scratch.name_lower.contains(term) { |
| 1482 | score += 12; |
| 1483 | } |
| 1484 | if scratch |
| 1485 | .hay_tokens |
| 1486 | .iter() |
| 1487 | .any(|tok| token_matches(tok, term)) |
| 1488 | { |
| 1489 | score += body_weight; |
| 1490 | } else if term.len() >= 3 && scratch.hay.contains(term) { |
| 1491 | score += (body_weight / 2).max(1); |
| 1492 | } |
| 1493 | } |
| 1494 | for target in &synonym_targets { |
| 1495 | if scratch.name_lower == *target { |
| 1496 | score += 12; |
| 1497 | } else if scratch |
| 1498 | .name_tokens |
| 1499 | .iter() |
| 1500 | .any(|tok| token_matches(tok, target)) |
| 1501 | || name_has_token(&scratch.name_lower, target) |
| 1502 | { |
| 1503 | score += 5; |
| 1504 | } |
| 1505 | } |
| 1506 | if score > 0 { |
| 1507 | scored.push((score, tool.name.clone())); |
| 1508 | } |
| 1509 | } |
| 1510 | scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); |
| 1511 | let floor = scored.first().map_or(0, |(top, _)| top / 4); |
| 1512 | scored |
| 1513 | .into_iter() |
| 1514 | .take_while(|(score, _)| *score >= floor) |
| 1515 | .take(max_results) |
| 1516 | .map(|(_, name)| name) |
| 1517 | .collect() |
| 1518 | } |
| 1519 | |
| 1520 | fn discover_tools_with_bm25_like( |
| 1521 | catalog: &[Tool], |
| 1522 | query: &str, |
| 1523 | max_results: usize, |
| 1524 | active_tools: &HashSet<String>, |
| 1525 | cache: Option<&ToolActivationCache>, |
| 1526 | ) -> Vec<String> { |
| 1527 | discover_tools_with_bm25_like_in( |
| 1528 | catalog |
| 1529 | .iter() |
| 1530 | .filter(|tool| !is_eager_wire_tool(tool, active_tools, cache)), |
| 1531 | query, |
| 1532 | max_results, |
| 1533 | ) |
| 1534 | } |
| 1535 | |
| 1536 | pub(crate) fn suggest_tools_for_codemode( |
| 1537 | catalog: &[Tool], |
| 1538 | requested: &str, |
| 1539 | limit: usize, |
| 1540 | ) -> Vec<String> { |
| 1541 | const GENERIC_TOKENS: &[&str] = &[ |
| 1542 | "a", "an", "and", "for", "get", "in", "is", "mcp", "not", "of", "on", "or", "run", "set", |
| 1543 | "the", "to", "tool", "tools", "use", |
| 1544 | ]; |
| 1545 | let trimmed = requested.trim(); |
| 1546 | let requested_lower = trimmed.to_ascii_lowercase(); |
| 1547 | if requested_lower.is_empty() || limit == 0 { |
| 1548 | return Vec::new(); |
| 1549 | } |
| 1550 | let query_tokens = split_identifier_tokens(trimmed); |
| 1551 | let informative_tokens: Vec<&String> = query_tokens |
| 1552 | .iter() |
| 1553 | .filter(|tok| !GENERIC_TOKENS.contains(&tok.as_str())) |
| 1554 | .collect(); |
| 1555 | let only_generic = informative_tokens.is_empty(); |
| 1556 | let active_tokens: Vec<&String> = if only_generic { |
| 1557 | query_tokens.iter().collect() |
| 1558 | } else { |
| 1559 | informative_tokens |
| 1560 | }; |
| 1561 | let mut scored: Vec<(i64, usize, String)> = Vec::new(); |
| 1562 | for tool in catalog { |
| 1563 | if !discoverable_in_program(tool) { |
| 1564 | continue; |
| 1565 | } |
| 1566 | let candidate = tool.name.to_ascii_lowercase(); |
| 1567 | let candidate_tokens = split_identifier_tokens(&tool.name); |
| 1568 | let mut overlap = 0i64; |
| 1569 | let mut matched_tokens = 0usize; |
| 1570 | for q in &active_tokens { |
| 1571 | if candidate_tokens.iter().any(|tok| token_matches(tok, q)) { |
| 1572 | overlap += 20; |
| 1573 | matched_tokens += 1; |
| 1574 | } else if q.len() >= 4 && candidate.contains(q.as_str()) { |
| 1575 | overlap += 8; |
| 1576 | matched_tokens += 1; |
| 1577 | } |
| 1578 | } |
| 1579 | let min_substr = requested_lower.len() >= 3 && candidate.len() >= 3; |
| 1580 | let prefix_match = min_substr |
| 1581 | && (candidate.starts_with(&requested_lower) || requested_lower.starts_with(&candidate)); |
| 1582 | let contains_match = min_substr |
| 1583 | && (candidate.contains(&requested_lower) || requested_lower.contains(&candidate)); |
| 1584 | let distance = codewhale_config::suggest::edit_distance(&candidate, &requested_lower); |
| 1585 | let max_len = requested_lower.len().max(candidate.len()); |
| 1586 | let close_typo = distance <= 3 && distance.saturating_mul(2) <= max_len; |
| 1587 | let enough_token_overlap = if only_generic { |
| 1588 | matched_tokens >= 2 && matched_tokens == active_tokens.len() |
| 1589 | } else { |
| 1590 | matched_tokens > 0 |
| 1591 | && (active_tokens.len() <= 1 |
| 1592 | || matched_tokens >= 2 |
| 1593 | || matched_tokens.saturating_mul(2) >= active_tokens.len()) |
| 1594 | }; |
| 1595 | if !enough_token_overlap && !prefix_match && !contains_match && !close_typo { |
| 1596 | continue; |
| 1597 | } |
| 1598 | let mut score = overlap; |
| 1599 | if prefix_match { |
| 1600 | score += 25; |
| 1601 | } |
| 1602 | if contains_match { |
| 1603 | score += 15; |
| 1604 | } |
| 1605 | if close_typo { |
| 1606 | score += (4 - distance as i64) * 5; |
| 1607 | } |
| 1608 | scored.push((score, distance, tool.name.clone())); |
| 1609 | } |
| 1610 | scored.sort_by(|a, b| { |
| 1611 | b.0.cmp(&a.0) |
| 1612 | .then_with(|| a.1.cmp(&b.1)) |
| 1613 | .then_with(|| a.2.cmp(&b.2)) |
| 1614 | }); |
| 1615 | scored.dedup_by(|a, b| a.2 == b.2); |
| 1616 | if let Some(&(top_score, _, _)) = scored.first() |
| 1617 | && top_score >= 40 |
| 1618 | { |
| 1619 | scored.retain(|(score, _, _)| score.saturating_mul(2) > top_score); |
| 1620 | } |
| 1621 | scored |
| 1622 | .into_iter() |
| 1623 | .take(limit) |
| 1624 | .map(|(_, _, name)| name) |
| 1625 | .collect() |
| 1626 | } |
| 1627 | |
| 1628 | fn suggest_tool_names(catalog: &[Tool], requested: &str, limit: usize) -> Vec<String> { |
| 1629 | let requested = requested.trim().to_ascii_lowercase(); |
| 1630 | if requested.is_empty() || limit == 0 { |
| 1631 | return Vec::new(); |
| 1632 | } |
| 1633 | |
| 1634 | let mut candidates: Vec<(u8, usize, String)> = Vec::new(); |
| 1635 | for tool in catalog { |
| 1636 | let candidate = tool.name.to_ascii_lowercase(); |
| 1637 | let prefix_match = candidate.starts_with(&requested) || requested.starts_with(&candidate); |
| 1638 | let contains_match = candidate.contains(&requested) || requested.contains(&candidate); |
| 1639 | let distance = codewhale_config::suggest::edit_distance(&candidate, &requested); |
| 1640 | let close_typo = distance <= 3; |
| 1641 | |
| 1642 | if !(prefix_match || contains_match || close_typo) { |
| 1643 | continue; |
| 1644 | } |
| 1645 | |
| 1646 | let rank = if prefix_match { |
| 1647 | 0 |
| 1648 | } else if contains_match { |
| 1649 | 1 |
| 1650 | } else { |
| 1651 | 2 |
| 1652 | }; |
| 1653 | candidates.push((rank, distance, tool.name.clone())); |
| 1654 | } |
| 1655 | |
| 1656 | candidates.sort_by(|a, b| { |
| 1657 | a.0.cmp(&b.0) |
| 1658 | .then_with(|| a.1.cmp(&b.1)) |
| 1659 | .then_with(|| a.2.cmp(&b.2)) |
| 1660 | }); |
| 1661 | candidates.dedup_by(|a, b| a.2 == b.2); |
| 1662 | candidates |
| 1663 | .into_iter() |
| 1664 | .take(limit) |
| 1665 | .map(|(_, _, name)| name) |
| 1666 | .collect() |
| 1667 | } |
| 1668 | |
| 1669 | /// Catalog tools the engine injects itself rather than registering, plus the |
| 1670 | /// legacy tool-search spellings. Exposed so the read-only request projection |
| 1671 | /// can label their provenance as `synthetic` from the same source of truth as |
| 1672 | /// `is_synthetic_catalog_tool` test coverage instead of guessing. |
| 1673 | /// |
| 1674 | /// MCP-contributed names are deliberately *not* here: those resolve through the |
| 1675 | /// real pool, and stay unknown when the pool did not resolve them. |
| 1676 | /// `multi_tool_use.parallel` is not here either — it is a legacy name the model |
| 1677 | /// may emit, never a catalog entry, so it can never appear in a transmitted |
| 1678 | /// tool array and has no catalog provenance to report. |
| 1679 | pub(super) fn default_synthetic_catalog_tool_names() -> Vec<String> { |
| 1680 | let mut names: Vec<String> = vec![ |
| 1681 | TOOL_SEARCH_NAME.to_string(), |
| 1682 | CODE_EXECUTION_TOOL_NAME.to_string(), |
| 1683 | EXECUTE_TOOLS_TOOL_NAME.to_string(), |
| 1684 | ]; |
| 1685 | names.sort(); |
| 1686 | names.dedup(); |
| 1687 | names |
| 1688 | } |
| 1689 | |
| 1690 | #[cfg(test)] |
| 1691 | fn is_synthetic_catalog_tool(name: &str) -> bool { |
| 1692 | is_tool_search_tool(name) |
| 1693 | || matches!(name, CODE_EXECUTION_TOOL_NAME | EXECUTE_TOOLS_TOOL_NAME) |
| 1694 | || McpPool::is_mcp_tool(name) |
| 1695 | } |
| 1696 | |
| 1697 | #[cfg(test)] |
| 1698 | pub(super) fn tool_catalog_consistency_issues( |
| 1699 | catalog: &[Tool], |
| 1700 | registry: &crate::tools::ToolRegistry, |
| 1701 | ) -> Vec<String> { |
| 1702 | let catalog_names = catalog |
| 1703 | .iter() |
| 1704 | .map(|tool| tool.name.as_str()) |
| 1705 | .collect::<HashSet<_>>(); |
| 1706 | let registry_api_tools = registry.to_api_tools(); |
| 1707 | let registry_model_visible_names = registry_api_tools |
| 1708 | .iter() |
| 1709 | .map(|tool| tool.name.as_str()) |
| 1710 | .collect::<HashSet<_>>(); |
| 1711 | let mut issues = Vec::new(); |
| 1712 | |
| 1713 | for tool in catalog { |
| 1714 | if is_synthetic_catalog_tool(&tool.name) { |
| 1715 | continue; |
| 1716 | } |
| 1717 | if !registry.contains(&tool.name) { |
| 1718 | issues.push(format!( |
| 1719 | "catalog advertises '{}' but no registered handler exists", |
| 1720 | tool.name |
| 1721 | )); |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | for name in DEFAULT_ACTIVE_NATIVE_TOOLS { |
| 1726 | if registry_model_visible_names.contains(name) && !catalog_names.contains(name) { |
| 1727 | issues.push(format!( |
| 1728 | "registered core tool '{name}' is missing from the model/search catalog" |
| 1729 | )); |
| 1730 | } |
| 1731 | } |
| 1732 | |
| 1733 | issues.sort(); |
| 1734 | issues |
| 1735 | } |
| 1736 | |
| 1737 | pub(super) fn missing_tool_error_message(tool_name: &str, catalog: &[Tool]) -> String { |
| 1738 | // Dogfood A5 (#4092): models mid-checklist sometimes emit each list entry |
| 1739 | // as its own tool call named `item`/`todo`/... . Fuzzy suggestions are |
| 1740 | // actively misleading there ("Did you mean: note, tts?"); name the actual |
| 1741 | // fix instead. |
| 1742 | if matches!( |
| 1743 | tool_name, |
| 1744 | "item" | "items" | "todo" | "todos" | "checklist" | "checklist_item" | "plan_item" |
| 1745 | ) { |
| 1746 | return format!( |
| 1747 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1748 | Checklist entries are not separate tool calls — write the whole list \ |
| 1749 | in one `todo_write` call with a `todos` array of \ |
| 1750 | {{content, status}} objects." |
| 1751 | ); |
| 1752 | } |
| 1753 | let suggestions = suggest_tool_names(catalog, tool_name, 3); |
| 1754 | let shell_hint = if is_shell_tool_name(tool_name) { |
| 1755 | Some(shell_tool_allow_shell_hint()) |
| 1756 | } else { |
| 1757 | None |
| 1758 | }; |
| 1759 | // #5123-class: `exec_shell` was replaced by lowercase `bash`. Name it first — |
| 1760 | // otherwise the error misdiagnoses a retired-name call as an allow_shell |
| 1761 | // permission problem and sends the model fixing the wrong thing. |
| 1762 | if tool_name == "exec_shell" { |
| 1763 | return format!( |
| 1764 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1765 | `exec_shell` was replaced by `bash` — call `bash` with a `command` (or `background: true` for background jobs) instead. \ |
| 1766 | If `bash` is also absent: {shell_hint}.", |
| 1767 | shell_hint = shell_tool_allow_shell_hint() |
| 1768 | ); |
| 1769 | } |
| 1770 | let discovery = if composition_eager(catalog) { |
| 1771 | Some("tools.search in execute_tools") |
| 1772 | } else if catalog.iter().any(|tool| tool.name == TOOL_SEARCH_NAME) { |
| 1773 | Some(TOOL_SEARCH_NAME) |
| 1774 | } else { |
| 1775 | None |
| 1776 | }; |
| 1777 | if matches!( |
| 1778 | tool_name, |
| 1779 | "exec_shell_wait" | "exec_shell_interact" | "exec_shell_cancel" |
| 1780 | ) { |
| 1781 | let terminals = discovery.map_or_else(String::new, |discovery| { |
| 1782 | format!( |
| 1783 | ", or use {discovery} to discover persistent terminal controls (`{TERMINAL_RUN_NAME}`, `{TERMINAL_WAIT_NAME}`, `{TERMINAL_SEND_NAME}`, `{TERMINAL_CANCEL_NAME}`)" |
| 1784 | ) |
| 1785 | }); |
| 1786 | return format!( |
| 1787 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1788 | Use `bash` (with `background: true` for background work) and `task_shell_wait` for background jobs{terminals}." |
| 1789 | ); |
| 1790 | } |
| 1791 | let merged_into = match tool_name { |
| 1792 | "memory_get" => Some(("memory_search", "id")), |
| 1793 | "session_get" => Some(("session_search", "session_id")), |
| 1794 | "context_archive_get" => Some(("context_archive_search", "id")), |
| 1795 | _ => None, |
| 1796 | }; |
| 1797 | if let Some((replacement, argument)) = merged_into { |
| 1798 | return format!( |
| 1799 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1800 | `{tool_name}` was merged into `{replacement}`: call `{replacement}` with `{argument}` instead." |
| 1801 | ); |
| 1802 | } |
| 1803 | if suggestions.is_empty() { |
| 1804 | let search = discovery.map_or_else(String::new, |discovery| { |
| 1805 | format!(", or use {discovery} with a short query") |
| 1806 | }); |
| 1807 | if let Some(shell_hint) = shell_hint { |
| 1808 | return format!( |
| 1809 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1810 | {shell_hint}{search}." |
| 1811 | ); |
| 1812 | } |
| 1813 | return format!( |
| 1814 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1815 | Verify mode/feature flags{search}." |
| 1816 | ); |
| 1817 | } |
| 1818 | |
| 1819 | let suggestion_text = format!("Did you mean: {}?", suggestions.join(", ")); |
| 1820 | let search = discovery.map_or_else(String::new, |discovery| { |
| 1821 | format!(" You can also use {discovery} to discover tools.") |
| 1822 | }); |
| 1823 | if let Some(shell_hint) = shell_hint { |
| 1824 | return format!( |
| 1825 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1826 | {suggestion_text} {shell_hint}.{search}" |
| 1827 | ); |
| 1828 | } |
| 1829 | |
| 1830 | format!( |
| 1831 | "Tool '{tool_name}' is not available in the current tool catalog. \ |
| 1832 | {suggestion_text}{search}" |
| 1833 | ) |
| 1834 | } |
| 1835 | |
| 1836 | fn shell_tool_allow_shell_hint() -> &'static str { |
| 1837 | "Shell tools are absent because this session or profile disabled shell access, \ |
| 1838 | commonly via top-level `allow_shell = false`. \ |
| 1839 | Work mode exposes shell by default with approval gating unless disabled. \ |
| 1840 | Run `/config allow_shell true` for this session or add `--save` for future sessions; \ |
| 1841 | the next turn will expose shell again" |
| 1842 | } |
| 1843 | |
| 1844 | pub(crate) fn is_shell_tool_name(tool_name: &str) -> bool { |
| 1845 | matches!( |
| 1846 | tool_name, |
| 1847 | "bash" |
| 1848 | | "Bash" |
| 1849 | | "exec_shell" |
| 1850 | | "exec_shell_wait" |
| 1851 | | "exec_shell_interact" |
| 1852 | | "exec_shell_cancel" |
| 1853 | | "task_shell_start" |
| 1854 | | "task_shell_wait" |
| 1855 | | TERMINAL_RUN_NAME |
| 1856 | | TERMINAL_WAIT_NAME |
| 1857 | | TERMINAL_SEND_NAME |
| 1858 | | TERMINAL_CANCEL_NAME |
| 1859 | | TERMINAL_RESET_NAME |
| 1860 | ) |
| 1861 | } |
| 1862 | |
| 1863 | pub(super) fn maybe_hydrate_requested_deferred_tool( |
| 1864 | tool_name: &str, |
| 1865 | tool_input: &Value, |
| 1866 | catalog: &[Tool], |
| 1867 | active_tools_at_batch_start: &HashSet<String>, |
| 1868 | hydrated_tools_this_batch: &mut HashSet<String>, |
| 1869 | ) -> Option<ToolResult> { |
| 1870 | let def = catalog.iter().find(|def| def.name == tool_name)?; |
| 1871 | |
| 1872 | if !def.defer_loading.unwrap_or(false) || active_tools_at_batch_start.contains(tool_name) { |
| 1873 | return None; |
| 1874 | } |
| 1875 | |
| 1876 | hydrated_tools_this_batch.insert(tool_name.to_string()); |
| 1877 | if deferred_first_call_matches_schema(def, tool_input) { |
| 1878 | // Progressive disclosure keeps unused schemas out of the prefix; it |
| 1879 | // must not cost a well-formed call its turn. Every authority gate has |
| 1880 | // already run for this call, so executing it grants nothing new, and |
| 1881 | // the tool still activates at the tail for later requests. |
| 1882 | return None; |
| 1883 | } |
| 1884 | Some(deferred_tool_schema_hydration_result(def, tool_input)) |
| 1885 | } |
| 1886 | |
| 1887 | /// Whether a call to a tool whose schema the model has not yet been shown is |
| 1888 | /// shaped like that schema: an object carrying every required field and, when |
| 1889 | /// the schema declares properties, no field outside them. Known limitation: |
| 1890 | /// field types are left to the tool's own input validation, which reports a |
| 1891 | /// wrong type as an ordinary tool error after the schema has been activated. |
| 1892 | pub fn deferred_first_call_matches_schema(tool: &Tool, tool_input: &Value) -> bool { |
| 1893 | let Some(input) = tool_input.as_object() else { |
| 1894 | return false; |
| 1895 | }; |
| 1896 | let expected = schema_fields(&tool.input_schema); |
| 1897 | let required = schema_required_fields(&tool.input_schema); |
| 1898 | required.iter().all(|field| input.contains_key(field)) |
| 1899 | && (expected.is_empty() && input.is_empty() |
| 1900 | || !expected.is_empty() |
| 1901 | && input |
| 1902 | .keys() |
| 1903 | .all(|key| expected.iter().any(|field| &field.name == key))) |
| 1904 | } |
| 1905 | |
| 1906 | #[cfg(test)] |
| 1907 | pub(super) fn preflight_requested_deferred_tool( |
| 1908 | tool_name: &str, |
| 1909 | tool_input: &Value, |
| 1910 | catalog: &[Tool], |
| 1911 | active_tools: &mut HashSet<String>, |
| 1912 | ) -> Option<ToolResult> { |
| 1913 | let active_tools_at_batch_start = active_tools.clone(); |
| 1914 | let mut hydrated_tools_this_batch = HashSet::new(); |
| 1915 | let result = maybe_hydrate_requested_deferred_tool( |
| 1916 | tool_name, |
| 1917 | tool_input, |
| 1918 | catalog, |
| 1919 | &active_tools_at_batch_start, |
| 1920 | &mut hydrated_tools_this_batch, |
| 1921 | ); |
| 1922 | active_tools.extend(hydrated_tools_this_batch); |
| 1923 | result |
| 1924 | } |
| 1925 | |
| 1926 | pub fn deferred_tool_schema_hydration_result(tool: &Tool, tool_input: &Value) -> ToolResult { |
| 1927 | let expected = schema_fields(&tool.input_schema); |
| 1928 | let required = schema_required_fields(&tool.input_schema); |
| 1929 | let received = received_field_names(tool_input); |
| 1930 | let missing = required |
| 1931 | .iter() |
| 1932 | .filter(|field| !received.contains(field)) |
| 1933 | .cloned() |
| 1934 | .collect::<Vec<_>>(); |
| 1935 | let unexpected = received |
| 1936 | .iter() |
| 1937 | .filter(|field| !expected.iter().any(|expected| &expected.name == *field)) |
| 1938 | .cloned() |
| 1939 | .collect::<Vec<_>>(); |
| 1940 | let corrections = likely_field_corrections(&received, &expected, &tool.name); |
| 1941 | |
| 1942 | let mut lines = vec![ |
| 1943 | format!("Tool `{}` was deferred and has now been loaded.", tool.name), |
| 1944 | String::new(), |
| 1945 | "The tool was not executed. Retry with the loaded schema.".to_string(), |
| 1946 | String::new(), |
| 1947 | "Expected fields:".to_string(), |
| 1948 | ]; |
| 1949 | if expected.is_empty() { |
| 1950 | lines.push(" (none)".to_string()); |
| 1951 | } else { |
| 1952 | for field in &expected { |
| 1953 | let required_marker = if required.contains(&field.name) { |
| 1954 | " required" |
| 1955 | } else { |
| 1956 | "" |
| 1957 | }; |
| 1958 | match field.description.as_deref() { |
| 1959 | Some(description) => lines.push(format!( |
| 1960 | " {}: {}{} — {}", |
| 1961 | field.name, field.kind, required_marker, description |
| 1962 | )), |
| 1963 | None => lines.push(format!( |
| 1964 | " {}: {}{}", |
| 1965 | field.name, field.kind, required_marker |
| 1966 | )), |
| 1967 | } |
| 1968 | } |
| 1969 | } |
| 1970 | lines.push(String::new()); |
| 1971 | lines.push("Received fields:".to_string()); |
| 1972 | if received.is_empty() { |
| 1973 | lines.push(" (none)".to_string()); |
| 1974 | } else { |
| 1975 | lines.push(format!(" {}", received.join(", "))); |
| 1976 | } |
| 1977 | if !missing.is_empty() { |
| 1978 | lines.push(String::new()); |
| 1979 | lines.push("Missing required fields:".to_string()); |
| 1980 | lines.push(format!(" {}", missing.join(", "))); |
| 1981 | } |
| 1982 | if !unexpected.is_empty() { |
| 1983 | lines.push(String::new()); |
| 1984 | lines.push("Unexpected fields:".to_string()); |
| 1985 | lines.push(format!(" {}", unexpected.join(", "))); |
| 1986 | } |
| 1987 | if !corrections.is_empty() { |
| 1988 | lines.push(String::new()); |
| 1989 | lines.push("Likely corrections:".to_string()); |
| 1990 | for correction in &corrections { |
| 1991 | lines.push(format!(" {correction}")); |
| 1992 | } |
| 1993 | } |
| 1994 | |
| 1995 | ToolResult::error(lines.join("\n")).with_metadata(json!({ |
| 1996 | "event": "tool.schema_hydrated", |
| 1997 | "tool": tool.name, |
| 1998 | "executed": false, |
| 1999 | "retry_required": true, |
| 2000 | "reason": "deferred_tool_first_use", |
| 2001 | "deferred_tool_loaded": true, |
| 2002 | "tool_name": tool.name, |
| 2003 | "expected_fields": expected.iter().map(|field| field.name.clone()).collect::<Vec<_>>(), |
| 2004 | "received_fields": received, |
| 2005 | "missing_required_fields": missing, |
| 2006 | "unexpected_fields": unexpected, |
| 2007 | "likely_corrections": corrections, |
| 2008 | })) |
| 2009 | } |
| 2010 | |
| 2011 | #[derive(Debug, Clone)] |
| 2012 | struct SchemaField { |
| 2013 | name: String, |
| 2014 | kind: String, |
| 2015 | description: Option<String>, |
| 2016 | } |
| 2017 | |
| 2018 | fn schema_fields(schema: &Value) -> Vec<SchemaField> { |
| 2019 | let Some(properties) = schema.get("properties").and_then(Value::as_object) else { |
| 2020 | return Vec::new(); |
| 2021 | }; |
| 2022 | let mut fields = properties |
| 2023 | .iter() |
| 2024 | .map(|(name, spec)| SchemaField { |
| 2025 | name: name.clone(), |
| 2026 | kind: schema_type_label(spec), |
| 2027 | description: concise_schema_description(spec), |
| 2028 | }) |
| 2029 | .collect::<Vec<_>>(); |
| 2030 | fields.sort_by(|a, b| a.name.cmp(&b.name)); |
| 2031 | fields |
| 2032 | } |
| 2033 | |
| 2034 | fn concise_schema_description(spec: &Value) -> Option<String> { |
| 2035 | const MAX_DESC_CHARS: usize = 160; |
| 2036 | let raw = spec.get("description").and_then(Value::as_str)?; |
| 2037 | let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" "); |
| 2038 | if collapsed.is_empty() { |
| 2039 | return None; |
| 2040 | } |
| 2041 | if collapsed.chars().count() <= MAX_DESC_CHARS { |
| 2042 | return Some(collapsed); |
| 2043 | } |
| 2044 | let truncated: String = collapsed.chars().take(MAX_DESC_CHARS - 1).collect(); |
| 2045 | Some(format!("{truncated}…")) |
| 2046 | } |
| 2047 | |
| 2048 | fn schema_required_fields(schema: &Value) -> Vec<String> { |
| 2049 | let mut required = schema |
| 2050 | .get("required") |
| 2051 | .and_then(Value::as_array) |
| 2052 | .into_iter() |
| 2053 | .flatten() |
| 2054 | .filter_map(|value| value.as_str().map(str::to_string)) |
| 2055 | .collect::<Vec<_>>(); |
| 2056 | required.sort(); |
| 2057 | required |
| 2058 | } |
| 2059 | |
| 2060 | fn schema_type_label(spec: &Value) -> String { |
| 2061 | schema_type_label_at_depth(spec, 0) |
| 2062 | } |
| 2063 | |
| 2064 | fn schema_type_label_at_depth(spec: &Value, depth: usize) -> String { |
| 2065 | const MAX_NESTED_DEPTH: usize = 2; |
| 2066 | const MAX_NESTED_FIELDS: usize = 6; |
| 2067 | if let Some(values) = spec.get("enum").and_then(Value::as_array) { |
| 2068 | let labels = values |
| 2069 | .iter() |
| 2070 | .filter_map(|value| match value { |
| 2071 | Value::String(text) => Some(text.clone()), |
| 2072 | Value::Number(num) => Some(num.to_string()), |
| 2073 | Value::Bool(flag) => Some(flag.to_string()), |
| 2074 | _ => None, |
| 2075 | }) |
| 2076 | .collect::<Vec<_>>(); |
| 2077 | if !labels.is_empty() { |
| 2078 | let kind = spec.get("type").and_then(Value::as_str).unwrap_or("enum"); |
| 2079 | return format!("{kind} ({})", labels.join(" | ")); |
| 2080 | } |
| 2081 | } |
| 2082 | if let Some(variants) = spec |
| 2083 | .get("oneOf") |
| 2084 | .or_else(|| spec.get("anyOf")) |
| 2085 | .and_then(Value::as_array) |
| 2086 | && depth < MAX_NESTED_DEPTH |
| 2087 | { |
| 2088 | let labels = variants |
| 2089 | .iter() |
| 2090 | .map(|variant| schema_type_label_at_depth(variant, depth + 1)) |
| 2091 | .collect::<Vec<_>>(); |
| 2092 | if !labels.is_empty() { |
| 2093 | return labels.join(" | "); |
| 2094 | } |
| 2095 | } |
| 2096 | let Some(kind) = spec.get("type").and_then(Value::as_str) else { |
| 2097 | if spec.get("properties").is_some() && depth < MAX_NESTED_DEPTH { |
| 2098 | return format_nested_object_shape(spec, depth, MAX_NESTED_FIELDS); |
| 2099 | } |
| 2100 | return "value".to_string(); |
| 2101 | }; |
| 2102 | if kind == "array" |
| 2103 | && depth < MAX_NESTED_DEPTH |
| 2104 | && let Some(items) = spec.get("items") |
| 2105 | { |
| 2106 | return format!("array<{}>", schema_type_label_at_depth(items, depth + 1)); |
| 2107 | } |
| 2108 | if kind == "object" && depth < MAX_NESTED_DEPTH && spec.get("properties").is_some() { |
| 2109 | return format_nested_object_shape(spec, depth, MAX_NESTED_FIELDS); |
| 2110 | } |
| 2111 | kind.to_string() |
| 2112 | } |
| 2113 | |
| 2114 | fn format_nested_object_shape(spec: &Value, depth: usize, max_fields: usize) -> String { |
| 2115 | let Some(properties) = spec.get("properties").and_then(Value::as_object) else { |
| 2116 | return "object".to_string(); |
| 2117 | }; |
| 2118 | if properties.is_empty() { |
| 2119 | return "object".to_string(); |
| 2120 | } |
| 2121 | let required = schema_required_fields(spec); |
| 2122 | let mut keys = properties.keys().collect::<Vec<_>>(); |
| 2123 | keys.sort(); |
| 2124 | let total = keys.len(); |
| 2125 | let mut parts = keys |
| 2126 | .into_iter() |
| 2127 | .take(max_fields) |
| 2128 | .map(|key| { |
| 2129 | let child = schema_type_label_at_depth(&properties[key], depth + 1); |
| 2130 | if required.contains(key) { |
| 2131 | format!("{key}: {child} required") |
| 2132 | } else { |
| 2133 | format!("{key}: {child}") |
| 2134 | } |
| 2135 | }) |
| 2136 | .collect::<Vec<_>>(); |
| 2137 | if total > max_fields { |
| 2138 | parts.push(format!("+{} more", total - max_fields)); |
| 2139 | } |
| 2140 | format!("object {{{}}}", parts.join(", ")) |
| 2141 | } |
| 2142 | |
| 2143 | fn received_field_names(input: &Value) -> Vec<String> { |
| 2144 | let mut fields = input |
| 2145 | .as_object() |
| 2146 | .map(|object| object.keys().cloned().collect::<Vec<_>>()) |
| 2147 | .unwrap_or_default(); |
| 2148 | fields.sort(); |
| 2149 | fields |
| 2150 | } |
| 2151 | |
| 2152 | fn likely_field_corrections( |
| 2153 | received: &[String], |
| 2154 | expected: &[SchemaField], |
| 2155 | tool_name: &str, |
| 2156 | ) -> Vec<String> { |
| 2157 | let has_expected = |name: &str| expected.iter().any(|field| field.name == name); |
| 2158 | let has_received = |name: &str| received.iter().any(|field| field == name); |
| 2159 | let mut corrections = Vec::new(); |
| 2160 | |
| 2161 | if has_received("old_string") && has_expected("search") { |
| 2162 | corrections.push("old_string -> search".to_string()); |
| 2163 | } else if has_received("old_str") && has_expected("search") { |
| 2164 | corrections.push("old_str -> search".to_string()); |
| 2165 | } |
| 2166 | if has_received("new_string") && has_expected("replace") { |
| 2167 | corrections.push("new_string -> replace".to_string()); |
| 2168 | } else if has_received("new_str") && has_expected("replace") { |
| 2169 | corrections.push("new_str -> replace".to_string()); |
| 2170 | } else if has_received("replacement") && has_expected("replace") { |
| 2171 | corrections.push("replacement -> replace".to_string()); |
| 2172 | } |
| 2173 | if matches!(tool_name, "checklist_update" | "todo_update") && has_received("todos") { |
| 2174 | corrections.push( |
| 2175 | "Use todo_write to replace the full list, or retry checklist_update/todo_update with id and status." |
| 2176 | .to_string(), |
| 2177 | ); |
| 2178 | } |
| 2179 | // RLM source fields are easy to misname (#2659). rlm_open takes exactly one |
| 2180 | // of file_path / content / url / session_object; nudge common wrong names |
| 2181 | // toward those. The unified `rlm` tool carries the same fields for |
| 2182 | // action=open, so it gets the same correction. |
| 2183 | if matches!(tool_name, "rlm_open" | "rlm") { |
| 2184 | for wrong in [ |
| 2185 | "prompt", |
| 2186 | "resident_file", |
| 2187 | "text", |
| 2188 | "body", |
| 2189 | "path", |
| 2190 | "file", |
| 2191 | "source", |
| 2192 | ] { |
| 2193 | if has_received(wrong) |
| 2194 | && !has_received("file_path") |
| 2195 | && !has_received("content") |
| 2196 | && !has_received("url") |
| 2197 | && !has_received("session_object") |
| 2198 | { |
| 2199 | corrections.push(format!("{wrong} -> file_path (local file), content (inline text), url, or session_object")); |
| 2200 | } |
| 2201 | } |
| 2202 | } |
| 2203 | corrections |
| 2204 | } |
| 2205 | |
| 2206 | #[cfg(test)] |
| 2207 | pub(super) fn execute_tool_search( |
| 2208 | tool_name: &str, |
| 2209 | input: &serde_json::Value, |
| 2210 | catalog: &[Tool], |
| 2211 | active_tools: &mut HashSet<String>, |
| 2212 | ) -> Result<ToolResult, ToolError> { |
| 2213 | execute_tool_search_inner( |
| 2214 | tool_name, |
| 2215 | input, |
| 2216 | catalog, |
| 2217 | AppMode::Agent, |
| 2218 | active_tools, |
| 2219 | None, |
| 2220 | &mut |_| Ok(Default::default()), |
| 2221 | ) |
| 2222 | } |
| 2223 | |
| 2224 | /// Execute tool search while retaining activated schemas in the bounded |
| 2225 | /// conversation cache. Kept separate from the test-only pure search helper so existing |
| 2226 | /// pure catalog tests and compatibility callers do not need an engine session. |
| 2227 | pub fn execute_tool_search_measured( |
| 2228 | tool_name: &str, |
| 2229 | input: &serde_json::Value, |
| 2230 | catalog: &[Tool], |
| 2231 | active_tools: &mut HashSet<String>, |
| 2232 | cache: &mut crate::core::session::ToolActivationCache, |
| 2233 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 2234 | ) -> Result<ToolResult, ToolError> { |
| 2235 | execute_tool_search_measured_for_mode( |
| 2236 | tool_name, |
| 2237 | input, |
| 2238 | catalog, |
| 2239 | AppMode::Agent, |
| 2240 | active_tools, |
| 2241 | cache, |
| 2242 | measure, |
| 2243 | ) |
| 2244 | } |
| 2245 | |
| 2246 | pub(super) fn execute_tool_search_measured_for_mode( |
| 2247 | tool_name: &str, |
| 2248 | input: &serde_json::Value, |
| 2249 | catalog: &[Tool], |
| 2250 | mode: AppMode, |
| 2251 | active_tools: &mut HashSet<String>, |
| 2252 | cache: &mut crate::core::session::ToolActivationCache, |
| 2253 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 2254 | ) -> Result<ToolResult, ToolError> { |
| 2255 | execute_tool_search_inner( |
| 2256 | tool_name, |
| 2257 | input, |
| 2258 | catalog, |
| 2259 | mode, |
| 2260 | active_tools, |
| 2261 | Some(cache), |
| 2262 | measure, |
| 2263 | ) |
| 2264 | } |
| 2265 | |
| 2266 | #[cfg(any(test, feature = "test-support"))] |
| 2267 | pub fn execute_tool_search_with_cache( |
| 2268 | tool_name: &str, |
| 2269 | input: &serde_json::Value, |
| 2270 | catalog: &[Tool], |
| 2271 | active_tools: &mut HashSet<String>, |
| 2272 | cache: &mut crate::core::session::ToolActivationCache, |
| 2273 | ) -> Result<ToolResult, ToolError> { |
| 2274 | execute_tool_search_measured( |
| 2275 | tool_name, |
| 2276 | input, |
| 2277 | catalog, |
| 2278 | active_tools, |
| 2279 | cache, |
| 2280 | &mut |names| ToolActivationCache::test_measure(catalog, names), |
| 2281 | ) |
| 2282 | } |
| 2283 | |
| 2284 | fn execute_tool_search_inner( |
| 2285 | _tool_name: &str, |
| 2286 | input: &serde_json::Value, |
| 2287 | catalog: &[Tool], |
| 2288 | mode: AppMode, |
| 2289 | active_tools: &mut HashSet<String>, |
| 2290 | cache: Option<&mut crate::core::session::ToolActivationCache>, |
| 2291 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 2292 | ) -> Result<ToolResult, ToolError> { |
| 2293 | let query = required_str(input, "query")?; |
| 2294 | let match_kind = optional_str(input, "match")?.unwrap_or("bm25"); |
| 2295 | if !matches!(match_kind, "bm25" | "regex") { |
| 2296 | return Err(ToolError::invalid_input(format!( |
| 2297 | "Unsupported match algorithm '{match_kind}'. Expected one of: bm25, regex" |
| 2298 | ))); |
| 2299 | } |
| 2300 | let max_results = usize::try_from(optional_u64( |
| 2301 | input, |
| 2302 | "max_results", |
| 2303 | TOOL_SEARCH_DEFAULT_MAX_RESULTS as u64, |
| 2304 | )?) |
| 2305 | .unwrap_or(TOOL_SEARCH_DEFAULT_MAX_RESULTS) |
| 2306 | .clamp(1, TOOL_SEARCH_MAX_RESULTS_LIMIT); |
| 2307 | let visible = mode_visible_catalog(catalog, mode); |
| 2308 | let mut discovered = if match_kind == "regex" { |
| 2309 | discover_tools_with_regex(&visible, query, max_results, active_tools, cache.as_deref())? |
| 2310 | } else { |
| 2311 | discover_tools_with_bm25_like(&visible, query, max_results, active_tools, cache.as_deref()) |
| 2312 | }; |
| 2313 | discovered.retain(|name| { |
| 2314 | catalog |
| 2315 | .iter() |
| 2316 | .find(|tool| &tool.name == name) |
| 2317 | .is_some_and(|tool| !is_eager_wire_tool(tool, active_tools, cache.as_deref())) |
| 2318 | }); |
| 2319 | let remaining_results = max_results.saturating_sub(discovered.len()); |
| 2320 | let unavailable = if match_kind == "regex" { |
| 2321 | unavailable_core_action_tools_with_regex(catalog, query, remaining_results)? |
| 2322 | } else { |
| 2323 | unavailable_core_action_tools_with_bm25_like(catalog, query, remaining_results) |
| 2324 | }; |
| 2325 | let unavailable_references = unavailable |
| 2326 | .iter() |
| 2327 | .map(|fallback| { |
| 2328 | json!({ |
| 2329 | "type": "unavailable_tool_reference", |
| 2330 | "tool_name": fallback.name, |
| 2331 | "reason": fallback.unavailable_reason, |
| 2332 | }) |
| 2333 | }) |
| 2334 | .collect(); |
| 2335 | let (payload, metadata) = admit_deferred_tools( |
| 2336 | Admission::Search, |
| 2337 | catalog, |
| 2338 | (mode == AppMode::Plan).then_some(&*visible), |
| 2339 | active_tools, |
| 2340 | cache, |
| 2341 | measure, |
| 2342 | discovered, |
| 2343 | unavailable_references, |
| 2344 | )?; |
| 2345 | Ok(admission_result(&payload, metadata)) |
| 2346 | } |
| 2347 | |
| 2348 | #[derive(Clone, Copy)] |
| 2349 | enum Admission { |
| 2350 | Search, |
| 2351 | ProgramLoad, |
| 2352 | } |
| 2353 | |
| 2354 | impl Admission { |
| 2355 | fn result_type(self) -> &'static str { |
| 2356 | match self { |
| 2357 | Self::Search => "tool_search_tool_search_result", |
| 2358 | Self::ProgramLoad => "tool_load_result", |
| 2359 | } |
| 2360 | } |
| 2361 | |
| 2362 | fn readmit(self) -> &'static str { |
| 2363 | match self { |
| 2364 | Self::Search => "Call tool_search with tool_search_input", |
| 2365 | Self::ProgramLoad => "Call tools.load with this name", |
| 2366 | } |
| 2367 | } |
| 2368 | |
| 2369 | fn readmission_reference(self, name: &str, reason: String, kind: &str) -> Value { |
| 2370 | let mut reference = json!({ |
| 2371 | "type": kind, |
| 2372 | "tool_name": name, |
| 2373 | "reason": reason, |
| 2374 | }); |
| 2375 | if matches!(self, Self::Search) { |
| 2376 | reference["tool_search_input"] = readmission_search_input(name); |
| 2377 | } |
| 2378 | reference |
| 2379 | } |
| 2380 | } |
| 2381 | |
| 2382 | fn admit_deferred_tools( |
| 2383 | admission: Admission, |
| 2384 | catalog: &[Tool], |
| 2385 | visible: Option<&[Tool]>, |
| 2386 | active_tools: &mut HashSet<String>, |
| 2387 | cache: Option<&mut crate::core::session::ToolActivationCache>, |
| 2388 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 2389 | mut discovered: Vec<String>, |
| 2390 | mut unavailable_references: Vec<Value>, |
| 2391 | ) -> Result<(Value, Value), ToolError> { |
| 2392 | let mut cache_rejected = Vec::new(); |
| 2393 | let mut cache_held = Vec::new(); |
| 2394 | let mut evicted = Vec::new(); |
| 2395 | let mut toolbox = None; |
| 2396 | if let Some(cache) = cache { |
| 2397 | if discovered.is_empty() { |
| 2398 | toolbox = Some(json!({ |
| 2399 | "active_deferred_tools": cache.names().filter(|name| visible.is_none_or(|visible| catalog_contains_tool(visible, name))).collect::<Vec<_>>(), |
| 2400 | "added_wire_schema_bytes": Value::Null, |
| 2401 | "soft_name_target": crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES, |
| 2402 | "soft_wire_byte_target": crate::core::session::TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES, |
| 2403 | "exceeds_soft_target": cache.names().count() > crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES, |
| 2404 | "authority": "Current deferred toolbox; admitted tools supersede earlier eviction or unavailable notices for the same name. Permission checks still apply to every call.", |
| 2405 | })); |
| 2406 | } else { |
| 2407 | let delta = cache.activate_measured(catalog, &discovered, measure)?; |
| 2408 | toolbox = Some(json!({ |
| 2409 | "active_deferred_tools": cache.names().filter(|name| visible.is_none_or(|visible| catalog_contains_tool(visible, name))).collect::<Vec<_>>(), |
| 2410 | "added_wire_schema_bytes": delta.schema_bytes, |
| 2411 | "soft_name_target": crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES, |
| 2412 | "soft_wire_byte_target": crate::core::session::TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES, |
| 2413 | "exceeds_soft_target": delta.exceeds_soft_target, |
| 2414 | "authority": "Current deferred toolbox; admitted tools supersede earlier eviction or unavailable notices for the same name. Permission checks still apply to every call.", |
| 2415 | })); |
| 2416 | remove_evicted_cache_activations(catalog, active_tools, delta.evicted.iter().cloned()); |
| 2417 | evicted = delta |
| 2418 | .evicted |
| 2419 | .into_iter() |
| 2420 | .filter(|name| { |
| 2421 | !active_tools.contains(name) |
| 2422 | && visible.is_none_or(|visible| catalog_contains_tool(visible, name)) |
| 2423 | }) |
| 2424 | .collect(); |
| 2425 | cache_rejected = delta.rejected; |
| 2426 | cache_held = delta.held; |
| 2427 | discovered = delta.admitted; |
| 2428 | for name in discovered.iter().rev() { |
| 2429 | cache.record_use(name); |
| 2430 | } |
| 2431 | } |
| 2432 | } |
| 2433 | for name in &discovered { |
| 2434 | active_tools.insert(name.clone()); |
| 2435 | } |
| 2436 | |
| 2437 | let references = discovered |
| 2438 | .iter() |
| 2439 | .map(|name| json!({"type": "tool_reference", "tool_name": name})) |
| 2440 | .collect::<Vec<_>>(); |
| 2441 | unavailable_references.extend(cache_rejected.iter().map(|name| { |
| 2442 | json!({ |
| 2443 | "type": "unavailable_tool_reference", |
| 2444 | "tool_name": name, |
| 2445 | "reason": format!("The provider cannot offer this tool schema, or its added wire schema exceeds {}KiB. It was not loaded. Use a smaller matching tool or a compatible route.", crate::core::session::TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES / 1024) |
| 2446 | }) |
| 2447 | })); |
| 2448 | unavailable_references.extend(cache_held.iter().map(|name| { |
| 2449 | admission.readmission_reference( |
| 2450 | name, |
| 2451 | format!("Not loaded in this batch: with the matches loaded before it, this schema would pass the soft toolbox target ({}) for one search, or twice that for the whole toolbox. {} to load this match on its own.", toolbox_soft_targets(), admission.readmit()), |
| 2452 | "unavailable_tool_reference", |
| 2453 | ) |
| 2454 | })); |
| 2455 | |
| 2456 | let mut payload = json!({ |
| 2457 | "type": admission.result_type(), |
| 2458 | "tool_references": references, |
| 2459 | "unavailable_tool_references": unavailable_references.clone(), |
| 2460 | }); |
| 2461 | let mut metadata = json!({ |
| 2462 | "tool_references": discovered, |
| 2463 | "unavailable_tool_references": unavailable_references, |
| 2464 | }); |
| 2465 | if let Some(toolbox) = toolbox { |
| 2466 | payload["toolbox"] = toolbox.clone(); |
| 2467 | metadata["toolbox"] = toolbox; |
| 2468 | } |
| 2469 | if !evicted.is_empty() { |
| 2470 | payload["evicted_tool_references"] = evicted |
| 2471 | .iter() |
| 2472 | .map(|name| { |
| 2473 | admission.readmission_reference( |
| 2474 | name, |
| 2475 | format!("Removed from the current deferred toolbox while making room under its soft targets ({}); MCP tools are removed before first-party tools. {} to load it again; a later admission supersedes this notice.", toolbox_soft_targets(), admission.readmit()), |
| 2476 | "evicted_tool_reference", |
| 2477 | ) |
| 2478 | }) |
| 2479 | .collect(); |
| 2480 | metadata["evicted_tool_references"] = json!(evicted); |
| 2481 | } |
| 2482 | Ok((payload, metadata)) |
| 2483 | } |
| 2484 | |
| 2485 | fn admission_result(payload: &Value, metadata: Value) -> ToolResult { |
| 2486 | ToolResult { |
| 2487 | content: serde_json::to_string(payload).unwrap_or_else(|_| payload.to_string()), |
| 2488 | success: true, |
| 2489 | metadata: Some(metadata), |
| 2490 | } |
| 2491 | } |
| 2492 | |
| 2493 | pub(super) fn load_tools_for_program( |
| 2494 | input: &Value, |
| 2495 | catalog: &[Tool], |
| 2496 | mode: AppMode, |
| 2497 | active_tools: &mut HashSet<String>, |
| 2498 | cache: &mut crate::core::session::ToolActivationCache, |
| 2499 | measure: &mut crate::core::session::ToolActivationMeasurer<'_>, |
| 2500 | ) -> Result<ToolResult, ToolError> { |
| 2501 | let ProgramDiscovery::Load { names } = ProgramDiscovery::parse(input)? else { |
| 2502 | return Err(ToolError::invalid_input("expected a tools.load request")); |
| 2503 | }; |
| 2504 | let visible = mode_visible_catalog(catalog, mode); |
| 2505 | let mut seen = HashSet::new(); |
| 2506 | let mut deferred = Vec::new(); |
| 2507 | let mut already_available = Vec::new(); |
| 2508 | let mut unavailable = Vec::new(); |
| 2509 | for name in names { |
| 2510 | if !seen.insert(name) { |
| 2511 | continue; |
| 2512 | } |
| 2513 | match visible.iter().find(|tool| tool.name == name) { |
| 2514 | None => unavailable.push(json!({ |
| 2515 | "type": "unavailable_tool_reference", |
| 2516 | "tool_name": name, |
| 2517 | "reason": unknown_program_tool_message(&visible, name), |
| 2518 | })), |
| 2519 | Some(tool) if is_eager_wire_tool(tool, active_tools, Some(&*cache)) => { |
| 2520 | already_available.push(name.to_string()); |
| 2521 | } |
| 2522 | Some(_) => deferred.push(name.to_string()), |
| 2523 | } |
| 2524 | } |
| 2525 | let (mut payload, mut metadata) = admit_deferred_tools( |
| 2526 | Admission::ProgramLoad, |
| 2527 | catalog, |
| 2528 | (mode == AppMode::Plan).then_some(&*visible), |
| 2529 | active_tools, |
| 2530 | Some(cache), |
| 2531 | measure, |
| 2532 | deferred, |
| 2533 | unavailable, |
| 2534 | )?; |
| 2535 | payload["already_available"] = json!(already_available); |
| 2536 | metadata["already_available"] = json!(already_available); |
| 2537 | Ok(admission_result(&payload, metadata)) |
| 2538 | } |
| 2539 | |
| 2540 | pub(super) fn is_program_load(input: &Value) -> bool { |
| 2541 | input.get("mode").and_then(Value::as_str) == Some("load") |
| 2542 | } |
| 2543 | |
| 2544 | pub(super) fn validate_discovery_input(input: &Value) -> Result<(), ToolError> { |
| 2545 | if input.get("mode").is_some() { |
| 2546 | return ProgramDiscovery::parse(input).map(|_| ()); |
| 2547 | } |
| 2548 | let query = required_str(input, "query")?; |
| 2549 | match optional_str(input, "match")?.unwrap_or("bm25") { |
| 2550 | "bm25" => Ok(()), |
| 2551 | "regex" => compile_tool_search_regex(query).map(|_| ()), |
| 2552 | other => Err(ToolError::invalid_input(format!( |
| 2553 | "Unsupported match algorithm '{other}'. Expected one of: bm25, regex" |
| 2554 | ))), |
| 2555 | } |
| 2556 | } |
| 2557 | |
| 2558 | fn toolbox_soft_targets() -> String { |
| 2559 | format!( |
| 2560 | "{} deferred tools, {}KiB of added wire schemas", |
| 2561 | crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES, |
| 2562 | crate::core::session::TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES / 1024 |
| 2563 | ) |
| 2564 | } |
| 2565 | |
| 2566 | fn readmission_search_input(name: &str) -> Value { |
| 2567 | json!({ |
| 2568 | "query": format!("^{}$", regex::escape(name)), |
| 2569 | "match": "regex", |
| 2570 | "max_results": 1, |
| 2571 | }) |
| 2572 | } |
| 2573 | |
| 2574 | fn render_ts_type(schema: &Value, depth: usize) -> String { |
| 2575 | if let Some(variants) = schema.get("enum").and_then(Value::as_array) { |
| 2576 | let mut rendered = Vec::new(); |
| 2577 | for variant in variants.iter().take(6) { |
| 2578 | rendered.push(match variant { |
| 2579 | Value::String(s) => format!("\"{}\"", s.replace('"', "\\\"")), |
| 2580 | other => other.to_string(), |
| 2581 | }); |
| 2582 | } |
| 2583 | if variants.len() > 6 { |
| 2584 | rendered.push("...".to_string()); |
| 2585 | } |
| 2586 | if !rendered.is_empty() { |
| 2587 | return rendered.join(" | "); |
| 2588 | } |
| 2589 | } |
| 2590 | if let Some(const_val) = schema.get("const") { |
| 2591 | return match const_val { |
| 2592 | Value::String(s) => format!("\"{}\"", s.replace('"', "\\\"")), |
| 2593 | other => other.to_string(), |
| 2594 | }; |
| 2595 | } |
| 2596 | if depth < 2 { |
| 2597 | for union_key in ["anyOf", "oneOf"] { |
| 2598 | if let Some(branches) = schema.get(union_key).and_then(Value::as_array) { |
| 2599 | let mut parts = Vec::new(); |
| 2600 | for branch in branches.iter().take(4) { |
| 2601 | let rendered = render_ts_type(branch, depth + 1); |
| 2602 | if !parts.contains(&rendered) { |
| 2603 | parts.push(rendered); |
| 2604 | } |
| 2605 | } |
| 2606 | if !parts.is_empty() { |
| 2607 | return parts.join(" | "); |
| 2608 | } |
| 2609 | } |
| 2610 | } |
| 2611 | } |
| 2612 | match schema.get("type") { |
| 2613 | Some(Value::String(kind)) => match kind.as_str() { |
| 2614 | "string" => "string".to_string(), |
| 2615 | "integer" | "number" => "number".to_string(), |
| 2616 | "boolean" => "boolean".to_string(), |
| 2617 | "null" => "null".to_string(), |
| 2618 | "array" => { |
| 2619 | if depth < 2 |
| 2620 | && let Some(items) = schema.get("items") |
| 2621 | { |
| 2622 | let inner = render_ts_type(items, depth + 1); |
| 2623 | if inner.contains(" | ") { |
| 2624 | format!("({inner})[]") |
| 2625 | } else { |
| 2626 | format!("{inner}[]") |
| 2627 | } |
| 2628 | } else { |
| 2629 | "unknown[]".to_string() |
| 2630 | } |
| 2631 | } |
| 2632 | "object" => { |
| 2633 | if depth < 1 |
| 2634 | && let Some(props) = schema.get("properties").and_then(Value::as_object) |
| 2635 | && !props.is_empty() |
| 2636 | { |
| 2637 | let required: HashSet<&str> = schema |
| 2638 | .get("required") |
| 2639 | .and_then(Value::as_array) |
| 2640 | .into_iter() |
| 2641 | .flatten() |
| 2642 | .filter_map(Value::as_str) |
| 2643 | .collect(); |
| 2644 | let mut keys: Vec<&String> = props.keys().collect(); |
| 2645 | keys.sort_by(|a, b| { |
| 2646 | let a_req = required.contains(a.as_str()); |
| 2647 | let b_req = required.contains(b.as_str()); |
| 2648 | b_req.cmp(&a_req).then_with(|| a.cmp(b)) |
| 2649 | }); |
| 2650 | let mut fields = Vec::new(); |
| 2651 | for key in keys.iter().take(6) { |
| 2652 | let opt = if required.contains(key.as_str()) { |
| 2653 | "" |
| 2654 | } else { |
| 2655 | "?" |
| 2656 | }; |
| 2657 | let ty = render_ts_type(&props[*key], depth + 1); |
| 2658 | fields.push(format!("{key}{opt}: {ty}")); |
| 2659 | } |
| 2660 | if keys.len() > 6 { |
| 2661 | fields.push(format!("...(+{})", keys.len() - 6)); |
| 2662 | } |
| 2663 | format!("{{ {} }}", fields.join(", ")) |
| 2664 | } else { |
| 2665 | "Record<string, unknown>".to_string() |
| 2666 | } |
| 2667 | } |
| 2668 | _ => "unknown".to_string(), |
| 2669 | }, |
| 2670 | Some(Value::Array(kinds)) => { |
| 2671 | let mut parts = Vec::new(); |
| 2672 | for kind in kinds { |
| 2673 | if let Some(s) = kind.as_str() { |
| 2674 | let mapped = match s { |
| 2675 | "string" => "string", |
| 2676 | "integer" | "number" => "number", |
| 2677 | "boolean" => "boolean", |
| 2678 | "null" => "null", |
| 2679 | "array" => "unknown[]", |
| 2680 | "object" => "Record<string, unknown>", |
| 2681 | _ => "unknown", |
| 2682 | }; |
| 2683 | if !parts.contains(&mapped) { |
| 2684 | parts.push(mapped); |
| 2685 | } |
| 2686 | } |
| 2687 | } |
| 2688 | if parts.is_empty() { |
| 2689 | "unknown".to_string() |
| 2690 | } else { |
| 2691 | parts.join(" | ") |
| 2692 | } |
| 2693 | } |
| 2694 | _ => "unknown".to_string(), |
| 2695 | } |
| 2696 | } |
| 2697 | |
| 2698 | pub(crate) fn render_ts_signature(tool: &Tool) -> String { |
| 2699 | let Some(props) = tool |
| 2700 | .input_schema |
| 2701 | .get("properties") |
| 2702 | .and_then(Value::as_object) |
| 2703 | else { |
| 2704 | return format!("{}(): Promise<unknown>", tool.name); |
| 2705 | }; |
| 2706 | if props.is_empty() { |
| 2707 | return format!("{}(): Promise<unknown>", tool.name); |
| 2708 | } |
| 2709 | let required: HashSet<&str> = tool |
| 2710 | .input_schema |
| 2711 | .get("required") |
| 2712 | .and_then(Value::as_array) |
| 2713 | .into_iter() |
| 2714 | .flatten() |
| 2715 | .filter_map(Value::as_str) |
| 2716 | .collect(); |
| 2717 | let mut keys: Vec<&String> = props.keys().collect(); |
| 2718 | keys.sort_by(|a, b| { |
| 2719 | let a_req = required.contains(a.as_str()); |
| 2720 | let b_req = required.contains(b.as_str()); |
| 2721 | b_req.cmp(&a_req).then_with(|| a.cmp(b)) |
| 2722 | }); |
| 2723 | let mut fields = Vec::new(); |
| 2724 | for key in keys.iter().take(12) { |
| 2725 | let opt = if required.contains(key.as_str()) { |
| 2726 | "" |
| 2727 | } else { |
| 2728 | "?" |
| 2729 | }; |
| 2730 | let ty = render_ts_type(&props[*key], 0); |
| 2731 | fields.push(format!("{key}{opt}: {ty}")); |
| 2732 | } |
| 2733 | if keys.len() > 12 { |
| 2734 | fields.push(format!("...(+{})", keys.len() - 12)); |
| 2735 | } |
| 2736 | format!( |
| 2737 | "{}({{ {} }}): Promise<unknown>", |
| 2738 | tool.name, |
| 2739 | fields.join(", ") |
| 2740 | ) |
| 2741 | } |
| 2742 | |
| 2743 | pub(crate) fn summarize_tool_description(description: &str) -> String { |
| 2744 | let first_line = description |
| 2745 | .lines() |
| 2746 | .map(str::trim) |
| 2747 | .find(|line| !line.is_empty()) |
| 2748 | .unwrap_or_default(); |
| 2749 | let collapsed = first_line.split_whitespace().collect::<Vec<_>>().join(" "); |
| 2750 | const MAX_SUMMARY_CHARS: usize = 140; |
| 2751 | if collapsed.chars().count() <= MAX_SUMMARY_CHARS { |
| 2752 | collapsed |
| 2753 | } else { |
| 2754 | let mut out: String = collapsed.chars().take(MAX_SUMMARY_CHARS).collect(); |
| 2755 | out.push('…'); |
| 2756 | out |
| 2757 | } |
| 2758 | } |
| 2759 | |
| 2760 | const PROGRAM_HELPER_NAMES: &[&str] = &["call", "list", "search", "describe", "load"]; |
| 2761 | const PROGRAM_LIST_DEFAULT_LIMIT: u64 = 200; |
| 2762 | const PROGRAM_LIST_MAX_LIMIT: usize = 500; |
| 2763 | const PROGRAM_SEARCH_DEFAULT_LIMIT: u64 = 10; |
| 2764 | const PROGRAM_SEARCH_MAX_LIMIT: usize = 24; |
| 2765 | const PROGRAM_SUGGESTION_LIMIT: usize = 3; |
| 2766 | const PROGRAM_LOAD_MAX_NAMES: usize = 8; |
| 2767 | |
| 2768 | fn tool_namespace(name: &str) -> Option<&str> { |
| 2769 | name.strip_prefix("mcp_") |
| 2770 | .and_then(|rest| rest.split_once('_')) |
| 2771 | .or_else(|| name.split_once('.')) |
| 2772 | .map(|(namespace, _)| namespace) |
| 2773 | .filter(|namespace| !namespace.is_empty() && !PROGRAM_HELPER_NAMES.contains(namespace)) |
| 2774 | } |
| 2775 | |
| 2776 | fn tool_matches_namespace(tool: &Tool, namespace: &str) -> bool { |
| 2777 | let namespace = namespace.to_ascii_lowercase(); |
| 2778 | let name = tool.name.to_ascii_lowercase(); |
| 2779 | name == namespace |
| 2780 | || [ |
| 2781 | format!("mcp_{namespace}_"), |
| 2782 | format!("{namespace}_"), |
| 2783 | format!("{namespace}."), |
| 2784 | ] |
| 2785 | .iter() |
| 2786 | .any(|prefix| name.starts_with(prefix)) |
| 2787 | } |
| 2788 | |
| 2789 | fn discoverable_in_program(tool: &Tool) -> bool { |
| 2790 | !is_tool_search_tool(&tool.name) && tool.name != EXECUTE_TOOLS_TOOL_NAME |
| 2791 | } |
| 2792 | |
| 2793 | fn suggested_signatures(catalog: &[Tool], requested: &str) -> Vec<String> { |
| 2794 | suggest_tools_for_codemode(catalog, requested, PROGRAM_SUGGESTION_LIMIT) |
| 2795 | .iter() |
| 2796 | .filter_map(|name| catalog.iter().find(|tool| &tool.name == name)) |
| 2797 | .map(render_ts_signature) |
| 2798 | .collect() |
| 2799 | } |
| 2800 | |
| 2801 | pub(crate) fn unknown_program_tool_message(catalog: &[Tool], requested: &str) -> String { |
| 2802 | let signatures = suggested_signatures(catalog, requested); |
| 2803 | if signatures.is_empty() { |
| 2804 | format!("unknown tool `{requested}`; find names with tools.list() or tools.search(query)") |
| 2805 | } else { |
| 2806 | format!( |
| 2807 | "unknown tool `{requested}`; did you mean: {}? Check tools.describe(names)", |
| 2808 | signatures.join("; ") |
| 2809 | ) |
| 2810 | } |
| 2811 | } |
| 2812 | |
| 2813 | fn find_program_tool<'a>(tools: &[&'a Tool], requested: &str) -> Option<&'a Tool> { |
| 2814 | if let Some(tool) = tools.iter().copied().find(|tool| tool.name == requested) { |
| 2815 | return Some(tool); |
| 2816 | } |
| 2817 | let mut matches = tools |
| 2818 | .iter() |
| 2819 | .copied() |
| 2820 | .filter(|tool| tool.name.eq_ignore_ascii_case(requested)); |
| 2821 | matches.next().filter(|_| matches.next().is_none()) |
| 2822 | } |
| 2823 | |
| 2824 | fn snake_case(name: &str) -> String { |
| 2825 | let chars: Vec<char> = name.chars().collect(); |
| 2826 | let mut out = String::with_capacity(name.len() + 4); |
| 2827 | for (index, &ch) in chars.iter().enumerate() { |
| 2828 | let word_start = ch.is_ascii_uppercase() |
| 2829 | && index.checked_sub(1).is_some_and(|before| { |
| 2830 | let prev = chars[before]; |
| 2831 | prev.is_ascii_lowercase() |
| 2832 | || prev.is_ascii_digit() |
| 2833 | || (prev.is_ascii_uppercase() |
| 2834 | && chars.get(index + 1).is_some_and(char::is_ascii_lowercase)) |
| 2835 | }); |
| 2836 | if word_start { |
| 2837 | out.push('_'); |
| 2838 | } |
| 2839 | out.push(ch.to_ascii_lowercase()); |
| 2840 | } |
| 2841 | out |
| 2842 | } |
| 2843 | |
| 2844 | fn resolve_program_tool( |
| 2845 | catalog: &[Tool], |
| 2846 | tools: &[&Tool], |
| 2847 | namespace: &str, |
| 2848 | op: &str, |
| 2849 | ) -> Result<String, ToolError> { |
| 2850 | let spellings = |namespace: &str, op: &str| { |
| 2851 | [ |
| 2852 | format!("mcp_{namespace}_{op}"), |
| 2853 | format!("{namespace}_{op}"), |
| 2854 | format!("{namespace}.{op}"), |
| 2855 | ] |
| 2856 | }; |
| 2857 | let given = spellings(namespace, op); |
| 2858 | let (snake_namespace, snake_op) = (snake_case(namespace), snake_case(op)); |
| 2859 | let snake = [ |
| 2860 | spellings(namespace, &snake_op), |
| 2861 | spellings(&snake_namespace, op), |
| 2862 | spellings(&snake_namespace, &snake_op), |
| 2863 | ] |
| 2864 | .concat(); |
| 2865 | let matching = |accepts: &dyn Fn(&str) -> bool| { |
| 2866 | tools |
| 2867 | .iter() |
| 2868 | .copied() |
| 2869 | .filter(|tool| accepts(&tool.name)) |
| 2870 | .collect::<Vec<_>>() |
| 2871 | }; |
| 2872 | let mut hits = matching(&|name: &str| given.iter().any(|candidate| candidate == name)); |
| 2873 | if hits.is_empty() { |
| 2874 | hits = matching(&|name: &str| snake.iter().any(|candidate| candidate == name)); |
| 2875 | } |
| 2876 | if hits.is_empty() { |
| 2877 | hits = matching(&|name: &str| { |
| 2878 | given |
| 2879 | .iter() |
| 2880 | .chain(&snake) |
| 2881 | .any(|candidate| candidate.eq_ignore_ascii_case(name)) |
| 2882 | }); |
| 2883 | } |
| 2884 | match hits.as_slice() { |
| 2885 | [tool] => Ok(tool.name.clone()), |
| 2886 | [] => Err(ToolError::invalid_input(unknown_program_tool_message( |
| 2887 | catalog, |
| 2888 | &format!("{namespace}_{op}"), |
| 2889 | ))), |
| 2890 | several => Err(ToolError::invalid_input(format!( |
| 2891 | "`{namespace}.{op}` matches more than one tool: {}; pass the exact name to tools.call(name, args)", |
| 2892 | several |
| 2893 | .iter() |
| 2894 | .map(|tool| render_ts_signature(tool)) |
| 2895 | .collect::<Vec<_>>() |
| 2896 | .join("; ") |
| 2897 | ))), |
| 2898 | } |
| 2899 | } |
| 2900 | |
| 2901 | fn program_tool_entry( |
| 2902 | tool: &Tool, |
| 2903 | include_signature: bool, |
| 2904 | include_description: bool, |
| 2905 | include_schema: bool, |
| 2906 | ) -> Value { |
| 2907 | let mut entry = json!({ |
| 2908 | "name": tool.name, |
| 2909 | "namespace": tool_namespace(&tool.name), |
| 2910 | "summary": summarize_tool_description(&tool.description), |
| 2911 | }); |
| 2912 | if include_signature { |
| 2913 | entry["signature"] = json!(render_ts_signature(tool)); |
| 2914 | } |
| 2915 | if crate::tools::codemode::refusal_before_gate(&tool.name, &json!({})).is_some() { |
| 2916 | entry["direct_only"] = json!(true); |
| 2917 | } |
| 2918 | if include_description { |
| 2919 | entry["description"] = json!(tool.description); |
| 2920 | } |
| 2921 | if include_schema { |
| 2922 | entry["input_schema"] = tool.input_schema.clone(); |
| 2923 | } |
| 2924 | entry |
| 2925 | } |
| 2926 | |
| 2927 | fn program_tools_result(tools: &[Value], total: usize) -> Result<ToolResult, ToolError> { |
| 2928 | ToolResult::json(&json!({ |
| 2929 | "total": total, |
| 2930 | "truncated": tools.len() < total, |
| 2931 | "tools": tools, |
| 2932 | })) |
| 2933 | .map_err(|error| ToolError::execution_failed(error.to_string())) |
| 2934 | } |
| 2935 | |
| 2936 | pub(super) enum ProgramDiscovery<'a> { |
| 2937 | List { |
| 2938 | namespace: Option<&'a str>, |
| 2939 | limit: usize, |
| 2940 | }, |
| 2941 | Describe { |
| 2942 | names: Vec<&'a str>, |
| 2943 | }, |
| 2944 | Search { |
| 2945 | namespace: Option<&'a str>, |
| 2946 | query: &'a str, |
| 2947 | regex: bool, |
| 2948 | limit: usize, |
| 2949 | }, |
| 2950 | Resolve { |
| 2951 | namespace: &'a str, |
| 2952 | op: &'a str, |
| 2953 | }, |
| 2954 | Load { |
| 2955 | names: Vec<&'a str>, |
| 2956 | }, |
| 2957 | } |
| 2958 | |
| 2959 | impl<'a> ProgramDiscovery<'a> { |
| 2960 | pub(super) fn parse(input: &'a Value) -> Result<Self, ToolError> { |
| 2961 | let namespace = optional_str(input, "namespace")? |
| 2962 | .map(str::trim) |
| 2963 | .filter(|namespace| !namespace.is_empty()); |
| 2964 | let limit = |default: u64, max: usize| -> Result<usize, ToolError> { |
| 2965 | let requested = optional_u64(input, "max_results", default)?; |
| 2966 | Ok(usize::try_from(requested).unwrap_or(max).clamp(1, max)) |
| 2967 | }; |
| 2968 | let regex = |query: &str| -> Result<bool, ToolError> { |
| 2969 | match optional_str(input, "match")?.unwrap_or("bm25") { |
| 2970 | "bm25" => Ok(false), |
| 2971 | "regex" => compile_tool_search_regex(query).map(|_| true), |
| 2972 | other => Err(ToolError::invalid_input(format!( |
| 2973 | "Unsupported match algorithm '{other}'. Expected one of: bm25, regex" |
| 2974 | ))), |
| 2975 | } |
| 2976 | }; |
| 2977 | let names = || -> Result<Vec<&'a str>, ToolError> { |
| 2978 | input |
| 2979 | .get("names") |
| 2980 | .and_then(Value::as_array) |
| 2981 | .and_then(|names| names.iter().map(Value::as_str).collect()) |
| 2982 | .ok_or_else(|| { |
| 2983 | ToolError::invalid_input("names must be an array of tool name strings") |
| 2984 | }) |
| 2985 | }; |
| 2986 | match required_str(input, "mode")? { |
| 2987 | "list" => Ok(Self::List { |
| 2988 | namespace, |
| 2989 | limit: limit(PROGRAM_LIST_DEFAULT_LIMIT, PROGRAM_LIST_MAX_LIMIT)?, |
| 2990 | }), |
| 2991 | "describe" => Ok(Self::Describe { names: names()? }), |
| 2992 | "search" => { |
| 2993 | let query = optional_str(input, "query")?.unwrap_or_default(); |
| 2994 | Ok(Self::Search { |
| 2995 | namespace, |
| 2996 | query, |
| 2997 | regex: regex(query)?, |
| 2998 | limit: limit(PROGRAM_SEARCH_DEFAULT_LIMIT, PROGRAM_SEARCH_MAX_LIMIT)?, |
| 2999 | }) |
| 3000 | } |
| 3001 | "resolve" => Ok(Self::Resolve { |
| 3002 | namespace: required_str(input, "namespace")?, |
| 3003 | op: required_str(input, "op")?, |
| 3004 | }), |
| 3005 | "load" => { |
| 3006 | let names = names()?; |
| 3007 | if names.is_empty() || names.len() > PROGRAM_LOAD_MAX_NAMES { |
| 3008 | return Err(ToolError::invalid_input(format!( |
| 3009 | "tools.load takes 1 to {PROGRAM_LOAD_MAX_NAMES} names" |
| 3010 | ))); |
| 3011 | } |
| 3012 | Ok(Self::Load { names }) |
| 3013 | } |
| 3014 | other => Err(ToolError::invalid_input(format!( |
| 3015 | "Unsupported discovery mode '{other}'. Expected one of: list, search, describe, resolve, load" |
| 3016 | ))), |
| 3017 | } |
| 3018 | } |
| 3019 | } |
| 3020 | |
| 3021 | /// Describe-only `tool_search` for `execute_tools` programs: no activation, so |
| 3022 | /// the request's tool array and the session-pinned prefix stay exactly as they |
| 3023 | /// were. |
| 3024 | pub(crate) fn describe_tools_for_program( |
| 3025 | input: &serde_json::Value, |
| 3026 | catalog: &[Tool], |
| 3027 | ) -> Result<ToolResult, ToolError> { |
| 3028 | let include_schema = optional_bool(input, "include_schema", false)?; |
| 3029 | let discoverable: Vec<&Tool> = catalog |
| 3030 | .iter() |
| 3031 | .filter(|tool| discoverable_in_program(tool)) |
| 3032 | .collect(); |
| 3033 | let scoped = |namespace: Option<&str>| { |
| 3034 | let mut tools = discoverable.clone(); |
| 3035 | tools.retain(|tool| namespace.is_none_or(|ns| tool_matches_namespace(tool, ns))); |
| 3036 | tools.sort_by(|a, b| a.name.cmp(&b.name)); |
| 3037 | tools |
| 3038 | }; |
| 3039 | match ProgramDiscovery::parse(input)? { |
| 3040 | ProgramDiscovery::List { namespace, limit } => { |
| 3041 | let matched = scoped(namespace); |
| 3042 | let tools: Vec<Value> = matched |
| 3043 | .iter() |
| 3044 | .take(limit) |
| 3045 | .map(|tool| program_tool_entry(tool, false, false, include_schema)) |
| 3046 | .collect(); |
| 3047 | program_tools_result(&tools, matched.len()) |
| 3048 | } |
| 3049 | ProgramDiscovery::Describe { names } => { |
| 3050 | let tools: Vec<Value> = names |
| 3051 | .into_iter() |
| 3052 | .map(|name| match find_program_tool(&discoverable, name) { |
| 3053 | Some(tool) => program_tool_entry(tool, true, true, include_schema), |
| 3054 | None => json!({ |
| 3055 | "name": name, |
| 3056 | "missing": true, |
| 3057 | "suggestions": suggested_signatures(catalog, name), |
| 3058 | }), |
| 3059 | }) |
| 3060 | .collect(); |
| 3061 | program_tools_result(&tools, tools.len()) |
| 3062 | } |
| 3063 | ProgramDiscovery::Search { |
| 3064 | namespace, |
| 3065 | query, |
| 3066 | regex, |
| 3067 | limit, |
| 3068 | } => { |
| 3069 | let scoped = scoped(namespace); |
| 3070 | let names = if query.trim().is_empty() { |
| 3071 | scoped |
| 3072 | .iter() |
| 3073 | .take(limit) |
| 3074 | .map(|tool| tool.name.clone()) |
| 3075 | .collect() |
| 3076 | } else if regex { |
| 3077 | discover_tools_with_regex_in(scoped.iter().copied(), query, limit)? |
| 3078 | } else { |
| 3079 | discover_tools_with_bm25_like_in(scoped.iter().copied(), query, limit) |
| 3080 | }; |
| 3081 | let tools: Vec<Value> = names |
| 3082 | .iter() |
| 3083 | .filter_map(|name| find_program_tool(&scoped, name)) |
| 3084 | .map(|tool| program_tool_entry(tool, true, false, include_schema)) |
| 3085 | .collect(); |
| 3086 | program_tools_result(&tools, tools.len()) |
| 3087 | } |
| 3088 | ProgramDiscovery::Resolve { namespace, op } => { |
| 3089 | let name = resolve_program_tool(catalog, &discoverable, namespace, op)?; |
| 3090 | ToolResult::json(&json!({ "name": name })) |
| 3091 | .map_err(|error| ToolError::execution_failed(error.to_string())) |
| 3092 | } |
| 3093 | ProgramDiscovery::Load { .. } => Err(ToolError::not_available( |
| 3094 | "tools.load needs the session turn that serves this program; call the tool directly", |
| 3095 | )), |
| 3096 | } |
| 3097 | } |
| 3098 | |
| 3099 | /// Runs under the effective per-call policy, including an explicitly approved |
| 3100 | /// elevation. Shared-launcher platform limits still apply; this is not a |
| 3101 | /// persistent REPL. Code arrives on stdin so sandbox-private /tmp is harmless. |
| 3102 | pub(super) async fn execute_code_execution_tool( |
| 3103 | input: &serde_json::Value, |
| 3104 | workspace: &Path, |
| 3105 | context: &ToolContext, |
| 3106 | ) -> Result<ToolResult, ToolError> { |
| 3107 | let code = required_str(input, "code")?; |
| 3108 | let interpreter = codewhale_dependencies::Python::resolve().ok_or_else(|| { |
| 3109 | ToolError::execution_failed("code_execution: Python interpreter became unavailable") |
| 3110 | })?; |
| 3111 | let (program, mut args) = codewhale_dependencies::split_interpreter_spec(&interpreter); |
| 3112 | args.push("-".to_string()); |
| 3113 | let budget = Duration::from_secs(120); |
| 3114 | let mut cmd = |
| 3115 | crate::tools::shell::sandboxed_runner_command(context, &program, args, workspace, budget)?; |
| 3116 | // Match the UTF-8 decoder below, including Windows Python's piped output. |
| 3117 | cmd.env("PYTHONIOENCODING", "utf-8"); |
| 3118 | let output = tokio::time::timeout( |
| 3119 | budget, |
| 3120 | codewhale_runtime::process_tree::contained_output_with_input( |
| 3121 | &mut cmd, |
| 3122 | code.as_bytes().to_vec(), |
| 3123 | ), |
| 3124 | ) |
| 3125 | .await |
| 3126 | .map_err(|_| ToolError::Timeout { |
| 3127 | seconds: budget.as_secs(), |
| 3128 | }) |
| 3129 | .and_then(|res| res.map_err(|e| ToolError::execution_failed(e.to_string())))?; |
| 3130 | |
| 3131 | let stdout = String::from_utf8_lossy(&output.stdout).to_string(); |
| 3132 | let stderr = String::from_utf8_lossy(&output.stderr).to_string(); |
| 3133 | let return_code = output.status.code().unwrap_or(-1); |
| 3134 | let success = output.status.success(); |
| 3135 | let payload = json!({ |
| 3136 | "type": "code_execution_result", |
| 3137 | "stdout": stdout, |
| 3138 | "stderr": stderr, |
| 3139 | "return_code": return_code, |
| 3140 | "content": [], |
| 3141 | }); |
| 3142 | |
| 3143 | Ok(ToolResult { |
| 3144 | content: serde_json::to_string(&payload).unwrap_or_else(|_| payload.to_string()), |
| 3145 | success, |
| 3146 | metadata: Some(payload), |
| 3147 | }) |
| 3148 | } |
| 3149 | |
| 3150 | /// Mark strict intent on a complete active tool set. |
| 3151 | /// |
| 3152 | /// Each tool is evaluated independently: compatible schemas are marked strict, |
| 3153 | /// while incompatible schemas remain non-strict. Logical schemas are left |
| 3154 | /// unchanged; the selected route shapes strict parameters at projection time. |
| 3155 | /// Returns `true` only when every tool in the set can use strict mode. |
| 3156 | pub fn prepare_tools_for_strict_mode(tools: &mut [Tool]) -> bool { |
| 3157 | let mut all_strict = true; |
| 3158 | for tool in tools { |
| 3159 | if codewhale_models::schema_sanitize::strict_schema_supported(&tool.input_schema) { |
| 3160 | tool.strict = Some(true); |
| 3161 | } else { |
| 3162 | tool.strict = None; |
| 3163 | all_strict = false; |
| 3164 | } |
| 3165 | } |
| 3166 | all_strict |
| 3167 | } |
| 3168 | |
| 3169 | #[cfg(test)] |
| 3170 | #[path = "tool_catalog/tests.rs"] |
| 3171 | mod synthetic_name_tests; |
| 3172 | |
| 3173 | #[cfg(test)] |
| 3174 | #[test] |
| 3175 | fn plan_visibility_keeps_work_catalog_available() { |
| 3176 | use serde_json::json; |
| 3177 | let catalog: Vec<Tool> = ["bash", "Bash", "exec_shell", TERMINAL_RUN_NAME, "read"] |
| 3178 | .into_iter() |
| 3179 | .map(|name| { |
| 3180 | serde_json::from_value(json!({ |
| 3181 | "type": "function", |
| 3182 | "name": name, |
| 3183 | "description": name, |
| 3184 | "defer_loading": name != "read", |
| 3185 | "input_schema": {"type": "object"} |
| 3186 | })) |
| 3187 | .expect("tool definition") |
| 3188 | }) |
| 3189 | .collect(); |
| 3190 | let plan = mode_visible_catalog(&catalog, AppMode::Plan); |
| 3191 | assert_eq!( |
| 3192 | plan.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), |
| 3193 | ["read"] |
| 3194 | ); |
| 3195 | let mut active = HashSet::from(["bash".to_string(), "read".to_string()]); |
| 3196 | let request = active_tools_for_request(&plan, &active, true).expect("read remains available"); |
| 3197 | assert_eq!( |
| 3198 | request.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), |
| 3199 | ["read"] |
| 3200 | ); |
| 3201 | |
| 3202 | active.clear(); |
| 3203 | let query = json!({"query":"(?m)^bash$", "match":"regex"}); |
| 3204 | execute_tool_search(TOOL_SEARCH_NAME, &query, &plan, &mut active).expect("empty search"); |
| 3205 | assert!(active.is_empty()); |
| 3206 | |
| 3207 | let work = mode_visible_catalog(&catalog, AppMode::Agent); |
| 3208 | execute_tool_search(TOOL_SEARCH_NAME, &query, &work, &mut active).expect("Work search"); |
| 3209 | assert!(active.contains("bash")); |
| 3210 | active.clear(); |
| 3211 | let mut cache = ToolActivationCache::default(); |
| 3212 | let mut measure = |names: &[String]| ToolActivationCache::test_measure(&catalog, names); |
| 3213 | execute_tool_search_measured_for_mode( |
| 3214 | TOOL_SEARCH_NAME, |
| 3215 | &query, |
| 3216 | &catalog, |
| 3217 | AppMode::Agent, |
| 3218 | &mut active, |
| 3219 | &mut cache, |
| 3220 | &mut measure, |
| 3221 | ) |
| 3222 | .expect("cache a Work tool"); |
| 3223 | let result = execute_tool_search_measured_for_mode( |
| 3224 | TOOL_SEARCH_NAME, |
| 3225 | &query, |
| 3226 | &catalog, |
| 3227 | AppMode::Plan, |
| 3228 | &mut active, |
| 3229 | &mut cache, |
| 3230 | &mut measure, |
| 3231 | ) |
| 3232 | .expect("Plan search"); |
| 3233 | assert!(cache.names().any(|name| name == "bash")); |
| 3234 | let receipt = result.metadata.expect("search receipt"); |
| 3235 | assert_eq!(receipt["tool_references"], json!([])); |
| 3236 | assert_eq!(receipt["toolbox"]["active_deferred_tools"], json!([])); |
| 3237 | |
| 3238 | let request = active_tools_for_request(&work, &active, true).expect("Work tools"); |
| 3239 | assert!(request.iter().any(|tool| tool.name == "bash")); |
| 3240 | } |
| 3241 | |
| 3242 | #[cfg(test)] |
| 3243 | #[test] |
| 3244 | fn plan_program_load_hides_shell_and_work_load_restores_it() { |
| 3245 | use serde_json::json; |
| 3246 | let catalog: Vec<Tool> = ["bash", "exec_shell", "read"] |
| 3247 | .into_iter() |
| 3248 | .map(|name| { |
| 3249 | serde_json::from_value(json!({ |
| 3250 | "type": "function", |
| 3251 | "name": name, |
| 3252 | "description": name, |
| 3253 | "defer_loading": name != "read", |
| 3254 | "input_schema": {"type": "object"} |
| 3255 | })) |
| 3256 | .expect("tool definition") |
| 3257 | }) |
| 3258 | .collect(); |
| 3259 | let load = json!({"mode": "load", "names": ["bash", "exec_shell"]}); |
| 3260 | let mut active = HashSet::from(["read".to_string()]); |
| 3261 | let mut cache = ToolActivationCache::default(); |
| 3262 | let mut measure = |names: &[String]| ToolActivationCache::test_measure(&catalog, names); |
| 3263 | let plan = load_tools_for_program( |
| 3264 | &load, |
| 3265 | &catalog, |
| 3266 | AppMode::Plan, |
| 3267 | &mut active, |
| 3268 | &mut cache, |
| 3269 | &mut measure, |
| 3270 | ) |
| 3271 | .expect("Plan load"); |
| 3272 | let receipt = plan.metadata.expect("load receipt"); |
| 3273 | assert_eq!(receipt["tool_references"], json!([])); |
| 3274 | assert_eq!( |
| 3275 | receipt["unavailable_tool_references"] |
| 3276 | .as_array() |
| 3277 | .expect("unavailable references") |
| 3278 | .len(), |
| 3279 | 2 |
| 3280 | ); |
| 3281 | assert_eq!(active, HashSet::from(["read".to_string()])); |
| 3282 | assert_eq!(cache.names().count(), 0); |
| 3283 | |
| 3284 | let work = load_tools_for_program( |
| 3285 | &load, |
| 3286 | &catalog, |
| 3287 | AppMode::Agent, |
| 3288 | &mut active, |
| 3289 | &mut cache, |
| 3290 | &mut measure, |
| 3291 | ) |
| 3292 | .expect("Work load"); |
| 3293 | assert_eq!( |
| 3294 | work.metadata.expect("load receipt")["tool_references"], |
| 3295 | json!(["bash", "exec_shell"]) |
| 3296 | ); |
| 3297 | let request = active_tools_for_request(&catalog, &active, true).expect("Work tools"); |
| 3298 | assert!(request.iter().any(|tool| tool.name == "bash")); |
| 3299 | |
| 3300 | let plan_after_work = load_tools_for_program( |
| 3301 | &load, |
| 3302 | &catalog, |
| 3303 | AppMode::Plan, |
| 3304 | &mut active, |
| 3305 | &mut cache, |
| 3306 | &mut measure, |
| 3307 | ) |
| 3308 | .expect("Plan load after Work load"); |
| 3309 | let plan_after_work_receipt = plan_after_work.metadata.expect("load receipt"); |
| 3310 | assert_eq!(plan_after_work_receipt["tool_references"], json!([])); |
| 3311 | assert_eq!( |
| 3312 | plan_after_work_receipt["toolbox"]["active_deferred_tools"], |
| 3313 | json!([]) |
| 3314 | ); |
| 3315 | assert!(cache.names().any(|name| name == "bash")); |
| 3316 | |
| 3317 | let plan_visible = mode_visible_catalog(&catalog, AppMode::Plan); |
| 3318 | let listed = |
| 3319 | describe_tools_for_program(&json!({"mode": "list"}), &plan_visible).expect("Plan list"); |
| 3320 | assert!(!listed.content.contains("bash"), "{}", listed.content); |
| 3321 | |
| 3322 | let searched = |
| 3323 | describe_tools_for_program(&json!({"mode": "search", "query": "bash"}), &plan_visible) |
| 3324 | .expect("Plan search"); |
| 3325 | assert!(!searched.content.contains("bash"), "{}", searched.content); |
| 3326 | |
| 3327 | let described = describe_tools_for_program( |
| 3328 | &json!({"mode": "describe", "names": ["bash"]}), |
| 3329 | &plan_visible, |
| 3330 | ) |
| 3331 | .expect("Plan describe"); |
| 3332 | let described_json: Value = |
| 3333 | serde_json::from_str(&described.content).expect("Plan describe json"); |
| 3334 | assert_eq!(described_json["tools"][0]["missing"], json!(true)); |
| 3335 | assert_eq!(described_json["tools"][0]["suggestions"], json!([])); |
| 3336 | } |
| 3337 |