From c03d12c75e66e55f2661da65b820d2f05e91c5e8 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Mon, 23 Nov 2026 16:45:23 +0100 Subject: [PATCH] refactor(engine): split tool schema selection and prompts --- rustcode/engine/src/tools/schema.rs | 2058 +---------------- .../schema/mcp_read_classification_tests.rs | 87 + .../engine/src/tools/schema/mcp_selection.rs | 989 ++++++++ rustcode/engine/src/tools/schema/prompts.rs | 623 +++++ .../src/tools/schema/response_limit_tests.rs | 58 + .../src/tools/schema/schema_budget_tests.rs | 261 +++ scripts/comment-baseline.txt | 7 +- scripts/rust-size-baseline.txt | 1 - 8 files changed, 2057 insertions(+), 2027 deletions(-) create mode 100644 rustcode/engine/src/tools/schema/mcp_read_classification_tests.rs create mode 100644 rustcode/engine/src/tools/schema/mcp_selection.rs create mode 100644 rustcode/engine/src/tools/schema/prompts.rs create mode 100644 rustcode/engine/src/tools/schema/response_limit_tests.rs create mode 100644 rustcode/engine/src/tools/schema/schema_budget_tests.rs diff --git a/rustcode/engine/src/tools/schema.rs b/rustcode/engine/src/tools/schema.rs index 012f5145b..42cf65aa4 100644 --- a/rustcode/engine/src/tools/schema.rs +++ b/rustcode/engine/src/tools/schema.rs @@ -1,3 +1,33 @@ +mod mcp_selection; +pub(super) use mcp_selection::select_mcp_tools_for_context_with_anchors; +#[cfg(test)] +pub(crate) use mcp_selection::select_mcp_tools_for_context_with_sticky_and_reservations_in_phase; +#[cfg(test)] +pub(super) use mcp_selection::{ + select_mcp_tools_for_context, select_mcp_tools_for_context_in_phase, + select_mcp_tools_for_context_with_raw_names, select_mcp_tools_for_context_with_sticky, +}; + +mod prompts; +#[cfg(test)] +use prompts::textual_mcp_listing; +pub use prompts::tool_system_prompt; +pub(crate) use prompts::{ + ANTIGRAVITY_OUTPUT_NOTE, append_output_style_hint, append_preview_hint, append_smart_ui_hint, + append_tool_response_limit, append_tool_response_policy, append_visualization_hint, + codex_windows_sandbox_note, harness_instructions, output_style_hint, runtime_reminder, + session_title_turn_hint, skills_reminder, smart_ui_hint, taught_visualization_hint, + tool_system_prompt_for_policy, visualization_prompt_hint, +}; +#[cfg(test)] +pub(crate) use prompts::{BASE_PROMPT_MAX_BYTES, BASE_PROMPT_MAX_TOKENS}; +#[cfg(test)] +pub(crate) use prompts::{ + CODEX_WINDOWS_SANDBOX_NOTE, OUTPUT_STYLE_PROMPT_HINT, OUTPUT_STYLE_SMART_UI_HINT, + OUTPUT_STYLE_VIZ_HINT, SMART_UI_HARNESS_HINT, SMART_UI_OFF_PROMPT_HINT, SMART_UI_PROMPT_HINT, + VISUALIZATION_PROMPT_HINT, VISUALIZATION_PROMPT_HINT_LEVEL_2, harness_output_style, +}; + use super::{TOOLS, ToolCapability, allowed_in_plan_mode}; use serde_json::Value; use std::collections::HashMap; @@ -1408,994 +1438,6 @@ pub(super) fn provider_compatible_schema(mut schema: Value) -> Value { schema } -fn context_terms(messages: &[Value]) -> std::collections::HashSet { - // Function words say nothing about which tool is wanted, and nearly every - // tool description contains a few of them: "and", "of" and "can" alone - // cleared the relevance threshold and filled the menu for any prompt. - use super::mcp_discovery::STOP_WORDS; - let mut terms = std::collections::HashSet::new(); - for message in messages { - let role = message.get("role").and_then(Value::as_str).unwrap_or(""); - if !matches!(role, "user" | "assistant") { - continue; - } - // A `user` row the harness wrote (a tool result rendered as text, a - // tool attachment, a runtime notice) is tool output, not the user's - // words: a `manage_mcp_servers` listing there named every server. - if role == "user" && !crate::network::messages::is_user_turn_boundary(message) { - continue; - } - let content = message.get("content").and_then(Value::as_str).unwrap_or(""); - let content = content.split("").next().unwrap_or(""); - let mut message_terms = std::collections::HashSet::new(); - for token in content - .split(|ch: char| !ch.is_ascii_alphanumeric()) - .map(str::to_ascii_lowercase) - { - if token.len() >= 2 && !STOP_WORDS.contains(&token.as_str()) { - if matches!(token.as_str(), "mail" | "mails" | "emails") { - message_terms.insert("email".to_string()); - } - message_terms.insert(token); - } - } - if message_terms.contains("email") - && ["latest", "newest", "recent"] - .iter() - .any(|term| message_terms.contains(*term)) - { - message_terms.insert("list".to_string()); - } - terms.extend(message_terms); - // Structured tool turns often have an empty assistant content field. - // Keep their names in the relevance set so the next request retains - // the exact schema needed to continue the active tool exchange. - if let Some(calls) = message.get("tool_calls").and_then(Value::as_array) { - for call in calls { - if let Some(name) = call - .get("function") - .and_then(|function| function.get("name")) - .and_then(Value::as_str) - .or_else(|| call.get("name").and_then(Value::as_str)) - { - terms.insert(name.to_ascii_lowercase()); - } - } - } - } - terms -} - -fn tool_name_was_used(name: &str, messages: &[Value]) -> bool { - messages.iter().any(|message| { - message - .get("tool_calls") - .and_then(Value::as_array) - .is_some_and(|calls| { - calls.iter().any(|call| { - call.get("function") - .and_then(|function| function.get("name")) - .and_then(Value::as_str) - .is_some_and(|call_name| call_name.eq_ignore_ascii_case(name)) - || call - .get("name") - .and_then(Value::as_str) - .is_some_and(|call_name| call_name.eq_ignore_ascii_case(name)) - }) - }) - }) -} - -fn user_message_mentions_name(messages: &[Value], name: &str) -> bool { - let name = name.to_ascii_lowercase(); - messages.iter().any(|message| { - // Only what the user typed. A tool result the request carries as a - // `user` row (`…`) is not: a `manage_mcp_servers` listing - // rendered that way named every configured server, and each server's - // tools were then admitted as if the user had asked for them. - if !crate::network::messages::is_user_turn_boundary(message) { - return false; - } - let content = message - .get("content") - .and_then(Value::as_str) - .unwrap_or("") - .split("") - .next() - .unwrap_or("") - .to_ascii_lowercase(); - let mut offset = 0; - while let Some(found) = content[offset..].find(&name) { - let start = offset + found; - let end = start + name.len(); - let before_is_name_char = content[..start] - .chars() - .next_back() - .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); - let after_is_name_char = content[end..] - .chars() - .next() - .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); - if !before_is_name_char && !after_is_name_char { - return true; - } - offset = end; - } - false - }) -} - -fn canonical_mcp_server(name: &str) -> Option<&str> { - name.strip_prefix("mcp__")? - .split_once("__") - .map(|(server, _)| server) -} - -fn user_mentions_mcp_server(messages: &[Value], server: &str) -> bool { - user_message_mentions_name(messages, server) - || user_message_mentions_name(messages, &format!("{server}_mcp")) -} - -/// Keep schemas returned by completed MCP discovery calls in the next -/// request's tool block. The discovery result itself is tool output, which -/// relevance scoring intentionally ignores; without this hint, a tool found -/// by query could be omitted before the model gets a chance to call it. -/// -/// Every discovery call in the request counts, newest first: binding only -/// the latest one let finding tool B evict tool A, and binding only the -/// current turn's dropped what an earlier turn found, so the model listed -/// the same tools again on every turn (#2502). -fn mcp_tools_selected_by_discovery_calls( - tools: &[(String, String, Value)], - owners: &[String], - raw_names: &[String], - messages: &[Value], -) -> Vec { - let docs = tools - .iter() - .zip(owners) - .zip(raw_names) - .map( - |(((name, description, _), owner), raw_name)| super::mcp_discovery::McpToolDoc { - server: owner, - raw_name, - advertised: name, - description, - }, - ) - .collect::>(); - super::mcp_discovery::bound_by_discovery_calls(&docs, messages) - .into_iter() - .map(|index| tools[index].0.clone()) - .collect() -} - -/// Find MCP schemas named by the user, including every tool from a named MCP -/// server. This intentionally reads user messages only: assistant/tool output -/// can describe a tool without being an instruction to make its whole server -/// sticky. -/// -/// Returns the tools asked for one by one, in the order they must be admitted -/// (a discovery result first, then names the user wrote), and separately the -/// tools that are only wanted because their server was named. A server can -/// have more tools than a request may carry, so those are ranked by the -/// caller instead of all being treated as equally required. -fn explicitly_requested_mcp_tool_names( - tools: &[(String, String, Value)], - owners: &[String], - raw_names: &[String], - messages: &[Value], -) -> (Vec, std::collections::HashSet) { - let mut named = mcp_tools_selected_by_discovery_calls(tools, owners, raw_names, messages); - let mut requested = std::collections::HashSet::new(); - for (name, _, _) in tools { - if user_message_mentions_name(messages, name) { - if !named.contains(name) { - named.push(name.clone()); - } - } else if canonical_mcp_server(name) - .is_some_and(|server| user_mentions_mcp_server(messages, server)) - { - requested.insert(name.clone()); - } - } - - // Unique MCP tool names are intentionally sent without a server prefix. - // Recover their server here so an explicit server name still pins them. - if let Ok(registry) = crate::mcp::get_mcp_registry().lock() { - let mut clients = registry.values().cloned().collect::>(); - clients.sort_by(|left, right| left.name.cmp(&right.name)); - for client in &clients { - let server_requested = user_mentions_mcp_server(messages, &client.name) - || user_message_mentions_name( - messages, - &client - .name - .chars() - .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' }) - .collect::(), - ); - if !server_requested { - continue; - } - let Ok(client_tools) = client.get_tools() else { - continue; - }; - for tool in client_tools { - let Some(raw_name) = tool.get("name").and_then(Value::as_str) else { - continue; - }; - let provider_name = - mcp_canonical_name_for_clients(&client.name, raw_name, &clients); - if tools.iter().any(|(name, _, _)| name == &provider_name) - || tools.iter().any(|(name, _, _)| name == raw_name) - { - requested.insert( - tools - .iter() - .find(|(name, _, _)| name == &provider_name || name == raw_name) - .map(|(name, _, _)| name.clone()) - .unwrap_or(provider_name), - ); - } - } - } - } - requested.retain(|name| !named.contains(name)); - (named, requested) -} - -/// Words that say what to do or name a kind of thing nearly every messaging, -/// file or task server offers. They say nothing about *which* tool is meant: -/// "chat", "msg", "reply" and "before" in a Minecraft permissions transcript -/// pulled a Snapchat reader into the menu (#2576). Compared after stemming. -const GENERIC_RELEVANCE_TERMS: &[&str] = &[ - "add", - "after", - "all", - "before", - "chat", - "check", - "clear", - "close", - "com", - "conversation", - "create", - "data", - "default", - "delete", - "detail", - "dm", - "entry", - "fetch", - "fill", - "find", - "first", - "get", - "http", - "https", - "id", - "info", - "item", - "last", - "latest", - "limit", - "list", - "load", - "member", - "message", - "msg", - "name", - "net", - "new", - "next", - "open", - "org", - "page", - "read", - "recent", - "remove", - "reply", - "result", - "run", - "save", - "search", - "send", - "set", - "show", - "start", - "status", - "stop", - "take", - "text", - "update", - "user", - "value", - "view", - "write", - "www", -]; - -/// How strongly the user's words point at one MCP tool. Only the tool's name -/// and description count: its schema's parameter names (`before`, `limit`, -/// `chat_id`) are shared by unrelated tools and are not what a user asks for. -fn mcp_tool_relevance( - name: &str, - description: &str, - terms: &std::collections::HashSet, -) -> usize { - mcp_tool_score(name, description, terms, false) -} - -/// Rank tools of a server the user already named. There the generic verbs -/// are what tells `send_chat_message` from `list_chats`, so they count. -fn mcp_tool_rank_within_server( - name: &str, - description: &str, - terms: &std::collections::HashSet, -) -> usize { - mcp_tool_score(name, description, terms, true) -} - -/// Whether one of `terms` (not a generic one) is a word of the tool's name. -/// Description words alone are weak: "issue" in a sentence about "issue -/// tracking" or "token" in an auth note matched tools nobody asked for. -fn mcp_tool_name_matches(name: &str, terms: &std::collections::HashSet) -> bool { - use super::mcp_discovery::{stem, tokens}; - let name = name.strip_prefix("mcp__").unwrap_or(name); - let name_terms = tokens(name) - .into_iter() - .collect::>(); - terms - .iter() - .map(|term| stem(term)) - .any(|term| !GENERIC_RELEVANCE_TERMS.contains(&term.as_str()) && name_terms.contains(&term)) -} - -fn mcp_tool_score( - name: &str, - description: &str, - terms: &std::collections::HashSet, - count_generic: bool, -) -> usize { - use super::mcp_discovery::{stem, tokens}; - // `mcp__` is a transport prefix, not evidence that every MCP tool is - // relevant whenever a user names an MCP server. The tokenizer is the one - // discovery uses, so `snake_case`, `camelCase` and plurals match alike. - let name = name.strip_prefix("mcp__").unwrap_or(name); - let name_terms = tokens(name) - .into_iter() - .collect::>(); - let description_terms = tokens(description) - .into_iter() - .collect::>(); - let mut score = 0; - let mut seen = std::collections::HashSet::new(); - for term in terms { - // The prompt may carry the verb inflected ("takes" for `take_…`). - let term = stem(term); - let generic = GENERIC_RELEVANCE_TERMS.contains(&term.as_str()); - if (generic && !count_generic) || !seen.insert(term.clone()) { - continue; - } - if name_terms.contains(&term) { - score += if generic { 3 } else { 8 }; - } else if description_terms.contains(&term) { - score += 3; - } - } - score -} - -#[cfg(test)] -pub(super) fn select_mcp_tools_for_context_in_phase( - tools: &[(String, String, Value)], - messages: &[Value], - phase: ToolSchemaPhase, -) -> (Vec, McpSchemaSelectionStats) { - select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( - tools, - &[], - &[], - messages, - &[], - phase, - ) -} - -/// Which candidate bucket admitted a tool into this request's `tools` block. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Admitted { - /// Carried over from the previous request's pinned menu. - Retained, - Requested, - Previous, - Relevant, -} - -#[cfg(test)] -pub(crate) fn select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( - tools: &[(String, String, Value)], - owners: &[String], - always_include_servers: &[String], - messages: &[Value], - sticky_names: &[String], - phase: ToolSchemaPhase, -) -> (Vec, McpSchemaSelectionStats) { - let raw_names = tools - .iter() - .zip(owners) - .map(|((name, _, _), owner)| { - name.strip_prefix(&mcp_canonical_name(owner, "")) - .unwrap_or(name) - .to_string() - }) - .collect::>(); - select_mcp_tools_for_context_with_raw_names( - tools, - owners, - &raw_names, - always_include_servers, - messages, - sticky_names, - phase, - ) -} - -#[cfg(test)] -pub(super) fn select_mcp_tools_for_context_with_raw_names( - tools: &[(String, String, Value)], - owners: &[String], - raw_names: &[String], - always_include_servers: &[String], - messages: &[Value], - sticky_names: &[String], - phase: ToolSchemaPhase, -) -> (Vec, McpSchemaSelectionStats) { - select_mcp_tools_for_context_with_anchors( - tools, - owners, - raw_names, - always_include_servers, - messages, - sticky_names, - &McpSessionAnchors::default(), - phase, - ) -} - -/// The server a tool belongs to: its registry owner, else the server in its -/// canonical `mcp__server__tool` name. -fn mcp_tool_server<'a>( - tools: &'a [(String, String, Value)], - owners: &'a [String], - index: usize, -) -> Option<&'a str> { - owners - .get(index) - .map(String::as_str) - .filter(|owner| !owner.is_empty()) - .or_else(|| canonical_mcp_server(&tools[index].0)) -} - -#[allow(clippy::too_many_arguments)] -pub(super) fn select_mcp_tools_for_context_with_anchors( - tools: &[(String, String, Value)], - owners: &[String], - raw_names: &[String], - always_include_servers: &[String], - messages: &[Value], - sticky_names: &[String], - anchors: &McpSessionAnchors, - phase: ToolSchemaPhase, -) -> (Vec, McpSchemaSelectionStats) { - // Once a menu is pinned, only what the user wrote may add to it. Assistant - // prose, tool calls and harness notices grow every round, and each tool - // they pulled in rewrote the `tools` block the provider had cached. - let authored = messages - .iter() - .filter(|message| crate::network::messages::is_user_turn_boundary(message)) - .cloned() - .collect::>(); - let terms = if sticky_names.is_empty() { - context_terms(messages) - } else { - context_terms(&authored) - }; - // The pinned menu outlives the turn, so a full one would never admit a - // tool by relevance again. What the newest user message points at is - // therefore seated ahead of the pin. It is the same on every round of a - // turn, so it changes the menu at most once per user message. - let fresh_terms = match authored.last() { - Some(latest) if !sticky_names.is_empty() => context_terms(std::slice::from_ref(latest)), - _ => std::collections::HashSet::new(), - }; - let (mut named, server_wide) = - explicitly_requested_mcp_tool_names(tools, owners, raw_names, messages); - // What the user asked for earlier in the session stays asked for after a - // compaction archived the message that said so (#2576). - for wanted in &anchors.requested { - if tools.iter().any(|(name, _, _)| name == wanted) && !named.contains(wanted) { - named.push(wanted.clone()); - } - } - let mut requested = named - .iter() - .filter_map(|wanted| tools.iter().position(|(name, _, _)| name == wanted)) - .collect::>(); - let mut server_requested = Vec::new(); - let mut previous = Vec::new(); - let mut relevant = Vec::new(); - let mut fresh = Vec::new(); - for (index, (name, description, _)) in tools.iter().enumerate() { - if named.contains(name) { - continue; - } - if !fresh_terms.is_empty() { - let score = mcp_tool_relevance(name, description, &fresh_terms); - if score >= MCP_RELEVANCE_THRESHOLD { - fresh.push((index, score)); - } - } - // The model may call a tool by its advertised or its canonical - // `mcp__server__tool` name; either is a use (#2502). A bare raw name - // that is not the advertised one could be a built-in's, so it is not. - // A call a compaction archived still counts (#2576). - let raw = raw_names.get(index).map(String::as_str).unwrap_or(name); - let canonical = owners - .get(index) - .map(|owner| mcp_canonical_name(owner, raw)) - .unwrap_or_else(|| name.clone()); - let was_used = anchors.used.contains(name) - || tool_name_was_used(name, messages) - || tool_name_was_used(&canonical, messages); - if server_wide.contains(name) { - server_requested.push(( - index, - was_used, - mcp_tool_rank_within_server(name, description, &terms), - )); - } else if was_used { - previous.push(index); - } else { - let score = mcp_tool_relevance(name, description, &terms); - // A single generic description word such as "result", "file", or - // "project" must not pull a large MCP suite into an unrelated - // request. Exact name terms score eight; two strong description - // matches score six. - if score >= MCP_RELEVANCE_THRESHOLD { - relevant.push((index, score)); - } - } - } - - // Relevance from the transcript may only widen the menu within servers the - // session has already engaged: one it used, one the user or a discovery - // call named, or a reserved one. A server new to the session is admitted - // only by what the user just wrote ("check my latest mails"), never by - // words older turns, assistant prose or a compaction left behind; the - // model can find anything else with `list_mcp_tools` (#2576). - let latest_terms = authored - .last() - .map(|latest| context_terms(std::slice::from_ref(latest))) - .unwrap_or_default(); - let mut engaged_servers = std::collections::HashSet::new(); - for index in requested - .iter() - .chain(server_requested.iter().map(|(index, _, _)| index)) - .chain(previous.iter()) - .copied() - { - if let Some(server) = mcp_tool_server(tools, owners, index) { - engaged_servers.insert(server); - } - } - for index in 0..tools.len() { - if let Some(server) = mcp_tool_server(tools, owners, index) { - if always_include_servers - .iter() - .any(|reserved| reserved == server) - || user_mentions_mcp_server(messages, server) - { - engaged_servers.insert(server); - } - } - } - for ranked in [&mut relevant, &mut fresh] { - ranked.retain(|(index, _)| { - mcp_tool_server(tools, owners, *index) - .is_some_and(|server| engaged_servers.contains(server)) - || (mcp_tool_relevance(&tools[*index].0, &tools[*index].1, &latest_terms) - >= MCP_RELEVANCE_THRESHOLD - // A server new to the session needs the message to name - // what the tool is; description words alone added an - // unrelated tool and rewrote the cached `tools` block. - && mcp_tool_name_matches(&tools[*index].0, &latest_terms)) - }); - // Two servers offering the same tool name with the same score are an - // ambiguous match: neither is admitted rather than the one whose - // server sorts first (#2576). - let snapshot = ranked.clone(); - ranked.retain(|(index, score)| { - let raw = raw_names - .get(*index) - .map(String::as_str) - .unwrap_or(&tools[*index].0); - !snapshot.iter().any(|(other, other_score)| { - other != index - && other_score == score - && raw_names - .get(*other) - .map(String::as_str) - .unwrap_or(&tools[*other].0) - == raw - && mcp_tool_server(tools, owners, *other) - != mcp_tool_server(tools, owners, *index) - }) - }); - } - // A named server can have more tools than the request may carry. The ones - // already in use and the ones the request's words point at go first; - // alphabetical order used to drop `send_…` behind `get_…` and `list_…`. - server_requested.sort_by(|left, right| { - right - .1 - .cmp(&left.1) - .then_with(|| right.2.cmp(&left.2)) - .then_with(|| tools[left.0].0.cmp(&tools[right.0].0)) - }); - requested.extend(server_requested.into_iter().map(|(index, _, _)| index)); - previous.sort_by(|left, right| tools[*left].0.cmp(&tools[*right].0)); - for ranked in [&mut relevant, &mut fresh] { - // Tied duplicates across servers were dropped above, so the name order - // here only seats two different tools, never picks a server. - ranked.sort_by(|(left_index, left_score), (right_index, right_score)| { - right_score - .cmp(left_score) - .then_with(|| tools[*left_index].0.cmp(&tools[*right_index].0)) - }); - } - - // Reserve complete configured server toolsets first. A reservation is - // all-or-none: if adding the complete set would exceed either hard limit, - // the server is reported as rejected and none of its tools are bound for - // this request. - let budget_bytes = mcp_schema_budget_bytes(); - let mut selected = Vec::new(); - let mut selected_indices = std::collections::HashSet::new(); - let mut rejected_indices = std::collections::HashSet::new(); - let mut selected_schema_bytes: usize = 0; - let mut per_server_bytes: std::collections::HashMap<&str, usize> = - std::collections::HashMap::new(); - let mut schema_budget_exhausted = false; - let mut reserved_servers = Vec::new(); - let mut rejected_reservations = Vec::new(); - let mut seen_servers = std::collections::HashSet::new(); - for server in always_include_servers { - if !seen_servers.insert(server.as_str()) { - continue; - } - let group = owners - .iter() - .enumerate() - .filter_map(|(index, owner)| (owner == server).then_some(index)) - .collect::>(); - if group.is_empty() { - continue; - } - let group_bytes = group.iter().fold(0usize, |total, index| { - let (name, description, schema) = &tools[*index]; - total.saturating_add(mcp_schema_bytes(name, description, schema)) - }); - // A single heavy server must not starve the rest of the catalog. - if group_bytes > MAX_MCP_PER_SERVER_SCHEMA_BYTES { - rejected_reservations.push(server.clone()); - schema_budget_exhausted = true; - rejected_indices.extend(group); - continue; - } - let count_fits = selected.len().saturating_add(group.len()) <= MAX_MCP_NATIVE_SCHEMAS; - let bytes_fit = selected_schema_bytes.saturating_add(group_bytes) <= budget_bytes; - if count_fits && bytes_fit { - for index in group { - if selected_indices.insert(index) { - selected.push(index); - } - } - selected_schema_bytes = selected_schema_bytes.saturating_add(group_bytes); - per_server_bytes.insert(server.as_str(), group_bytes); - reserved_servers.push(server.clone()); - } else { - rejected_reservations.push(server.clone()); - schema_budget_exhausted |= !bytes_fit; - rejected_indices.extend(group); - } - } - - // Explicitly requested tools stay first: naming one is a hard requirement, so it - // must outrank a pinned menu from a previous turn. Retention then follows. - // Because the pinned menu is itself the previous request's whole `tools` block, - // a requested name is almost always already pinned, so this ordering cannot - // shrink the pinned set — it only re-seats its members. Chaining retention last - // instead left it as a mere preference competing for an already-full budget, - // which is why consecutive requests selected disjoint name sets. (#1591) - let mut candidates = Vec::new(); - candidates.extend( - requested - .iter() - .copied() - .filter(|index| !rejected_indices.contains(index)) - .map(|index| (index, Admitted::Requested)), - ); - candidates.extend( - fresh - .iter() - .map(|(index, _)| *index) - .filter(|index| !rejected_indices.contains(index)) - .map(|index| { - // A pinned tool the message also points at was retained, not - // newly admitted; only its seat moved. - if sticky_names.contains(&tools[index].0) { - (index, Admitted::Retained) - } else { - (index, Admitted::Relevant) - } - }), - ); - // Tools the model has called in this conversation outrank the rest of - // the pin: a full pin of tools nobody used kept a used one out, and the - // model listed it again every turn (#2502). A used tool is almost always - // pinned already, so this rarely changes the menu. - candidates.extend( - previous - .iter() - .copied() - .filter(|index| !rejected_indices.contains(index)) - // A used tool is admitted for being used, pinned or not, so the - // log says why it is there (#2576). - .map(|index| (index, Admitted::Previous)), - ); - candidates.extend( - sticky_names - .iter() - .filter_map(|sticky| tools.iter().position(|(name, _, _)| name == sticky)) - .filter(|index| !rejected_indices.contains(index)) - .map(|index| (index, Admitted::Retained)), - ); - candidates.extend( - relevant - .iter() - .map(|(index, _)| *index) - .filter(|index| !rejected_indices.contains(index)) - .map(|index| (index, Admitted::Relevant)), - ); - // Attribute by the bucket that actually admitted the tool. Deriving the - // counts from the candidate lists instead skipped tools a reservation had - // already inserted, so a `previous` tool admitted by a reservation was - // selected but never reported as previously used. (#1591) - let mut admitted = std::collections::HashMap::new(); - for (index, bucket) in candidates { - if selected.len() >= MAX_MCP_NATIVE_SCHEMAS { - break; - } - if !selected_indices.insert(index) { - continue; - } - let (name, description, schema) = &tools[index]; - let bytes = mcp_schema_bytes(name, description, schema); - if selected_schema_bytes.saturating_add(bytes) > budget_bytes { - selected_indices.remove(&index); - schema_budget_exhausted = true; - continue; - } - // Per-server fairness: an explicit request always wins, but relevance - // alone must not let one heavy server consume the shared budget. - let owner = owners.get(index).map(String::as_str).unwrap_or(""); - let server_bytes = per_server_bytes.get(owner).copied().unwrap_or(0); - if bucket != Admitted::Requested - && server_bytes.saturating_add(bytes) > MAX_MCP_PER_SERVER_SCHEMA_BYTES - { - selected_indices.remove(&index); - schema_budget_exhausted = true; - continue; - } - admitted.entry(index).or_insert(bucket); - selected.push(index); - selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); - if !owner.is_empty() { - per_server_bytes.insert(owner, server_bytes.saturating_add(bytes)); - } - } - - let mut fallback_count = 0; - if selected.is_empty() && phase == ToolSchemaPhase::Established { - for preferred in MCP_DISCOVERY_CORE { - if selected.len() >= MCP_DISCOVERY_FALLBACK_COUNT { - break; - } - if let Some(index) = tools.iter().position(|(name, _, _)| name == preferred) { - if rejected_indices.contains(&index) { - continue; - } - if !selected_indices.insert(index) { - continue; - } - let (name, description, schema) = &tools[index]; - let bytes = mcp_schema_bytes(name, description, schema); - if selected_schema_bytes.saturating_add(bytes) <= budget_bytes { - selected.push(index); - selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); - } else { - selected_indices.remove(&index); - schema_budget_exhausted = true; - } - } - } - fallback_count = selected.len(); - } - - // Sticky and explicit tools can be promoted within the already selected - // surface. Reserved server tools stay first so a follow-up cannot break a - // complete configured reservation. - if !sticky_names.is_empty() { - let reserved_indices = owners - .iter() - .enumerate() - .filter_map(|(index, owner)| reserved_servers.contains(owner).then_some(index)) - .filter(|index| selected_indices.contains(index)) - .collect::>(); - let sticky_indices = sticky_names - .iter() - .filter_map(|name| tools.iter().position(|(tool_name, _, _)| tool_name == name)) - .collect::>(); - let mut prioritized = Vec::with_capacity(selected.len()); - let mut prioritized_set = std::collections::HashSet::with_capacity(selected.len()); - for index in reserved_indices - .into_iter() - .chain(requested.iter().copied()) - .chain(sticky_indices) - .chain(selected.iter().copied()) - { - if prioritized.len() >= MAX_MCP_NATIVE_SCHEMAS { - break; - } - if selected_indices.contains(&index) && prioritized_set.insert(index) { - prioritized.push(index); - } - } - selected = prioritized; - selected_schema_bytes = 0; - let mut within_budget = Vec::with_capacity(selected.len()); - for index in selected { - let (name, description, schema) = &tools[index]; - let bytes = mcp_schema_bytes(name, description, schema); - if selected_schema_bytes.saturating_add(bytes) > budget_bytes { - schema_budget_exhausted = true; - continue; - } - selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); - within_budget.push(index); - } - selected = within_budget; - } - - // Emit in a stable order: the pinned menu keeps its seats in the order the - // previous request sent them, and a newly admitted tool goes after them. - // Sorting by catalog position put a new tool in the middle, which changed - // every byte after it and cost the provider's cached prefix. - let mut seen = std::collections::HashSet::with_capacity(selected.len()); - selected.retain(|index| seen.insert(*index)); - let pinned_seat = |index: usize| { - sticky_names - .iter() - .position(|name| name == &tools[index].0) - .unwrap_or(usize::MAX) - }; - selected.sort_by_key(|index| (pinned_seat(*index), *index)); - debug_assert!(selected.len() <= MAX_MCP_NATIVE_SCHEMAS); - let selected_set = selected - .iter() - .copied() - .collect::>(); - let selected_names = selected - .iter() - .map(|index| tools[*index].0.clone()) - .collect::>(); - let omitted_names = tools - .iter() - .enumerate() - .filter_map(|(index, (name, _, _))| { - (!selected_set.contains(&index)).then_some(name.clone()) - }) - .collect::>(); - // Each selected tool under the one bucket that admitted it; the counts - // are the sizes of these lists, so they always add up to `selected`. - let mut admitted_by: std::collections::BTreeMap<&'static str, Vec> = - std::collections::BTreeMap::new(); - for index in &selected { - // Having been called is the strongest reason a tool is offered, so a - // used tool is reported as such unless the user asked for it by name. - let used = previous.contains(index) && admitted.get(index) != Some(&Admitted::Requested); - let bucket = match admitted.get(index) { - _ if used => "previously_used", - Some(Admitted::Requested) => "requested", - Some(Admitted::Previous) => "previously_used", - Some(Admitted::Relevant) => "relevant", - Some(Admitted::Retained) => "retained", - None if mcp_tool_server(tools, owners, *index) - .is_some_and(|server| reserved_servers.iter().any(|name| name == server)) => - { - "reserved" - } - None => "fallback", - }; - admitted_by - .entry(bucket) - .or_default() - .push(tools[*index].0.clone()); - } - let bucket_len = |bucket: &str| admitted_by.get(bucket).map_or(0, Vec::len); - let stats = McpSchemaSelectionStats { - available: tools.len(), - selected: selected.len(), - requested: bucket_len("requested"), - relevant: bucket_len("relevant"), - previously_used: bucket_len("previously_used"), - fallback: fallback_count.min(selected.len()), - omitted: tools.len().saturating_sub(selected.len()), - selected_names, - omitted_names, - reserved_servers, - rejected_reservations, - phase, - mcp_schema_bytes: selected_schema_bytes, - mcp_schema_budget_bytes: budget_bytes, - schema_budget_exhausted, - admitted_by, - ..Default::default() - }; - (selected, stats) -} - -#[cfg(test)] -pub(super) fn select_mcp_tools_for_context( - tools: &[(String, String, Value)], - messages: &[Value], -) -> (Vec, McpSchemaSelectionStats) { - select_mcp_tools_for_context_in_phase(tools, messages, ToolSchemaPhase::Established) -} - -#[cfg(test)] -pub(super) fn select_mcp_tools_for_context_with_sticky_in_phase( - tools: &[(String, String, Value)], - messages: &[Value], - sticky_names: &[String], - phase: ToolSchemaPhase, -) -> (Vec, McpSchemaSelectionStats) { - select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( - tools, - &[], - &[], - messages, - sticky_names, - phase, - ) -} - -#[cfg(test)] -pub(super) fn select_mcp_tools_for_context_with_sticky( - tools: &[(String, String, Value)], - messages: &[Value], - sticky_names: &[String], -) -> (Vec, McpSchemaSelectionStats) { - select_mcp_tools_for_context_with_sticky_in_phase( - tools, - messages, - sticky_names, - ToolSchemaPhase::Established, - ) -} - #[cfg(test)] pub(crate) fn native_tools_schema_for_context( policy: ToolSchemaPolicy, @@ -2630,1045 +1672,11 @@ fn agent_tool_schema(name: &str) -> Value { } } -/// Regression budget for the invariant prompt prefix. Tool schemas are sent -/// separately for ApiNative requests and are intentionally not counted here. #[cfg(test)] -pub(crate) const BASE_PROMPT_MAX_BYTES: usize = 4_700; -#[cfg(test)] -pub(crate) const BASE_PROMPT_MAX_TOKENS: usize = 1_020; - -/// Append the resolved execution policy after the cached, profile-independent -/// prompt so model switches cannot retain another profile's mutation limit. -pub(crate) fn append_tool_response_limit(prompt: &mut String, max_mutating_calls: usize) { - append_tool_response_policy( - prompt, - crate::config::ToolSchedulingPolicy { - max_mutating_calls, - ..Default::default() - }, - ); -} - -pub(crate) fn append_tool_response_policy( - prompt: &mut String, - policy: crate::config::ToolSchedulingPolicy, -) { - use std::fmt::Write; - - if policy.allow_batching { - write!( - prompt, - "\n\n# Tool response limit\n\ -This trusted profile permits a bounded batch of up to {} read-only calls and {} workspace-changing calls in one assistant response. \ -Control-plane calls first, reads follow; workspace changes grounded and sequential; never assume an unexecuted call ran. \ -Read-only calls do not consume the workspace-changing limit. \ -Calls beyond the limit are held by the harness and executed automatically in a later round: never reissue them.\n", - policy.max_read_only_calls, policy.max_mutating_calls - ) - } else { - write!( - prompt, - "\n\n# Tool response limit\n\ -The effective max_mutating_calls_per_response is {}. \ -Batch independent read-only calls freely in one assistant response and wait for their results before choosing the next action. \ -Workspace-changing calls (mutating `run_command` calls, file writes/edits and other tools with side effects) run \ -one after another in the order given, up to that limit per response; send several together only when a later one \ -does not depend on an earlier result. Read-only inspection never consumes this limit. Never assume an unexecuted call ran. \ -Calls beyond the limit are held by the harness and executed automatically in a later round: never reissue them.\n", - policy.max_mutating_calls - ) - } - .expect("writing to a String cannot fail"); - // The interface folds each batch of calls into one count line, so the - // sentence before a batch is what the reader follows the work by. - prompt.push_str( - "\n# Progress notes\n\ -Before each batch of tool calls, write one short plain sentence saying what you are about to do or what the last results showed. \ -One line, no headings or lists, and never one per call. Skip it only when the batch simply continues what the previous note already said.\n", - ); -} - -/// How a root agent formats its replies (docs/output-style.md). Every -/// RustCode frontend renders CommonMark with tables and highlighted fences, -/// so this part is sent to all of them; the clause in -/// [`OUTPUT_STYLE_VIZ_HINT`] only to those that draw `rustcode-viz`. -pub(crate) const OUTPUT_STYLE_PROMPT_HINT: &str = "# Output style\n\ -Replies render as Markdown. Lead with the answer or result; never restate the question or narrate what you are about to say. \ -Keep paragraphs short. Use headings only for long, multi-part answers; bullets for parallel items, numbered steps for sequences, \ -a table for comparisons. Fence code with its language and show changes as ```diff; put `path:line` citations in inline code. \ -Link issues and pull requests by their full URL (https://github.com/owner/repo/pull/12), never a bare #12. \ -No emoji, filler, or recap of what the reply already said. End with a next step only when the user has one to take.\n"; - -/// Added to [`OUTPUT_STYLE_PROMPT_HINT`] for frontends that draw -/// `rustcode-viz`: without it the reply repeated a chart as a table. -pub(crate) const OUTPUT_STYLE_VIZ_HINT: &str = "A rustcode-viz block replaces a table or list, never repeats one in prose; its summary carries the takeaway.\n"; - -/// Added to [`OUTPUT_STYLE_PROMPT_HINT`] while Smart UI is on: the view carries the -/// detail, so the text around it stays a line or two (its "a table" means a view's). -pub(crate) const OUTPUT_STYLE_SMART_UI_HINT: &str = - "Keep prose brief. Use HTML anchors for links in views.\n"; - -/// The output-style text for a frontend. With Smart UI on the agent is taught -/// views instead of `rustcode-viz`; otherwise it depends on the viz level. -pub(crate) fn output_style_hint(visualization_level: u8, smart_ui: crate::app::SmartUi) -> String { - let mut hint = String::from(OUTPUT_STYLE_PROMPT_HINT); - if smart_ui == crate::app::SmartUi::On { - hint.push_str(OUTPUT_STYLE_SMART_UI_HINT); - } else if visualization_level > 0 { - hint.push_str(OUTPUT_STYLE_VIZ_HINT); - } - hint.push('\n'); - hint -} - -/// The output-style guidance for an external harness that takes developer -/// instructions (Codex `thread/start` `developerInstructions`). It never -/// gets RustCode's root prompt, so it also carries the citation rule from -/// the Workflow section. -pub(crate) fn harness_output_style(smart_ui: crate::app::SmartUi) -> String { - let views = if smart_ui == crate::app::SmartUi::On { - OUTPUT_STYLE_SMART_UI_HINT - } else { - "" - }; - format!( - "{OUTPUT_STYLE_PROMPT_HINT}{views}Cite code as `path:line` with the full repo-relative path.\n" - ) -} - -/// What an external harness adds to its own system prompt: where it runs, so it can say so when asked and -/// link what it makes so the app opens it, that RustCode is what owns its threads and projects, then -/// either Smart UI when the user has it on or the `rustcode-viz` types the connected client draws (none -/// at level 0), then `skills` ([`crate::skills::harness_skills_note`], because this harness has no -/// `use_skill`), what this harness does that the model must work around (`harness_note`: what its -/// sandbox blocks on this platform, how it cuts tool output; empty when nothing), then [`harness_output_style`]. Codex takes this as -/// `developerInstructions` and Claude Code's adapter as its `systemPrompt`: it goes in every prompt, -/// so every byte here is paid on every turn. -pub(crate) fn harness_instructions( - harness: &str, - visualization_level: u8, - smart_ui: crate::app::SmartUi, - skills: Option<&str>, - harness_note: &str, -) -> String { - let harness = harness.split_whitespace().collect::>().join(" "); - format!( - "In case you're asked: you are running in RustCode through the {harness} harness. \ - No need to mention this otherwise. Asked to show something, take a screenshot into the working \ - directory or `$TMPDIR` and embed it with Markdown image syntax and its absolute path, outside any \ - view or fence, one per line. Link any other file you produce by its absolute path so the user can \ - open it from RustCode. RustCode is the app that owns this machine's threads, its projects and its \ - settings: when the `rustcode` tools (or `mcp__rustcode__*`) are listed, they answer what the user \ - asks about them; without them, `rustcode threads list --all` and `rustcode threads path ` do \ - the same from a shell. Thread data lives in `~/.config/rustcode/threads`, not in another tool's \ - database. Tokens and reported cost are `thread_usage` (or `rustcode usage`), and what the \ - harnesses recorded of turns and tool calls is `query_data` (or `rustcode data query \"\"`); \ - its description lists the tables.\n\n{}{}{}{}{}", - taught_visualization_hint(visualization_level, smart_ui), - harness_smart_ui_hint(smart_ui), - skills.unwrap_or_default(), - harness_note, - harness_output_style(smart_ui) - ) -} - -/// What Codex's own Windows sandbox denies, for a Codex thread there (#3526). RustCode passes no -/// Windows-specific policy: the sandbox holds its shell in a restricted token either way, and that -/// token cannot reach the WMI service, so the model is told what to read instead of retrying. -pub(crate) const CODEX_WINDOWS_SANDBOX_NOTE: &str = r#"# Sandbox on Windows -This thread's shell runs in Codex's Windows sandbox unless the user picks Full access. WMI answers out of process, so the sandbox denies it and `Get-CimInstance`, `Get-WmiObject`, `wmic` and `systeminfo` fail with `Access denied` (0x80041003); retrying or wrapping it does not help. Read the same facts without WMI: `Get-ItemProperty HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\0` and `HKLM:\HARDWARE\DESCRIPTION\System\BIOS` for the CPU and board, `[System.Environment]::ProcessorCount` and `[System.Environment]::OSVersion` for counts and version, `[System.IO.DriveInfo]::GetDrives()` for disks, and `Get-Counter` (performance counters, not WMI) for load and memory. Registry and .NET reads are not restricted. - -"#; - -/// Antigravity cuts a long tool result down to its head and tail and saves the rest in its own -/// folder (#4098). Models acted on the preview and missed the middle, so it is told to bound what a -/// command prints and to read the saved file when the middle matters. -pub(crate) const ANTIGRAVITY_OUTPUT_NOTE: &str = "# Long command output -This harness cuts a long tool result down to a preview with the middle removed, and saves the whole output to a file it names in the result (\"You can find the full output in a file at …\"). Bound what a command prints so the answer fits: `| head -n 100`, `rg -m 20`, `git diff --stat`, `wc -l` before reading, or a narrower path. When a result says it was truncated and the part you need is in the middle, read that saved file (with a line range or `rg`) instead of acting on the preview. - -"; - -/// [`CODEX_WINDOWS_SANDBOX_NOTE`] on Windows, where Codex sandboxes the shell at all. -pub(crate) fn codex_windows_sandbox_note() -> &'static str { - if cfg!(windows) { - CODEX_WINDOWS_SANDBOX_NOTE - } else { - "" - } -} - -/// The tag [`runtime_reminder`] wraps [`harness_instructions`] in, and the -/// engine strips from an echo of it (`harness/acp_child.rs`). -pub(crate) const RUNTIME_REMINDER_START: &str = ""; -pub(crate) const RUNTIME_REMINDER_END: &str = ""; - -/// [`harness_instructions`] as the opening block of a first prompt, for an -/// agent that has no `sessionCapabilities.systemPrompt` (pi-acp, OpenCode): it -/// still has to hear where it runs, what the client draws and what RustCode -/// owns. Tagged and labelled so the model does not read it as the user's -/// words; the engine drops the agent's echo of it (`strip_runtime_echo`). -pub(crate) fn runtime_reminder(instructions: &str) -> String { - format!( - "{RUNTIME_REMINDER_START}\nRustCode's setup instructions for this thread, not the user's message.\n\n{instructions}{RUNTIME_REMINDER_END}" - ) -} - -/// The current skills note alone, as the opening block of the first prompt after a harness without a -/// client system prompt loaded a saved session: that session holds the setup text it was first sent, -/// so a skill turned off since is only heard of here. Tagged like [`runtime_reminder`] so the engine -/// drops the agent's echo of it. -pub(crate) fn skills_reminder(note: &str) -> String { - format!( - "{RUNTIME_REMINDER_START}\nRustCode's current skills for this thread (replaces the Skills section of its setup instructions), not the user's message.\n\n{note}{RUNTIME_REMINDER_END}" - ) -} - -/// Smart UI for a harness that has no root prompt and no `use_skill`: the -/// fence, when to write a view, the kit's names, and what the sandbox blocks. -/// The format itself is `docs/smart-ui.md`. -pub(crate) const SMART_UI_HARNESS_HINT: &str = "\ -# Smart UI -Views run in chat: a ```rustcode-ui v1 fence with a title, built from the `::` catalog (the app draws each block; HTML only for what it lacks), no imports or network, max 64 KB. \ -Answer visually, asked or not: data, numbers, results, status, comparisons, plans or 4+ items go in a view (chart, bars, stats, table), never a Markdown table. Only short explanations, one fact, code and diffs stay Markdown. Be brief: one line with the finding before the view, nothing after it. Sources go last inside the view, folded: details.rc-sources > ol > li > a[href]. A report to another thread stays plain Markdown. -Pick: a trend → line chart; parts → stacked bar, donut; ranking → bars; options → cards; exact rows → table; a choice → form. -Catalog: `::` opens a block, `- ` items split at |, a blank line ends it; items may end {ok|warn|bad|info}; `code`, **bold** work. A name after a block is its heading. -:: title T · :: head Title | caption · :: h · :: p · :: callout info|ok|warn|bad · :: divider · :: details Summary · :: tab Name … :: end -:: hero Label / - 503 | 3.4x | sentence · :: stats / - 128 | Runs | +12 | 1,4,2 (spark) · :: bars / - label | 75 | 75 s | tip · :: progress / - EU | 72% | note -:: chart line|bar|stacked|hbar|donut Title | size=lg | line=150 normal | band=75-270 | end / x | series… heading row, then rows · :: heatmap, :: compare (yes|no|partial), :: table / a | b rows -:: list / - Title | detail | value · :: kv / - Key | value · :: cards / - Title | body | badge · :: steps / - [x] [>] [!] [ ] · :: timeline / - 10:02 | event | detail -:: findings / - high | file:line | finding | note · :: files / - path | +12 -3 · :: tags · :: term · :: code lang · :: actions / - Label | message · :: sources / - Title | url -:: form Message | Button / - select|choice name | Label | a, *b · - text|number|date name | Label · - check name | Label · - range name | Label | 0-100 = 40 -Card and item text: one short line. HTML otherwise: kit classes (.rc-*), no colours, fonts or heights of your own; data-rc-send=\"text\" sends a follow-up. No outer border, background or repeated title; no vh. If `smart_ui_check` is listed, run it first. - -"; - -/// [`SMART_UI_HARNESS_HINT`] when the setting is off, else the off note the -/// root prompt uses; nothing for a client that cannot run the blocks. -pub(crate) fn harness_smart_ui_hint(smart_ui: crate::app::SmartUi) -> &'static str { - match smart_ui { - crate::app::SmartUi::On => SMART_UI_HARNESS_HINT, - crate::app::SmartUi::Off => SMART_UI_OFF_PROMPT_HINT, - crate::app::SmartUi::Unsupported => "", - } -} - -/// Append the output-style guidance to a root prompt. Subagent replies are -/// read by the parent, not rendered, and compact prompts are for small -/// models where every token counts. -pub(crate) fn append_output_style_hint( - prompt: &mut String, - policy: ToolSchemaPolicy, - visualization_level: u8, - smart_ui: crate::app::SmartUi, -) { - if !policy.is_subagent() && !policy.compact_text_prompt { - prompt.push_str(&output_style_hint(visualization_level, smart_ui)); - } -} - -/// Short guidance for `rustcode-viz` blocks; the full format lives in -/// `docs/visualizations.md` and the TUI renderer validates every payload. -pub(crate) const VISUALIZATION_PROMPT_HINT: &str = "# Visualizations\n\ -When a chart, table, or tree beats prose (trends, comparisons, breakdowns, hierarchies), add a ```rustcode-viz fence even if not asked with one JSON object: \ -{\"version\":1,\"type\":\"bar_chart\",\"title\":\"..\",\"summary\":\"..\",\"items\":[{\"label\":\"..\",\"value\":1}]}; \ -\"table\" takes columns, rows (arrays), optional sort_by {column,descending}; \"tree\" takes nodes [{label,note,children}]. Max 30 bars, 50 rows, 120 nodes.\n\n"; - -/// The widget types added at visualization level 2, appended after -/// [`VISUALIZATION_PROMPT_HINT`] for frontends that draw them. Level 1 -/// frontends keep exactly the level 1 prompt. -pub(crate) const VISUALIZATION_PROMPT_HINT_LEVEL_2: &str = "Also: \"line_chart\" takes labels [x] and series \ -[{name,values:[number|null]}] for trends (max 4 series, 100 points); \"stat_list\" takes items \ -[{label,value,unit,note}] for headline numbers (max 12); \"checklist\" takes items \ -[{label,status:done|todo|in_progress|failed|skipped,note}] for progress (max 50).\n\n"; - -/// The visualization prompt text for a frontend's visualization level: none -/// for 0, the level 1 types for 1, and the level 2 types added from 2. -pub(crate) fn visualization_prompt_hint(level: u8) -> String { - match level { - 0 => String::new(), - 1 => VISUALIZATION_PROMPT_HINT.to_owned(), - _ => format!("{VISUALIZATION_PROMPT_HINT}{VISUALIZATION_PROMPT_HINT_LEVEL_2}"), - } -} - -/// What an agent is taught of `rustcode-viz`. With Smart UI on, nothing: one -/// tool per client state, so the rules never conflict. The blocks still render. -pub(crate) fn taught_visualization_hint(level: u8, smart_ui: crate::app::SmartUi) -> String { - if smart_ui == crate::app::SmartUi::On { - String::new() - } else { - visualization_prompt_hint(level) - } -} - -/// Append the visualization hint when the frontend renders `rustcode-viz` -/// blocks. Only the root agent writes user-facing replies, and compact prompts -/// are for small models where every token counts. Frontends that cannot draw -/// the blocks never get the hint, so they never see the JSON fences, and each -/// frontend is taught only the types its level draws. -pub(crate) fn append_visualization_hint( - prompt: &mut String, - policy: ToolSchemaPolicy, - visualization_level: u8, - smart_ui: crate::app::SmartUi, -) { - if !policy.is_subagent() && !policy.compact_text_prompt { - prompt.push_str(&taught_visualization_hint(visualization_level, smart_ui)); - } -} - -/// Guidance for `rustcode-ui v1` blocks (#2484), sent only to frontends that -/// advertise `_meta.rustcode.smartUi`; the format lives in `docs/smart-ui.md`. -pub(crate) const SMART_UI_PROMPT_HINT: &str = "# Smart UI\n\ -This app runs small views in replies: a ```rustcode-ui v1 fence of `::` catalog blocks. \ -Answer visually, asked or not: data, numbers, results, status, comparisons, plans or 4+ items go in a view (chart, bars, stats, table), never a Markdown table. \ -Only short explanations, one fact, code and diffs stay Markdown. Be brief: one line with the finding before the view, nothing after it. Sources go last inside the view, folded: details.rc-sources > ol > li > a[href]. A report to another thread stays plain Markdown. \ -First call `use_skill` with `smart-ui` directly (no `list_skills`).\n\n"; - -/// Sent instead of [`SMART_UI_PROMPT_HINT`] when the frontend could run the -/// blocks but the user has the setting off. Without it an agent asked for -/// "Smart UI" guesses a fence the app shows as source. -pub(crate) const SMART_UI_OFF_PROMPT_HINT: &str = "# Smart UI\n\ -This app has Smart UI (interactive HTML components in the chat), but it is turned off. \ -If the user asks for Smart UI or an interactive view, tell them to turn on Settings › Chat › Smart UI \ -and restart the engine; until then answer with Markdown or rustcode-viz, never an HTML fence.\n\n"; - -/// The Smart UI hint, if any, for a root prompt. -pub(crate) fn smart_ui_hint(smart_ui: crate::app::SmartUi) -> &'static str { - match smart_ui { - crate::app::SmartUi::On => SMART_UI_PROMPT_HINT, - crate::app::SmartUi::Off => SMART_UI_OFF_PROMPT_HINT, - crate::app::SmartUi::Unsupported => "", - } -} - -/// Append the Smart UI hint for a root prompt whose frontend runs the blocks. -pub(crate) fn append_smart_ui_hint( - prompt: &mut String, - policy: ToolSchemaPolicy, - smart_ui: crate::app::SmartUi, -) { - if !policy.is_subagent() && !policy.compact_text_prompt { - prompt.push_str(smart_ui_hint(smart_ui)); - } -} - -/// Append the `localhost_preview` guidance for a request that offers the -/// tool, and the other threads' for one that offers those. -pub(crate) fn append_preview_hint(prompt: &mut String, policy: ToolSchemaPolicy) { - if policy.include_preview_tool { - prompt.push_str(crate::preview::PREVIEW_PROMPT_HINT); - } - if policy.include_desktop_tool { - prompt.push_str(crate::desktop_control::PROMPT_HINT); - } - if policy.include_smart_ui_preview_tool { - prompt.push_str(crate::smart_ui::PREVIEW_PROMPT_HINT); - } - if policy.include_orchestration_tools { - prompt.push_str(crate::orchestration::prompt_hint( - policy.orchestration_version, - )); - } -} - -/// MCP lines of a textual tool contract, bounded like the native schema -/// selection. Text protocols used to inline every connected MCP tool with its -/// full schema; with a dozen servers that was 18k of a 20k-token prompt for a -/// small model (#2587). Tools past the global or per-server byte budget are -/// listed by name only, and `list_mcp_tools` `select` returns their schemas. -fn textual_mcp_listing( - entries: &[(String, String, String, Value)], - compact: bool, - budget_bytes: usize, -) -> String { - let mut listed = String::new(); - let mut used = 0usize; - let mut per_server: HashMap<&str, usize> = HashMap::new(); - let mut names_only: std::collections::BTreeMap<&str, Vec<&str>> = Default::default(); - for (name, server, desc, schema) in entries { - let args = serde_json::to_string(schema).unwrap_or_default(); - let line = if compact { - format!("- {name} | Args: {args}\n") - } else { - format!("- {name} | Args: {args} | {desc}\n") - }; - let server_used = per_server.entry(server.as_str()).or_default(); - if used + line.len() <= budget_bytes - && *server_used + line.len() <= MAX_MCP_PER_SERVER_SCHEMA_BYTES - { - used += line.len(); - *server_used += line.len(); - listed.push_str(&line); - } else { - names_only - .entry(server.as_str()) - .or_default() - .push(name.as_str()); - } - } - if !names_only.is_empty() { - listed.push_str( - "- More MCP tools, listed by name without arguments; call `list_mcp_tools` with `select` to get a schema before using one:\n", - ); - for (server, names) in names_only { - listed.push_str(&format!(" - {server}: {}\n", names.join(", "))); - } - } - listed -} - -pub(crate) fn tool_system_prompt_for_policy( - policy: ToolSchemaPolicy, - protocol: crate::config::ToolProtocol, - agent_mode: crate::config::AgentMode, -) -> String { - // The first-turn-only `set_session_title` tool must not vary the system - // prompt: a turn-1/turn-2 difference here invalidates the whole cached - // prefix. Its guidance (and, for text protocols, its call shape) rides in - // the per-turn context tail instead; see `session_title_turn_hint`. - // `localhost_preview` is described by its own hint, appended only for - // sessions that have it (`append_preview_hint`), so the shared prompt - // never lists a tool most clients cannot run. - let policy = ToolSchemaPolicy { - include_session_title_tool: false, - include_preview_tool: false, - include_desktop_tool: false, - include_smart_ui_preview_tool: false, - include_orchestration_tools: false, - include_orchestration_v2_tools: false, - include_orchestration_v3_tools: false, - include_orchestration_v4_tools: false, - include_orchestration_v6_tools: false, - include_orchestration_v7_tools: false, - include_orchestration_v9_tools: false, - ..policy - }; - let mut p = String::new(); - - p.push_str( - "\n# Skills\n\ -Skills stay on demand; never probe speculatively. Call `list_skills` only when the request names a skill, the Relevant-skills hint names a match, or built-ins/shell are stuck. \ -For local machine state check the shell first, never `list_skills` first. \ -`list_skills` returns metadata only; `use_skill` loads the selected SKILL.md.\n\n", - ); - - if agent_mode == crate::config::AgentMode::Plan { - p.push_str( - "CRITICAL: You are operating in PLAN MODE (Read-only / Design mode).\n\ - - File writing, deletion, shell commands, delegation, and unknown tools are disabled; you can read, search, ask questions, and design, but CANNOT modify files or execute commands.\n\ - - Investigate before planning with `grep`, `glob`, and `view_file`: read the manifest, real call sites, crates, and existing patterns.\n\ - - Make the plan specific to THIS repository: name files, functions/structs, and inspected line ranges; resolve unknowns now, never guess dependencies or module layout, and state verified facts and uncertainties.\n\ - - Explain the plan and tell the user to switch to Build Mode (press Shift+Tab) to implement it.\n\n" - ); - } - - p.push_str( - "You are rustcode, a terminal coding agent.\n\ -# Workflow\n\ -- Act on change requests: locate, inspect, edit, verify. Prefer the smallest focused sequence once grounded; do not restate tasks or narrate tools. Finish with changed files, verification, and blockers.\n\ -- For research/review answers, label verified findings, judgments, and gaps, and never claim comprehensive coverage without evidence. Avoid fixed long templates. Cite `path:line` with full repo-relative paths.\n\ -- Use `sandbox/` for temporary work and `artifacts/` for persistent reports. Run commands expected to exceed 2s in the background and keep working; results arrive automatically, so never poll.\n\ -- `run_command` uses the platform shell. Chained shell commands are fine when inspectable; use `&&` for dependent commands, show destructive operations, and never mask required failures. Check from the nearest project manifest. If in-scope dependencies are missing, run the deterministic lockfile install once, then retry. Never run `cargo check` on a standalone `.rs` file.\n\ -- Prefer write tools for file creation; heredoc only for small appends/pipes.\n\ -- Do not branch, commit, push or open a PR unless the user or the project's instructions ask; then, if `git-feature-workflow` is available, load and follow it. Preserve unrelated work; never use `git add .`, `git add -A`, or `git add --all`.\n\ -- Tool results are authoritative: claim checks only after an observed exit code 0. Fix compiler/tool errors or warnings, then rerun failed or stale checks. Subagent reports are advisory; inspect the workspace yourself.\n\ -- Use native `grep`/`glob` for exact discovery, `rg` through `run_command` for advanced searches, and SocratiCode `codebase_*` for semantic relationships. Inspect the exact range before editing; never guess lines, APIs, or dependencies.\n\ -- Batch independent reads in one response; mutations run in order, control-plane calls first. Wait for results before the next calls. Give each call a short `summary` for the user.\n\ -- Chained shell observations are fine when small and inspectable. `view_file` returns numbered text and continuation metadata; complete results are authoritative, so do not reread them—edit or verify next. For manual previews, use the user's exact port, do not start/probe/fallback, and let them run it after verification; do not start a server merely to inspect a static app.\n\ -- Match neighboring signatures, state/lock, and error conventions.\n\ -- Run focused checks and cover boundaries for complex logic.\n\ -- Read-only tools run immediately; modifying/destructive operations require confirmation. Use `ask_question` only for ambiguous requirements or explicit validation, never routine confirmation. The UI supplies the write-in slot; do not include `Other`. Finish with a plain-text summary.\n\n\ -# Avoiding loops\n\ -- Avoid unchanged rereads; use `view_file` with `start_line`/`end_line` or existing evidence. Correct errors and change empty queries. -- Repeated reads, no-ops, and failed attempts are advisory loop signals, not a hard stop. Avoid endlessly repeating an identical call, but continue when needed with a different `view_file` range, `grep`, edit, or test. Use cached replay content when supplied; if a replayed read is incomplete or unavailable, choose another useful inspection. An edit that reports \"already applied\" changed nothing on disk, so do not re-issue that identical edit without new evidence. -- Use `todo_write` only for complex 3+ step work, not routine edits, git, or simple questions; update it at milestones.\n\n" - ); - - // Gate on the same condition as the agent tool list below: promising a - // delegation workflow with zero callable subagent tools made the model - // probe `run_command` and `list_mcp_tools` for a `spawn_agent` that was - // never offered. (#1589) - if policy.include_agent_tools && agent_mode != crate::config::AgentMode::Plan { - p.push_str( - "# Delegation Policy\n\\ -- Subagent tools are available by default; use them when parallel work or independent review will help the task.\n\\ -- Before delegating, identify the critical path and keep blockers in the main agent. Delegate only bounded, self-contained side tasks with clear outputs and disjoint write scopes.\n\\ -- Review every subagent result and inspect its workspace changes before treating the task as complete.\n\\n", - ); - } else if policy.profile == ToolSchemaProfile::Coding - && agent_mode != crate::config::AgentMode::Plan - { - // Say why there is no agent tool instead of staying silent: with no - // hint the model spent rounds searching MCP for one. (#1710) - p.push_str( - "# Delegation\n\ -- No agent tools; don't search. `/delegate` unless config disables.\n\n", - ); - } - - p.push_str("# Tool Format\n"); - match protocol { - crate::config::ToolProtocol::Json => { - p.push_str( - "Active tool protocol: textual JSON fence. Call tools only as fenced `tool` blocks containing one JSON object; emit no prose before/after.\n\n\ - ```tool\n\ - {\"name\": \"tool_name\", \"arguments\": {...}}\n\ - ```\n\n\ - Rules: keys are \"name\" and \"arguments\"; argument values use their proper JSON types. Use only the ```tool fence (never ```tool_code, ```json, or another fence) and never duplicate a call. Batch independent reads as multiple fences; mutations run in order. Wait for results before the next calls.\n\n" - ); - } - crate::config::ToolProtocol::Native => { - p.push_str( - "Active tool protocol: textual native tags. Call tools only with native tags; emit no prose before/after.\n\n\ - [TOOL_CALLS]tool_name[ARGS]{\"arg_name\": \"value\"}\n\n\ - Rules: batch independent reads as multiple [TOOL_CALLS] markers; mutations run in order, control-plane calls first. Wait for results before the next calls. Arguments must be a valid JSON object matching the tool parameters.\n\n" - ); - } - crate::config::ToolProtocol::ApiNative => { - p.push_str( - "Active tool protocol: API-native. Tools use the API's native function-calling interface: invoke them directly; do NOT print tool calls as text or JSON. Batch independent reads together; mutations run in order, control-plane calls first. Wait for results before the next action. When complete, reply with a plain-text summary and no tool call.\n\n" - ); - } - } - - // Text protocols enumerate tools in the prompt. ApiNative carries the full - // tool schema in the request's `tools` field instead, so listing them here - // would only duplicate that and waste context. That also means a filtered - // `tools` block is the model's only view of the surface, so state the - // filtering and the discovery route before returning; it used to mention - // neither and left a silent-drop rejection as the only feedback. (#1589) - if matches!(protocol, crate::config::ToolProtocol::ApiNative) { - p.push_str( - "# Tool Surface\n\ -This request's tool list is filtered, not exhaustive. A listed tool is the only one carrying its argument schema here, and the list stays fixed for the whole turn. \ -Never guess MCP server names: see MCP Servers, then `list_mcp_tools` `select` for schemas. Any registered tool works by its exact name.\n\n", - ); - return p; - } - - p.push_str("For connected services with a matching MCP server listed, prefer their tools over shell. With no matching server, check the shell first; never probe `list_mcp_tools` speculatively.\n\n"); - p.push_str("Available tools:\n"); - for t in TOOLS { - if !text_builtin_is_advertised(t, policy, agent_mode) { - continue; - } - if policy.compact_text_prompt { - p.push_str(&format!("- {} | Args: {}\n", t.name, t.arguments)); - } else { - p.push_str(&format!( - "- {} | Args: {} | {}\n", - t.name, t.arguments, t.description - )); - } - } - if policy.include_mcp_tools && agent_mode != crate::config::AgentMode::Plan { - let entries = collect_mcp_tools_with_servers() - .into_iter() - .filter(|(name, ..)| policy.offers_mcp_tool(name)) - .map(|(name, server, _, desc, schema)| (name, server, desc, schema)) - .collect::>(); - p.push_str(&textual_mcp_listing( - &entries, - policy.compact_text_prompt, - mcp_schema_budget_bytes(), - )); - } - if policy.include_agent_tools && agent_mode != crate::config::AgentMode::Plan { - p.push_str("- spawn_agent | Args: {\"task\":\"task description\",\"context_inheritance\":\"minimal|evidence|recent|fork\",\"evidence\":\"selected facts\"} | Start a fresh child; default minimal. Optional agent_type explorer|worker|default. Writes require explicit write_access or agent_type worker, plus allowed_paths and verification. Returns JSON with agent_id.\n"); - p.push_str("- send_agent | Args: {\"id\": subagent_id, \"message\": \"message\", \"interrupt\": false} | Follow up an idle subagent or steer an active child at its next safe boundary; interrupt stops its current turn and redirects it now.\n"); - if policy.profile == ToolSchemaProfile::Coding { - p.push_str("- set_goal | Args: {\"goal\": \"goal description\"} | Set a new long-running task and switch the agent to continuous autoloop mode.\n"); - p.push_str("- todo_write | Args: {\"todos\": [{\"id\": \"t1\", \"content\": \"step\", \"status\": \"pending|in_progress|completed|blocked\", \"priority\": \"high|medium|low\"}], \"merge\": false} | Replace the persistent task plan; with merge true, update only the steps whose id you give. Use this at the start of multi-step work and update it as steps finish.\n"); - } - } - - if policy.compact_text_prompt { - p.push_str("\nUse the exact tool names and JSON argument shapes listed above.\n"); - return p; - } - - match protocol { - crate::config::ToolProtocol::Json => { - p.push_str( - "\nExample (task — needs a tool):\n\ -User: Where is the agent loop implemented?\n\ -Assistant:\n\ -```tool\n\ -{\"name\": \"grep\", \"arguments\": {\"pattern\": \"agent loop\", \"include\": \"*.rs\"}}\n\ -```\n\n\ -Example (conversation — no tool):\n\ -User: hello, how are you?\n\ -Assistant: Hi! Ready to help with your code. What are you working on?\n", - ); - } - crate::config::ToolProtocol::Native => { - p.push_str( - "\nExample (task — needs a tool):\n\ -User: Where is the agent loop implemented?\n\ -Assistant:\n\ -[TOOL_CALLS]grep[ARGS]{\"pattern\": \"agent loop\", \"include\": \"*.rs\"}\n\n\ -Example (conversation — no tool):\n\ -User: hello, how are you?\n\ -Assistant: Hi! Ready to help with your code. What are you working on?\n", - ); - } - // ApiNative returns early above (tools come from the request schema, not - // the prompt), so this arm is unreachable but keeps the match exhaustive. - crate::config::ToolProtocol::ApiNative => {} - } - - p -} - -/// First-turn guidance for `set_session_title`, injected into the per-turn -/// context tail so the cached system prompt stays byte-identical across turns. -/// Text protocols list tools only in the system prompt, so the hint also -/// carries the call shape there; API-native requests get the schema from the -/// request's `tools` field. -pub(crate) fn session_title_turn_hint(protocol: crate::config::ToolProtocol) -> String { - let mut hint = String::from( - "First-turn session title: a concise title is already saved from the user's request. Call `set_session_title` before doing other work. Name the main task in 2 to 4 plain words when possible, using at most 32 characters. Do not copy the full prompt, transcript, or secrets into the title.", - ); - if !matches!(protocol, crate::config::ToolProtocol::ApiNative) { - let tool = &super::misc::SET_SESSION_TITLE; - hint.push_str(&format!( - "\nAvailable this turn only:\n- {} | Args: {} | {}", - tool.name, tool.arguments, tool.description - )); - } - hint -} - -pub fn tool_system_prompt( - include_agent_tools: bool, - protocol: crate::config::ToolProtocol, - agent_mode: crate::config::AgentMode, -) -> String { - tool_system_prompt_for_policy( - ToolSchemaPolicy::root_for_mode(include_agent_tools, agent_mode), - protocol, - agent_mode, - ) -} - -#[cfg(test)] -mod response_limit_tests { - use super::*; - use crate::config::{AgentMode, ModelProfile, ToolProtocol}; - - #[test] - fn mutation_guidance_matches_effective_policy_for_every_protocol() { - for protocol in [ - ToolProtocol::ApiNative, - ToolProtocol::Json, - ToolProtocol::Native, - ] { - for policy in [ - ToolSchemaPolicy::root_for_mode(false, AgentMode::Build), - ToolSchemaPolicy::subagent(), - ] { - let base = tool_system_prompt_for_policy(policy, protocol, AgentMode::Build); - // Reuse the same base as the root prompt cache does, including - // switching back to the default after a profile override. - for configured in [None, Some(3), Some(0), Some(usize::MAX), None] { - let profile = ModelProfile { - max_mutating_calls_per_response: configured, - ..ModelProfile::default() - }; - let limit = profile.max_mutating_calls_per_response(); - let mut prompt = base.clone(); - append_tool_response_limit(&mut prompt, limit); - assert!(prompt.contains(&format!( - "effective max_mutating_calls_per_response is {limit}." - ))); - assert_eq!(prompt.matches("# Tool response limit").count(), 1); - assert!(prompt.contains("Read-only inspection never consumes this limit")); - assert!(prompt.contains("Never assume an unexecuted call ran")); - - // The shell guidance must agree with the actual executor: - // mutating commands consume the mutation allowance while - // read-only inspection does not. - let calls = (0..=limit) - .map(|_| crate::tools::ToolCall { - name: "run_command".into(), - arguments: serde_json::json!({"command": "cargo test"}), - call_id: None, - }) - .collect(); - let (kept, dropped) = crate::tools::partition_tool_batch(calls, limit); - assert_eq!(kept.len(), limit); - assert_eq!(dropped.len(), 1); - } - } - } - } - - #[test] - fn native_protocol_batches_reads_and_limits_mutations() { - let prompt = tool_system_prompt(false, ToolProtocol::Native, AgentMode::Build); - - assert!(prompt.contains("multiple [TOOL_CALLS] markers")); - assert!(prompt.contains("mutations run in order")); - assert!(!prompt.contains("exactly one [TOOL_CALLS] marker")); - } -} +mod response_limit_tests; #[cfg(test)] -mod schema_budget_tests { - use super::*; - - /// Ceiling for the built-in half of the native `tools` block under the - /// root coding policy with agent tools, the widest menu a request carries. - /// - /// The block was 31,659 bytes before its descriptions were trimmed to - /// 23,583 (#1826). The 25 KiB ceiling accommodates archive retrieval and - /// MCP server management (#1890) while staying below the old size. It is - /// sent on every request, so keep new descriptions concise and measure - /// their cost. Run with `-- --nocapture` for the per-tool table. - const BUILTIN_SCHEMA_BYTE_BUDGET: usize = 25 * 1024; - - /// Room the plain root block must keep under that budget, so the next tool - /// does not use the last free byte. - const MIN_BUILTIN_SCHEMA_HEADROOM_BYTES: usize = 256; - - /// Serialized bytes of every built-in tool's native schema entry, largest - /// first, measured the way the request builder serializes it. Covers the - /// whole registry and the agent-control tools, advertised or not. - fn builtin_schema_sizes() -> Vec<(&'static str, usize)> { - let entry = |name: &str, description: &str, parameters: Value| { - // One array element, without the array's own brackets. - serialized_schema_bytes(&[serde_json::json!({ - "type": "function", - "function": { - "name": name, - "description": description, - "parameters": provider_compatible_schema(parameters), - } - })]) - 2 - }; - let mut sizes = TOOLS - .iter() - .map(|tool| { - ( - tool.name, - entry(tool.name, tool.description, schema_for_tool(tool.name)), - ) - }) - .chain(AGENT_TOOL_SPECS.iter().map(|(name, description, _)| { - (*name, entry(name, description, schema_for_agent_tool(name))) - })) - .collect::>(); - sizes.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); - sizes - } - - /// Room the newest client's block must keep under the hard cap. Without - /// it the next tool added here fits the cap by 1 byte and the block still - /// shrinks on the request after that; the assertion turns the next - /// addition into a build failure with the number to free (#3376). - const MIN_ORCHESTRATION_HEADROOM_BYTES: usize = 2 * 1024; - - #[test] - fn the_orchestration_tools_fit_the_hard_cap() { - // Every supported client version gets every tool its version - // advertises in its built-in schema: the hard cap must never withhold - // one the client can answer, since the tool is then silently missing - // from the menu. This is the regression test for the 41 KiB cap that - // cut `thread_status`, `merge_when_green` and `cleanup_worktree` from a - // v9 client (#3376): the names are compared, not only the count, so a - // swap cannot pass as a match. - for version in 1..=crate::orchestration::VERSION { - let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); - let expected = crate::tools::TOOLS - .iter() - .filter(|tool| builtin_is_advertised(tool, policy)) - .map(|tool| tool.name) - .collect::>(); - let (tools, withheld) = build_builtin_native_tools_schema(policy); - let kept = tools - .iter() - .filter_map(|tool| tool["function"]["name"].as_str()) - .collect::>(); - let bytes = serialized_schema_bytes(&tools); - println!( - "orchestration v{version}: {bytes} bytes, {} of {} tools, {} bytes free, withheld {withheld:?}", - kept.len(), - expected.len(), - MAX_BUILTIN_NATIVE_SCHEMA_BYTES - bytes - ); - assert_eq!(kept, expected, "v{version} lost a tool to the cap"); - assert!(withheld.is_empty(), "v{version} withheld: {withheld:?}"); - assert!( - bytes < MAX_BUILTIN_NATIVE_SCHEMA_BYTES, - "v{version} is {bytes} bytes, over the hard cap" - ); - if version == crate::orchestration::VERSION { - let free = MAX_BUILTIN_NATIVE_SCHEMA_BYTES - bytes; - assert!( - free >= MIN_ORCHESTRATION_HEADROOM_BYTES, - "v{version} has {free} bytes free, under the {MIN_ORCHESTRATION_HEADROOM_BYTES} \ - a new tool needs: shorten descriptions in `tools/misc.rs` and `tools/schema.rs` first" - ); - } - } - // A client below 5 is not shown an argument its app cannot answer. - let start_schema = |version: u8| { - let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); - let (tools, _) = build_builtin_native_tools_schema(policy); - tools - .into_iter() - .find(|tool| tool["function"]["name"] == crate::orchestration::START_SESSION) - .expect("start_session") - }; - assert!(start_schema(4)["function"]["parameters"]["properties"]["account"].is_null()); - assert!(start_schema(5)["function"]["parameters"]["properties"]["account"].is_object()); - // A standalone thread arrived in v15 (issue 3443): v14 never sees the - // field, so an app that cannot start one is not offered it. - assert!(start_schema(14)["function"]["parameters"]["properties"]["standalone"].is_null()); - assert!(start_schema(15)["function"]["parameters"]["properties"]["standalone"].is_object()); - // Nor is v9 shown files to attach, which its app would drop. - let message_schema = |version: u8| { - let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); - let (tools, _) = build_builtin_native_tools_schema(policy); - tools - .into_iter() - .find(|tool| tool["function"]["name"] == crate::orchestration::MESSAGE_SESSION) - .expect("message_session") - }; - assert!(message_schema(9)["function"]["parameters"]["properties"]["attachments"].is_null()); - assert!( - message_schema(10)["function"]["parameters"]["properties"]["attachments"].is_object() - ); - } - - #[test] - fn the_block_check_is_not_a_built_in_tool() { - // It is listed by the `rustcode` MCP server an external harness runs, - // and answered there; a RustCode turn would only get the error handler. - assert!( - crate::tools::TOOLS - .iter() - .any(|tool| tool.name == crate::smart_ui::CHECK_TOOL_NAME) - ); - for policy in [ - ToolSchemaPolicy::root(true), - ToolSchemaPolicy::read_only_inspection(), - ] { - let (tools, _) = build_builtin_native_tools_schema(policy); - assert!( - !tools - .iter() - .any(|tool| tool["function"]["name"] == crate::smart_ui::CHECK_TOOL_NAME), - "the block check is never a built-in tool" - ); - } - } - - #[test] - fn the_link_tool_is_built_in_for_every_client() { - // The `rustcode` MCP server an external harness runs lists and answers - // it (`orchestration/mcp_server.rs`, #3369), and a RustCode turn - // answers it in `pull_watch::answer` through its own handler: since - // #3376 freed the room, it is advertised to every client instead of - // only to an external harness. - assert!( - crate::tools::TOOLS - .iter() - .any(|tool| tool.name == crate::pull_watch::LINK_TOOL_NAME) - ); - for policy in [ - ToolSchemaPolicy::root(false), - ToolSchemaPolicy::root(true), - ToolSchemaPolicy::root(true).with_orchestration_tools(crate::orchestration::VERSION), - ] { - let (tools, withheld) = build_builtin_native_tools_schema(policy); - assert!( - tools - .iter() - .any(|tool| tool["function"]["name"] == crate::pull_watch::LINK_TOOL_NAME), - "the link tool is missing from the built-in block: {policy:?}, withheld {withheld:?}" - ); - } - // It links a thread, so it is not a read-only inspection tool. - let (tools, _) = - build_builtin_native_tools_schema(ToolSchemaPolicy::read_only_inspection()); - assert!( - !tools - .iter() - .any(|tool| tool["function"]["name"] == crate::pull_watch::LINK_TOOL_NAME) - ); - } - - #[test] - fn builtin_schema_bytes_stay_within_budget() { - let sizes = builtin_schema_sizes(); - for (name, bytes) in &sizes { - println!("{bytes:>6} {name}"); - } - println!( - "{:>6} all {} built-in and agent tools", - sizes.iter().map(|(_, bytes)| bytes).sum::(), - sizes.len() - ); - - let (tools, withheld) = build_builtin_native_tools_schema(ToolSchemaPolicy::root(true)); - let bytes = serialized_schema_bytes(&tools); - println!( - "{bytes:>6} advertised built-in block, {} tools (budget {BUILTIN_SCHEMA_BYTE_BUDGET})", - tools.len() - ); - assert!( - withheld.is_empty(), - "the byte cap withheld built-in tools: {withheld:?}" - ); - assert!( - bytes <= BUILTIN_SCHEMA_BYTE_BUDGET, - "built-in tool schemas grew to {bytes} bytes, over the {BUILTIN_SCHEMA_BYTE_BUDGET} budget; \ - shorten a description (largest first: {:?})", - &sizes[..5] - ); - // A budget reached to the last byte is a budget that fails the next - // tool that arrives, which is how the versioned block lost three tools - // under its old cap (#3376). Keep room for one modest addition. - let free = BUILTIN_SCHEMA_BYTE_BUDGET - bytes; - assert!( - free >= MIN_BUILTIN_SCHEMA_HEADROOM_BYTES, - "the built-in block has {free} bytes free, under the {MIN_BUILTIN_SCHEMA_HEADROOM_BYTES} \ - a new tool needs: shorten a description (largest first: {:?})", - &sizes[..5] - ); - // The budget only means something while it sits under the hard cap - // that starts withholding tools. - assert!(BUILTIN_SCHEMA_BYTE_BUDGET < MAX_BUILTIN_NATIVE_SCHEMA_BYTES); - } - - #[test] - fn cached_builtin_schema_matches_a_fresh_build_for_each_policy() { - for policy in [ - ToolSchemaPolicy::root(false), - ToolSchemaPolicy::root(true), - ToolSchemaPolicy::root(true).with_session_title_tool(), - ToolSchemaPolicy::read_only_inspection(), - ] { - let (tools, withheld) = build_builtin_native_tools_schema(policy); - let cached = cached_builtin_native_tools_schema(policy); - assert_eq!(cached.tools, tools, "{policy:?}"); - assert_eq!(cached.withheld, withheld, "{policy:?}"); - assert_eq!(cached.bytes, serialized_schema_bytes(&tools), "{policy:?}"); - assert!(Arc::ptr_eq( - &cached, - &cached_builtin_native_tools_schema(policy) - )); - } - } - - /// Trimming must never leave a tool undescribed, and a description pays - /// for every byte, including stray runs of spaces. - #[test] - fn every_builtin_tool_keeps_a_description() { - for tool in TOOLS { - assert!( - tool.description.trim().len() >= 20, - "{} lost its description", - tool.name - ); - assert!( - !tool.description.contains(" "), - "{} has a run of spaces in its description", - tool.name - ); - } - } -} +mod schema_budget_tests; #[cfg(test)] -mod mcp_read_classification_tests { - use super::{mcp_annotations_mark_read_only, mcp_name_suggests_read_only}; - use serde_json::json; - - // Session 01a130ea (#1970): five unannotated worklog lookups in one - // response were held over the workspace-change limit. - #[test] - fn unannotated_lookups_are_reads() { - for name in [ - "solidtime_list_clients", - "solidtime_get_active_timer", - "solidtime_list_entries", - "list_clients", - "get_active_timer", - "search_issues", - "find_user", - "read_page", - "show-config", - ] { - assert!(mcp_name_suggests_read_only(name), "{name}"); - assert!(mcp_annotations_mark_read_only(name, None), "{name}"); - } - } - - #[test] - fn unannotated_mutations_and_unknown_verbs_stay_conservative() { - for name in [ - "solidtime_start_timer", - "solidtime_create_entry", - "delete_list_items", - "get_or_create_issue", - "search_and_replace", - "worklog_check_gaps", - "whoami", - "solidtime_list", - "listClients", - ] { - assert!(!mcp_name_suggests_read_only(name), "{name}"); - } - } - - #[test] - fn explicit_annotations_override_the_name_heuristic() { - let not_read_only = json!({"readOnlyHint": false}); - assert!(!mcp_annotations_mark_read_only( - "list_clients", - Some(¬_read_only) - )); - let destructive = json!({"destructiveHint": true}); - assert!(!mcp_annotations_mark_read_only( - "get_and_purge", - Some(&destructive) - )); - let read_only = json!({"readOnlyHint": true}); - assert!(mcp_annotations_mark_read_only("whoami", Some(&read_only))); - } - - // #2587: twelve servers inlined 101 MCP schemas into a small model's - // textual contract. Past the budget, tools are named and deferred to - // `list_mcp_tools`, and no server crowds out the others. - #[test] - fn textual_mcp_listing_defers_tools_past_the_schema_budget() { - let schema = json!({"type": "object", "properties": {"q": {"type": "string"}}}); - let entries = (0..40) - .map(|i| { - let server = if i < 30 { "big" } else { "small" }; - ( - format!("{server}_tool_{i:02}"), - server.to_string(), - "x".repeat(300), - schema.clone(), - ) - }) - .collect::>(); - - let budget = super::MAX_MCP_NATIVE_SCHEMA_BYTES; - let listing = super::textual_mcp_listing(&entries, false, budget); - - assert!(listing.len() < budget + 1024, "{} bytes", listing.len()); - assert!(listing.contains("- big_tool_00 | Args:")); - assert!(listing.contains("- small_tool_30 | Args:"), "{listing}"); - assert!(listing.contains("`list_mcp_tools` with `select`")); - assert!(listing.contains("big_tool_29")); - assert!(!listing.contains("- big_tool_29 | Args:")); - - let small = super::textual_mcp_listing(&entries[..2], false, 8 * 1024); - assert!(!small.contains("list_mcp_tools")); - } -} +mod mcp_read_classification_tests; diff --git a/rustcode/engine/src/tools/schema/mcp_read_classification_tests.rs b/rustcode/engine/src/tools/schema/mcp_read_classification_tests.rs new file mode 100644 index 000000000..258951a33 --- /dev/null +++ b/rustcode/engine/src/tools/schema/mcp_read_classification_tests.rs @@ -0,0 +1,87 @@ +use super::{mcp_annotations_mark_read_only, mcp_name_suggests_read_only}; +use serde_json::json; + +// Session 01a130ea (#1970): five unannotated worklog lookups in one +// response were held over the workspace-change limit. +#[test] +fn unannotated_lookups_are_reads() { + for name in [ + "solidtime_list_clients", + "solidtime_get_active_timer", + "solidtime_list_entries", + "list_clients", + "get_active_timer", + "search_issues", + "find_user", + "read_page", + "show-config", + ] { + assert!(mcp_name_suggests_read_only(name), "{name}"); + assert!(mcp_annotations_mark_read_only(name, None), "{name}"); + } +} + +#[test] +fn unannotated_mutations_and_unknown_verbs_stay_conservative() { + for name in [ + "solidtime_start_timer", + "solidtime_create_entry", + "delete_list_items", + "get_or_create_issue", + "search_and_replace", + "worklog_check_gaps", + "whoami", + "solidtime_list", + "listClients", + ] { + assert!(!mcp_name_suggests_read_only(name), "{name}"); + } +} + +#[test] +fn explicit_annotations_override_the_name_heuristic() { + let not_read_only = json!({"readOnlyHint": false}); + assert!(!mcp_annotations_mark_read_only( + "list_clients", + Some(¬_read_only) + )); + let destructive = json!({"destructiveHint": true}); + assert!(!mcp_annotations_mark_read_only( + "get_and_purge", + Some(&destructive) + )); + let read_only = json!({"readOnlyHint": true}); + assert!(mcp_annotations_mark_read_only("whoami", Some(&read_only))); +} + +// #2587: twelve servers inlined 101 MCP schemas into a small model's +// textual contract. Past the budget, tools are named and deferred to +// `list_mcp_tools`, and no server crowds out the others. +#[test] +fn textual_mcp_listing_defers_tools_past_the_schema_budget() { + let schema = json!({"type": "object", "properties": {"q": {"type": "string"}}}); + let entries = (0..40) + .map(|i| { + let server = if i < 30 { "big" } else { "small" }; + ( + format!("{server}_tool_{i:02}"), + server.to_string(), + "x".repeat(300), + schema.clone(), + ) + }) + .collect::>(); + + let budget = super::MAX_MCP_NATIVE_SCHEMA_BYTES; + let listing = super::textual_mcp_listing(&entries, false, budget); + + assert!(listing.len() < budget + 1024, "{} bytes", listing.len()); + assert!(listing.contains("- big_tool_00 | Args:")); + assert!(listing.contains("- small_tool_30 | Args:"), "{listing}"); + assert!(listing.contains("`list_mcp_tools` with `select`")); + assert!(listing.contains("big_tool_29")); + assert!(!listing.contains("- big_tool_29 | Args:")); + + let small = super::textual_mcp_listing(&entries[..2], false, 8 * 1024); + assert!(!small.contains("list_mcp_tools")); +} diff --git a/rustcode/engine/src/tools/schema/mcp_selection.rs b/rustcode/engine/src/tools/schema/mcp_selection.rs new file mode 100644 index 000000000..6344cb0e9 --- /dev/null +++ b/rustcode/engine/src/tools/schema/mcp_selection.rs @@ -0,0 +1,989 @@ +use super::*; + +fn context_terms(messages: &[Value]) -> std::collections::HashSet { + // Function words say nothing about which tool is wanted, and nearly every + // tool description contains a few of them: "and", "of" and "can" alone + // cleared the relevance threshold and filled the menu for any prompt. + use crate::tools::mcp_discovery::STOP_WORDS; + let mut terms = std::collections::HashSet::new(); + for message in messages { + let role = message.get("role").and_then(Value::as_str).unwrap_or(""); + if !matches!(role, "user" | "assistant") { + continue; + } + // A `user` row the harness wrote (a tool result rendered as text, a + // tool attachment, a runtime notice) is tool output, not the user's + // words: a `manage_mcp_servers` listing there named every server. + if role == "user" && !crate::network::messages::is_user_turn_boundary(message) { + continue; + } + let content = message.get("content").and_then(Value::as_str).unwrap_or(""); + let content = content.split("").next().unwrap_or(""); + let mut message_terms = std::collections::HashSet::new(); + for token in content + .split(|ch: char| !ch.is_ascii_alphanumeric()) + .map(str::to_ascii_lowercase) + { + if token.len() >= 2 && !STOP_WORDS.contains(&token.as_str()) { + if matches!(token.as_str(), "mail" | "mails" | "emails") { + message_terms.insert("email".to_string()); + } + message_terms.insert(token); + } + } + if message_terms.contains("email") + && ["latest", "newest", "recent"] + .iter() + .any(|term| message_terms.contains(*term)) + { + message_terms.insert("list".to_string()); + } + terms.extend(message_terms); + // Structured tool turns often have an empty assistant content field. + // Keep their names in the relevance set so the next request retains + // the exact schema needed to continue the active tool exchange. + if let Some(calls) = message.get("tool_calls").and_then(Value::as_array) { + for call in calls { + if let Some(name) = call + .get("function") + .and_then(|function| function.get("name")) + .and_then(Value::as_str) + .or_else(|| call.get("name").and_then(Value::as_str)) + { + terms.insert(name.to_ascii_lowercase()); + } + } + } + } + terms +} + +fn tool_name_was_used(name: &str, messages: &[Value]) -> bool { + messages.iter().any(|message| { + message + .get("tool_calls") + .and_then(Value::as_array) + .is_some_and(|calls| { + calls.iter().any(|call| { + call.get("function") + .and_then(|function| function.get("name")) + .and_then(Value::as_str) + .is_some_and(|call_name| call_name.eq_ignore_ascii_case(name)) + || call + .get("name") + .and_then(Value::as_str) + .is_some_and(|call_name| call_name.eq_ignore_ascii_case(name)) + }) + }) + }) +} + +fn user_message_mentions_name(messages: &[Value], name: &str) -> bool { + let name = name.to_ascii_lowercase(); + messages.iter().any(|message| { + // Only what the user typed. A tool result the request carries as a + // `user` row (`…`) is not: a `manage_mcp_servers` listing + // rendered that way named every configured server, and each server's + // tools were then admitted as if the user had asked for them. + if !crate::network::messages::is_user_turn_boundary(message) { + return false; + } + let content = message + .get("content") + .and_then(Value::as_str) + .unwrap_or("") + .split("") + .next() + .unwrap_or("") + .to_ascii_lowercase(); + let mut offset = 0; + while let Some(found) = content[offset..].find(&name) { + let start = offset + found; + let end = start + name.len(); + let before_is_name_char = content[..start] + .chars() + .next_back() + .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); + let after_is_name_char = content[end..] + .chars() + .next() + .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); + if !before_is_name_char && !after_is_name_char { + return true; + } + offset = end; + } + false + }) +} + +fn canonical_mcp_server(name: &str) -> Option<&str> { + name.strip_prefix("mcp__")? + .split_once("__") + .map(|(server, _)| server) +} + +fn user_mentions_mcp_server(messages: &[Value], server: &str) -> bool { + user_message_mentions_name(messages, server) + || user_message_mentions_name(messages, &format!("{server}_mcp")) +} + +/// Keep schemas returned by completed MCP discovery calls in the next +/// request's tool block. The discovery result itself is tool output, which +/// relevance scoring intentionally ignores; without this hint, a tool found +/// by query could be omitted before the model gets a chance to call it. +/// +/// Every discovery call in the request counts, newest first: binding only +/// the latest one let finding tool B evict tool A, and binding only the +/// current turn's dropped what an earlier turn found, so the model listed +/// the same tools again on every turn (#2502). +fn mcp_tools_selected_by_discovery_calls( + tools: &[(String, String, Value)], + owners: &[String], + raw_names: &[String], + messages: &[Value], +) -> Vec { + let docs = tools + .iter() + .zip(owners) + .zip(raw_names) + .map(|(((name, description, _), owner), raw_name)| { + crate::tools::mcp_discovery::McpToolDoc { + server: owner, + raw_name, + advertised: name, + description, + } + }) + .collect::>(); + crate::tools::mcp_discovery::bound_by_discovery_calls(&docs, messages) + .into_iter() + .map(|index| tools[index].0.clone()) + .collect() +} + +/// Find MCP schemas named by the user, including every tool from a named MCP +/// server. This intentionally reads user messages only: assistant/tool output +/// can describe a tool without being an instruction to make its whole server +/// sticky. +/// +/// Returns the tools asked for one by one, in the order they must be admitted +/// (a discovery result first, then names the user wrote), and separately the +/// tools that are only wanted because their server was named. A server can +/// have more tools than a request may carry, so those are ranked by the +/// caller instead of all being treated as equally required. +fn explicitly_requested_mcp_tool_names( + tools: &[(String, String, Value)], + owners: &[String], + raw_names: &[String], + messages: &[Value], +) -> (Vec, std::collections::HashSet) { + let mut named = mcp_tools_selected_by_discovery_calls(tools, owners, raw_names, messages); + let mut requested = std::collections::HashSet::new(); + for (name, _, _) in tools { + if user_message_mentions_name(messages, name) { + if !named.contains(name) { + named.push(name.clone()); + } + } else if canonical_mcp_server(name) + .is_some_and(|server| user_mentions_mcp_server(messages, server)) + { + requested.insert(name.clone()); + } + } + + // Unique MCP tool names are intentionally sent without a server prefix. + // Recover their server here so an explicit server name still pins them. + if let Ok(registry) = crate::mcp::get_mcp_registry().lock() { + let mut clients = registry.values().cloned().collect::>(); + clients.sort_by(|left, right| left.name.cmp(&right.name)); + for client in &clients { + let server_requested = user_mentions_mcp_server(messages, &client.name) + || user_message_mentions_name( + messages, + &client + .name + .chars() + .map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '_' }) + .collect::(), + ); + if !server_requested { + continue; + } + let Ok(client_tools) = client.get_tools() else { + continue; + }; + for tool in client_tools { + let Some(raw_name) = tool.get("name").and_then(Value::as_str) else { + continue; + }; + let provider_name = + mcp_canonical_name_for_clients(&client.name, raw_name, &clients); + if tools.iter().any(|(name, _, _)| name == &provider_name) + || tools.iter().any(|(name, _, _)| name == raw_name) + { + requested.insert( + tools + .iter() + .find(|(name, _, _)| name == &provider_name || name == raw_name) + .map(|(name, _, _)| name.clone()) + .unwrap_or(provider_name), + ); + } + } + } + } + requested.retain(|name| !named.contains(name)); + (named, requested) +} + +/// Words that say what to do or name a kind of thing nearly every messaging, +/// file or task server offers. They say nothing about *which* tool is meant: +/// "chat", "msg", "reply" and "before" in a Minecraft permissions transcript +/// pulled a Snapchat reader into the menu (#2576). Compared after stemming. +const GENERIC_RELEVANCE_TERMS: &[&str] = &[ + "add", + "after", + "all", + "before", + "chat", + "check", + "clear", + "close", + "com", + "conversation", + "create", + "data", + "default", + "delete", + "detail", + "dm", + "entry", + "fetch", + "fill", + "find", + "first", + "get", + "http", + "https", + "id", + "info", + "item", + "last", + "latest", + "limit", + "list", + "load", + "member", + "message", + "msg", + "name", + "net", + "new", + "next", + "open", + "org", + "page", + "read", + "recent", + "remove", + "reply", + "result", + "run", + "save", + "search", + "send", + "set", + "show", + "start", + "status", + "stop", + "take", + "text", + "update", + "user", + "value", + "view", + "write", + "www", +]; + +/// How strongly the user's words point at one MCP tool. Only the tool's name +/// and description count: its schema's parameter names (`before`, `limit`, +/// `chat_id`) are shared by unrelated tools and are not what a user asks for. +fn mcp_tool_relevance( + name: &str, + description: &str, + terms: &std::collections::HashSet, +) -> usize { + mcp_tool_score(name, description, terms, false) +} + +/// Rank tools of a server the user already named. There the generic verbs +/// are what tells `send_chat_message` from `list_chats`, so they count. +fn mcp_tool_rank_within_server( + name: &str, + description: &str, + terms: &std::collections::HashSet, +) -> usize { + mcp_tool_score(name, description, terms, true) +} + +/// Whether one of `terms` (not a generic one) is a word of the tool's name. +/// Description words alone are weak: "issue" in a sentence about "issue +/// tracking" or "token" in an auth note matched tools nobody asked for. +fn mcp_tool_name_matches(name: &str, terms: &std::collections::HashSet) -> bool { + use crate::tools::mcp_discovery::{stem, tokens}; + let name = name.strip_prefix("mcp__").unwrap_or(name); + let name_terms = tokens(name) + .into_iter() + .collect::>(); + terms + .iter() + .map(|term| stem(term)) + .any(|term| !GENERIC_RELEVANCE_TERMS.contains(&term.as_str()) && name_terms.contains(&term)) +} + +fn mcp_tool_score( + name: &str, + description: &str, + terms: &std::collections::HashSet, + count_generic: bool, +) -> usize { + use crate::tools::mcp_discovery::{stem, tokens}; + // `mcp__` is a transport prefix, not evidence that every MCP tool is + // relevant whenever a user names an MCP server. The tokenizer is the one + // discovery uses, so `snake_case`, `camelCase` and plurals match alike. + let name = name.strip_prefix("mcp__").unwrap_or(name); + let name_terms = tokens(name) + .into_iter() + .collect::>(); + let description_terms = tokens(description) + .into_iter() + .collect::>(); + let mut score = 0; + let mut seen = std::collections::HashSet::new(); + for term in terms { + // The prompt may carry the verb inflected ("takes" for `take_…`). + let term = stem(term); + let generic = GENERIC_RELEVANCE_TERMS.contains(&term.as_str()); + if (generic && !count_generic) || !seen.insert(term.clone()) { + continue; + } + if name_terms.contains(&term) { + score += if generic { 3 } else { 8 }; + } else if description_terms.contains(&term) { + score += 3; + } + } + score +} + +#[cfg(test)] +pub(in crate::tools) fn select_mcp_tools_for_context_in_phase( + tools: &[(String, String, Value)], + messages: &[Value], + phase: ToolSchemaPhase, +) -> (Vec, McpSchemaSelectionStats) { + select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( + tools, + &[], + &[], + messages, + &[], + phase, + ) +} + +/// Which candidate bucket admitted a tool into this request's `tools` block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Admitted { + /// Carried over from the previous request's pinned menu. + Retained, + Requested, + Previous, + Relevant, +} + +#[cfg(test)] +pub(crate) fn select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( + tools: &[(String, String, Value)], + owners: &[String], + always_include_servers: &[String], + messages: &[Value], + sticky_names: &[String], + phase: ToolSchemaPhase, +) -> (Vec, McpSchemaSelectionStats) { + let raw_names = tools + .iter() + .zip(owners) + .map(|((name, _, _), owner)| { + name.strip_prefix(&mcp_canonical_name(owner, "")) + .unwrap_or(name) + .to_string() + }) + .collect::>(); + select_mcp_tools_for_context_with_raw_names( + tools, + owners, + &raw_names, + always_include_servers, + messages, + sticky_names, + phase, + ) +} + +#[cfg(test)] +pub(in crate::tools) fn select_mcp_tools_for_context_with_raw_names( + tools: &[(String, String, Value)], + owners: &[String], + raw_names: &[String], + always_include_servers: &[String], + messages: &[Value], + sticky_names: &[String], + phase: ToolSchemaPhase, +) -> (Vec, McpSchemaSelectionStats) { + select_mcp_tools_for_context_with_anchors( + tools, + owners, + raw_names, + always_include_servers, + messages, + sticky_names, + &McpSessionAnchors::default(), + phase, + ) +} + +/// The server a tool belongs to: its registry owner, else the server in its +/// canonical `mcp__server__tool` name. +fn mcp_tool_server<'a>( + tools: &'a [(String, String, Value)], + owners: &'a [String], + index: usize, +) -> Option<&'a str> { + owners + .get(index) + .map(String::as_str) + .filter(|owner| !owner.is_empty()) + .or_else(|| canonical_mcp_server(&tools[index].0)) +} + +#[allow(clippy::too_many_arguments)] +pub(in crate::tools) fn select_mcp_tools_for_context_with_anchors( + tools: &[(String, String, Value)], + owners: &[String], + raw_names: &[String], + always_include_servers: &[String], + messages: &[Value], + sticky_names: &[String], + anchors: &McpSessionAnchors, + phase: ToolSchemaPhase, +) -> (Vec, McpSchemaSelectionStats) { + // Once a menu is pinned, only what the user wrote may add to it. Assistant + // prose, tool calls and harness notices grow every round, and each tool + // they pulled in rewrote the `tools` block the provider had cached. + let authored = messages + .iter() + .filter(|message| crate::network::messages::is_user_turn_boundary(message)) + .cloned() + .collect::>(); + let terms = if sticky_names.is_empty() { + context_terms(messages) + } else { + context_terms(&authored) + }; + // The pinned menu outlives the turn, so a full one would never admit a + // tool by relevance again. What the newest user message points at is + // therefore seated ahead of the pin. It is the same on every round of a + // turn, so it changes the menu at most once per user message. + let fresh_terms = match authored.last() { + Some(latest) if !sticky_names.is_empty() => context_terms(std::slice::from_ref(latest)), + _ => std::collections::HashSet::new(), + }; + let (mut named, server_wide) = + explicitly_requested_mcp_tool_names(tools, owners, raw_names, messages); + // What the user asked for earlier in the session stays asked for after a + // compaction archived the message that said so (#2576). + for wanted in &anchors.requested { + if tools.iter().any(|(name, _, _)| name == wanted) && !named.contains(wanted) { + named.push(wanted.clone()); + } + } + let mut requested = named + .iter() + .filter_map(|wanted| tools.iter().position(|(name, _, _)| name == wanted)) + .collect::>(); + let mut server_requested = Vec::new(); + let mut previous = Vec::new(); + let mut relevant = Vec::new(); + let mut fresh = Vec::new(); + for (index, (name, description, _)) in tools.iter().enumerate() { + if named.contains(name) { + continue; + } + if !fresh_terms.is_empty() { + let score = mcp_tool_relevance(name, description, &fresh_terms); + if score >= MCP_RELEVANCE_THRESHOLD { + fresh.push((index, score)); + } + } + // The model may call a tool by its advertised or its canonical + // `mcp__server__tool` name; either is a use (#2502). A bare raw name + // that is not the advertised one could be a built-in's, so it is not. + // A call a compaction archived still counts (#2576). + let raw = raw_names.get(index).map(String::as_str).unwrap_or(name); + let canonical = owners + .get(index) + .map(|owner| mcp_canonical_name(owner, raw)) + .unwrap_or_else(|| name.clone()); + let was_used = anchors.used.contains(name) + || tool_name_was_used(name, messages) + || tool_name_was_used(&canonical, messages); + if server_wide.contains(name) { + server_requested.push(( + index, + was_used, + mcp_tool_rank_within_server(name, description, &terms), + )); + } else if was_used { + previous.push(index); + } else { + let score = mcp_tool_relevance(name, description, &terms); + // A single generic description word such as "result", "file", or + // "project" must not pull a large MCP suite into an unrelated + // request. Exact name terms score eight; two strong description + // matches score six. + if score >= MCP_RELEVANCE_THRESHOLD { + relevant.push((index, score)); + } + } + } + + // Relevance from the transcript may only widen the menu within servers the + // session has already engaged: one it used, one the user or a discovery + // call named, or a reserved one. A server new to the session is admitted + // only by what the user just wrote ("check my latest mails"), never by + // words older turns, assistant prose or a compaction left behind; the + // model can find anything else with `list_mcp_tools` (#2576). + let latest_terms = authored + .last() + .map(|latest| context_terms(std::slice::from_ref(latest))) + .unwrap_or_default(); + let mut engaged_servers = std::collections::HashSet::new(); + for index in requested + .iter() + .chain(server_requested.iter().map(|(index, _, _)| index)) + .chain(previous.iter()) + .copied() + { + if let Some(server) = mcp_tool_server(tools, owners, index) { + engaged_servers.insert(server); + } + } + for index in 0..tools.len() { + if let Some(server) = mcp_tool_server(tools, owners, index) { + if always_include_servers + .iter() + .any(|reserved| reserved == server) + || user_mentions_mcp_server(messages, server) + { + engaged_servers.insert(server); + } + } + } + for ranked in [&mut relevant, &mut fresh] { + ranked.retain(|(index, _)| { + mcp_tool_server(tools, owners, *index) + .is_some_and(|server| engaged_servers.contains(server)) + || (mcp_tool_relevance(&tools[*index].0, &tools[*index].1, &latest_terms) + >= MCP_RELEVANCE_THRESHOLD + // A server new to the session needs the message to name + // what the tool is; description words alone added an + // unrelated tool and rewrote the cached `tools` block. + && mcp_tool_name_matches(&tools[*index].0, &latest_terms)) + }); + // Two servers offering the same tool name with the same score are an + // ambiguous match: neither is admitted rather than the one whose + // server sorts first (#2576). + let snapshot = ranked.clone(); + ranked.retain(|(index, score)| { + let raw = raw_names + .get(*index) + .map(String::as_str) + .unwrap_or(&tools[*index].0); + !snapshot.iter().any(|(other, other_score)| { + other != index + && other_score == score + && raw_names + .get(*other) + .map(String::as_str) + .unwrap_or(&tools[*other].0) + == raw + && mcp_tool_server(tools, owners, *other) + != mcp_tool_server(tools, owners, *index) + }) + }); + } + // A named server can have more tools than the request may carry. The ones + // already in use and the ones the request's words point at go first; + // alphabetical order used to drop `send_…` behind `get_…` and `list_…`. + server_requested.sort_by(|left, right| { + right + .1 + .cmp(&left.1) + .then_with(|| right.2.cmp(&left.2)) + .then_with(|| tools[left.0].0.cmp(&tools[right.0].0)) + }); + requested.extend(server_requested.into_iter().map(|(index, _, _)| index)); + previous.sort_by(|left, right| tools[*left].0.cmp(&tools[*right].0)); + for ranked in [&mut relevant, &mut fresh] { + // Tied duplicates across servers were dropped above, so the name order + // here only seats two different tools, never picks a server. + ranked.sort_by(|(left_index, left_score), (right_index, right_score)| { + right_score + .cmp(left_score) + .then_with(|| tools[*left_index].0.cmp(&tools[*right_index].0)) + }); + } + + // Reserve complete configured server toolsets first. A reservation is + // all-or-none: if adding the complete set would exceed either hard limit, + // the server is reported as rejected and none of its tools are bound for + // this request. + let budget_bytes = mcp_schema_budget_bytes(); + let mut selected = Vec::new(); + let mut selected_indices = std::collections::HashSet::new(); + let mut rejected_indices = std::collections::HashSet::new(); + let mut selected_schema_bytes: usize = 0; + let mut per_server_bytes: std::collections::HashMap<&str, usize> = + std::collections::HashMap::new(); + let mut schema_budget_exhausted = false; + let mut reserved_servers = Vec::new(); + let mut rejected_reservations = Vec::new(); + let mut seen_servers = std::collections::HashSet::new(); + for server in always_include_servers { + if !seen_servers.insert(server.as_str()) { + continue; + } + let group = owners + .iter() + .enumerate() + .filter_map(|(index, owner)| (owner == server).then_some(index)) + .collect::>(); + if group.is_empty() { + continue; + } + let group_bytes = group.iter().fold(0usize, |total, index| { + let (name, description, schema) = &tools[*index]; + total.saturating_add(mcp_schema_bytes(name, description, schema)) + }); + // A single heavy server must not starve the rest of the catalog. + if group_bytes > MAX_MCP_PER_SERVER_SCHEMA_BYTES { + rejected_reservations.push(server.clone()); + schema_budget_exhausted = true; + rejected_indices.extend(group); + continue; + } + let count_fits = selected.len().saturating_add(group.len()) <= MAX_MCP_NATIVE_SCHEMAS; + let bytes_fit = selected_schema_bytes.saturating_add(group_bytes) <= budget_bytes; + if count_fits && bytes_fit { + for index in group { + if selected_indices.insert(index) { + selected.push(index); + } + } + selected_schema_bytes = selected_schema_bytes.saturating_add(group_bytes); + per_server_bytes.insert(server.as_str(), group_bytes); + reserved_servers.push(server.clone()); + } else { + rejected_reservations.push(server.clone()); + schema_budget_exhausted |= !bytes_fit; + rejected_indices.extend(group); + } + } + + // Explicitly requested tools stay first: naming one is a hard requirement, so it + // must outrank a pinned menu from a previous turn. Retention then follows. + // Because the pinned menu is itself the previous request's whole `tools` block, + // a requested name is almost always already pinned, so this ordering cannot + // shrink the pinned set — it only re-seats its members. Chaining retention last + // instead left it as a mere preference competing for an already-full budget, + // which is why consecutive requests selected disjoint name sets. (#1591) + let mut candidates = Vec::new(); + candidates.extend( + requested + .iter() + .copied() + .filter(|index| !rejected_indices.contains(index)) + .map(|index| (index, Admitted::Requested)), + ); + candidates.extend( + fresh + .iter() + .map(|(index, _)| *index) + .filter(|index| !rejected_indices.contains(index)) + .map(|index| { + // A pinned tool the message also points at was retained, not + // newly admitted; only its seat moved. + if sticky_names.contains(&tools[index].0) { + (index, Admitted::Retained) + } else { + (index, Admitted::Relevant) + } + }), + ); + // Tools the model has called in this conversation outrank the rest of + // the pin: a full pin of tools nobody used kept a used one out, and the + // model listed it again every turn (#2502). A used tool is almost always + // pinned already, so this rarely changes the menu. + candidates.extend( + previous + .iter() + .copied() + .filter(|index| !rejected_indices.contains(index)) + // A used tool is admitted for being used, pinned or not, so the + // log says why it is there (#2576). + .map(|index| (index, Admitted::Previous)), + ); + candidates.extend( + sticky_names + .iter() + .filter_map(|sticky| tools.iter().position(|(name, _, _)| name == sticky)) + .filter(|index| !rejected_indices.contains(index)) + .map(|index| (index, Admitted::Retained)), + ); + candidates.extend( + relevant + .iter() + .map(|(index, _)| *index) + .filter(|index| !rejected_indices.contains(index)) + .map(|index| (index, Admitted::Relevant)), + ); + // Attribute by the bucket that actually admitted the tool. Deriving the + // counts from the candidate lists instead skipped tools a reservation had + // already inserted, so a `previous` tool admitted by a reservation was + // selected but never reported as previously used. (#1591) + let mut admitted = std::collections::HashMap::new(); + for (index, bucket) in candidates { + if selected.len() >= MAX_MCP_NATIVE_SCHEMAS { + break; + } + if !selected_indices.insert(index) { + continue; + } + let (name, description, schema) = &tools[index]; + let bytes = mcp_schema_bytes(name, description, schema); + if selected_schema_bytes.saturating_add(bytes) > budget_bytes { + selected_indices.remove(&index); + schema_budget_exhausted = true; + continue; + } + // Per-server fairness: an explicit request always wins, but relevance + // alone must not let one heavy server consume the shared budget. + let owner = owners.get(index).map(String::as_str).unwrap_or(""); + let server_bytes = per_server_bytes.get(owner).copied().unwrap_or(0); + if bucket != Admitted::Requested + && server_bytes.saturating_add(bytes) > MAX_MCP_PER_SERVER_SCHEMA_BYTES + { + selected_indices.remove(&index); + schema_budget_exhausted = true; + continue; + } + admitted.entry(index).or_insert(bucket); + selected.push(index); + selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); + if !owner.is_empty() { + per_server_bytes.insert(owner, server_bytes.saturating_add(bytes)); + } + } + + let mut fallback_count = 0; + if selected.is_empty() && phase == ToolSchemaPhase::Established { + for preferred in MCP_DISCOVERY_CORE { + if selected.len() >= MCP_DISCOVERY_FALLBACK_COUNT { + break; + } + if let Some(index) = tools.iter().position(|(name, _, _)| name == preferred) { + if rejected_indices.contains(&index) { + continue; + } + if !selected_indices.insert(index) { + continue; + } + let (name, description, schema) = &tools[index]; + let bytes = mcp_schema_bytes(name, description, schema); + if selected_schema_bytes.saturating_add(bytes) <= budget_bytes { + selected.push(index); + selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); + } else { + selected_indices.remove(&index); + schema_budget_exhausted = true; + } + } + } + fallback_count = selected.len(); + } + + // Sticky and explicit tools can be promoted within the already selected + // surface. Reserved server tools stay first so a follow-up cannot break a + // complete configured reservation. + if !sticky_names.is_empty() { + let reserved_indices = owners + .iter() + .enumerate() + .filter_map(|(index, owner)| reserved_servers.contains(owner).then_some(index)) + .filter(|index| selected_indices.contains(index)) + .collect::>(); + let sticky_indices = sticky_names + .iter() + .filter_map(|name| tools.iter().position(|(tool_name, _, _)| tool_name == name)) + .collect::>(); + let mut prioritized = Vec::with_capacity(selected.len()); + let mut prioritized_set = std::collections::HashSet::with_capacity(selected.len()); + for index in reserved_indices + .into_iter() + .chain(requested.iter().copied()) + .chain(sticky_indices) + .chain(selected.iter().copied()) + { + if prioritized.len() >= MAX_MCP_NATIVE_SCHEMAS { + break; + } + if selected_indices.contains(&index) && prioritized_set.insert(index) { + prioritized.push(index); + } + } + selected = prioritized; + selected_schema_bytes = 0; + let mut within_budget = Vec::with_capacity(selected.len()); + for index in selected { + let (name, description, schema) = &tools[index]; + let bytes = mcp_schema_bytes(name, description, schema); + if selected_schema_bytes.saturating_add(bytes) > budget_bytes { + schema_budget_exhausted = true; + continue; + } + selected_schema_bytes = selected_schema_bytes.saturating_add(bytes); + within_budget.push(index); + } + selected = within_budget; + } + + // Emit in a stable order: the pinned menu keeps its seats in the order the + // previous request sent them, and a newly admitted tool goes after them. + // Sorting by catalog position put a new tool in the middle, which changed + // every byte after it and cost the provider's cached prefix. + let mut seen = std::collections::HashSet::with_capacity(selected.len()); + selected.retain(|index| seen.insert(*index)); + let pinned_seat = |index: usize| { + sticky_names + .iter() + .position(|name| name == &tools[index].0) + .unwrap_or(usize::MAX) + }; + selected.sort_by_key(|index| (pinned_seat(*index), *index)); + debug_assert!(selected.len() <= MAX_MCP_NATIVE_SCHEMAS); + let selected_set = selected + .iter() + .copied() + .collect::>(); + let selected_names = selected + .iter() + .map(|index| tools[*index].0.clone()) + .collect::>(); + let omitted_names = tools + .iter() + .enumerate() + .filter_map(|(index, (name, _, _))| { + (!selected_set.contains(&index)).then_some(name.clone()) + }) + .collect::>(); + // Each selected tool under the one bucket that admitted it; the counts + // are the sizes of these lists, so they always add up to `selected`. + let mut admitted_by: std::collections::BTreeMap<&'static str, Vec> = + std::collections::BTreeMap::new(); + for index in &selected { + // Having been called is the strongest reason a tool is offered, so a + // used tool is reported as such unless the user asked for it by name. + let used = previous.contains(index) && admitted.get(index) != Some(&Admitted::Requested); + let bucket = match admitted.get(index) { + _ if used => "previously_used", + Some(Admitted::Requested) => "requested", + Some(Admitted::Previous) => "previously_used", + Some(Admitted::Relevant) => "relevant", + Some(Admitted::Retained) => "retained", + None if mcp_tool_server(tools, owners, *index) + .is_some_and(|server| reserved_servers.iter().any(|name| name == server)) => + { + "reserved" + } + None => "fallback", + }; + admitted_by + .entry(bucket) + .or_default() + .push(tools[*index].0.clone()); + } + let bucket_len = |bucket: &str| admitted_by.get(bucket).map_or(0, Vec::len); + let stats = McpSchemaSelectionStats { + available: tools.len(), + selected: selected.len(), + requested: bucket_len("requested"), + relevant: bucket_len("relevant"), + previously_used: bucket_len("previously_used"), + fallback: fallback_count.min(selected.len()), + omitted: tools.len().saturating_sub(selected.len()), + selected_names, + omitted_names, + reserved_servers, + rejected_reservations, + phase, + mcp_schema_bytes: selected_schema_bytes, + mcp_schema_budget_bytes: budget_bytes, + schema_budget_exhausted, + admitted_by, + ..Default::default() + }; + (selected, stats) +} + +#[cfg(test)] +pub(in crate::tools) fn select_mcp_tools_for_context( + tools: &[(String, String, Value)], + messages: &[Value], +) -> (Vec, McpSchemaSelectionStats) { + select_mcp_tools_for_context_in_phase(tools, messages, ToolSchemaPhase::Established) +} + +#[cfg(test)] +pub(in crate::tools) fn select_mcp_tools_for_context_with_sticky_in_phase( + tools: &[(String, String, Value)], + messages: &[Value], + sticky_names: &[String], + phase: ToolSchemaPhase, +) -> (Vec, McpSchemaSelectionStats) { + select_mcp_tools_for_context_with_sticky_and_reservations_in_phase( + tools, + &[], + &[], + messages, + sticky_names, + phase, + ) +} + +#[cfg(test)] +pub(in crate::tools) fn select_mcp_tools_for_context_with_sticky( + tools: &[(String, String, Value)], + messages: &[Value], + sticky_names: &[String], +) -> (Vec, McpSchemaSelectionStats) { + select_mcp_tools_for_context_with_sticky_in_phase( + tools, + messages, + sticky_names, + ToolSchemaPhase::Established, + ) +} diff --git a/rustcode/engine/src/tools/schema/prompts.rs b/rustcode/engine/src/tools/schema/prompts.rs new file mode 100644 index 000000000..0e2909328 --- /dev/null +++ b/rustcode/engine/src/tools/schema/prompts.rs @@ -0,0 +1,623 @@ +use super::*; + +/// Regression budget for the invariant prompt prefix. Tool schemas are sent +/// separately for ApiNative requests and are intentionally not counted here. +#[cfg(test)] +pub(crate) const BASE_PROMPT_MAX_BYTES: usize = 4_700; +#[cfg(test)] +pub(crate) const BASE_PROMPT_MAX_TOKENS: usize = 1_020; + +/// Append the resolved execution policy after the cached, profile-independent +/// prompt so model switches cannot retain another profile's mutation limit. +pub(crate) fn append_tool_response_limit(prompt: &mut String, max_mutating_calls: usize) { + append_tool_response_policy( + prompt, + crate::config::ToolSchedulingPolicy { + max_mutating_calls, + ..Default::default() + }, + ); +} + +pub(crate) fn append_tool_response_policy( + prompt: &mut String, + policy: crate::config::ToolSchedulingPolicy, +) { + use std::fmt::Write; + + if policy.allow_batching { + write!( + prompt, + "\n\n# Tool response limit\n\ +This trusted profile permits a bounded batch of up to {} read-only calls and {} workspace-changing calls in one assistant response. \ +Control-plane calls first, reads follow; workspace changes grounded and sequential; never assume an unexecuted call ran. \ +Read-only calls do not consume the workspace-changing limit. \ +Calls beyond the limit are held by the harness and executed automatically in a later round: never reissue them.\n", + policy.max_read_only_calls, policy.max_mutating_calls + ) + } else { + write!( + prompt, + "\n\n# Tool response limit\n\ +The effective max_mutating_calls_per_response is {}. \ +Batch independent read-only calls freely in one assistant response and wait for their results before choosing the next action. \ +Workspace-changing calls (mutating `run_command` calls, file writes/edits and other tools with side effects) run \ +one after another in the order given, up to that limit per response; send several together only when a later one \ +does not depend on an earlier result. Read-only inspection never consumes this limit. Never assume an unexecuted call ran. \ +Calls beyond the limit are held by the harness and executed automatically in a later round: never reissue them.\n", + policy.max_mutating_calls + ) + } + .expect("writing to a String cannot fail"); + // The interface folds each batch of calls into one count line, so the + // sentence before a batch is what the reader follows the work by. + prompt.push_str( + "\n# Progress notes\n\ +Before each batch of tool calls, write one short plain sentence saying what you are about to do or what the last results showed. \ +One line, no headings or lists, and never one per call. Skip it only when the batch simply continues what the previous note already said.\n", + ); +} + +/// How a root agent formats its replies (docs/output-style.md). Every +/// RustCode frontend renders CommonMark with tables and highlighted fences, +/// so this part is sent to all of them; the clause in +/// [`OUTPUT_STYLE_VIZ_HINT`] only to those that draw `rustcode-viz`. +pub(crate) const OUTPUT_STYLE_PROMPT_HINT: &str = "# Output style\n\ +Replies render as Markdown. Lead with the answer or result; never restate the question or narrate what you are about to say. \ +Keep paragraphs short. Use headings only for long, multi-part answers; bullets for parallel items, numbered steps for sequences, \ +a table for comparisons. Fence code with its language and show changes as ```diff; put `path:line` citations in inline code. \ +Link issues and pull requests by their full URL (https://github.com/owner/repo/pull/12), never a bare #12. \ +No emoji, filler, or recap of what the reply already said. End with a next step only when the user has one to take.\n"; + +/// Added to [`OUTPUT_STYLE_PROMPT_HINT`] for frontends that draw +/// `rustcode-viz`: without it the reply repeated a chart as a table. +pub(crate) const OUTPUT_STYLE_VIZ_HINT: &str = "A rustcode-viz block replaces a table or list, never repeats one in prose; its summary carries the takeaway.\n"; + +/// Added to [`OUTPUT_STYLE_PROMPT_HINT`] while Smart UI is on: the view carries the +/// detail, so the text around it stays a line or two (its "a table" means a view's). +pub(crate) const OUTPUT_STYLE_SMART_UI_HINT: &str = + "Keep prose brief. Use HTML anchors for links in views.\n"; + +/// The output-style text for a frontend. With Smart UI on the agent is taught +/// views instead of `rustcode-viz`; otherwise it depends on the viz level. +pub(crate) fn output_style_hint(visualization_level: u8, smart_ui: crate::app::SmartUi) -> String { + let mut hint = String::from(OUTPUT_STYLE_PROMPT_HINT); + if smart_ui == crate::app::SmartUi::On { + hint.push_str(OUTPUT_STYLE_SMART_UI_HINT); + } else if visualization_level > 0 { + hint.push_str(OUTPUT_STYLE_VIZ_HINT); + } + hint.push('\n'); + hint +} + +/// The output-style guidance for an external harness that takes developer +/// instructions (Codex `thread/start` `developerInstructions`). It never +/// gets RustCode's root prompt, so it also carries the citation rule from +/// the Workflow section. +pub(crate) fn harness_output_style(smart_ui: crate::app::SmartUi) -> String { + let views = if smart_ui == crate::app::SmartUi::On { + OUTPUT_STYLE_SMART_UI_HINT + } else { + "" + }; + format!( + "{OUTPUT_STYLE_PROMPT_HINT}{views}Cite code as `path:line` with the full repo-relative path.\n" + ) +} + +/// What an external harness adds to its own system prompt: where it runs, so it can say so when asked and +/// link what it makes so the app opens it, that RustCode is what owns its threads and projects, then +/// either Smart UI when the user has it on or the `rustcode-viz` types the connected client draws (none +/// at level 0), then `skills` ([`crate::skills::harness_skills_note`], because this harness has no +/// `use_skill`), what this harness does that the model must work around (`harness_note`: what its +/// sandbox blocks on this platform, how it cuts tool output; empty when nothing), then [`harness_output_style`]. Codex takes this as +/// `developerInstructions` and Claude Code's adapter as its `systemPrompt`: it goes in every prompt, +/// so every byte here is paid on every turn. +pub(crate) fn harness_instructions( + harness: &str, + visualization_level: u8, + smart_ui: crate::app::SmartUi, + skills: Option<&str>, + harness_note: &str, +) -> String { + let harness = harness.split_whitespace().collect::>().join(" "); + format!( + "In case you're asked: you are running in RustCode through the {harness} harness. \ + No need to mention this otherwise. Asked to show something, take a screenshot into the working \ + directory or `$TMPDIR` and embed it with Markdown image syntax and its absolute path, outside any \ + view or fence, one per line. Link any other file you produce by its absolute path so the user can \ + open it from RustCode. RustCode is the app that owns this machine's threads, its projects and its \ + settings: when the `rustcode` tools (or `mcp__rustcode__*`) are listed, they answer what the user \ + asks about them; without them, `rustcode threads list --all` and `rustcode threads path ` do \ + the same from a shell. Thread data lives in `~/.config/rustcode/threads`, not in another tool's \ + database. Tokens and reported cost are `thread_usage` (or `rustcode usage`), and what the \ + harnesses recorded of turns and tool calls is `query_data` (or `rustcode data query \"\"`); \ + its description lists the tables.\n\n{}{}{}{}{}", + taught_visualization_hint(visualization_level, smart_ui), + harness_smart_ui_hint(smart_ui), + skills.unwrap_or_default(), + harness_note, + harness_output_style(smart_ui) + ) +} + +/// What Codex's own Windows sandbox denies, for a Codex thread there (#3526). RustCode passes no +/// Windows-specific policy: the sandbox holds its shell in a restricted token either way, and that +/// token cannot reach the WMI service, so the model is told what to read instead of retrying. +pub(crate) const CODEX_WINDOWS_SANDBOX_NOTE: &str = r#"# Sandbox on Windows +This thread's shell runs in Codex's Windows sandbox unless the user picks Full access. WMI answers out of process, so the sandbox denies it and `Get-CimInstance`, `Get-WmiObject`, `wmic` and `systeminfo` fail with `Access denied` (0x80041003); retrying or wrapping it does not help. Read the same facts without WMI: `Get-ItemProperty HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\0` and `HKLM:\HARDWARE\DESCRIPTION\System\BIOS` for the CPU and board, `[System.Environment]::ProcessorCount` and `[System.Environment]::OSVersion` for counts and version, `[System.IO.DriveInfo]::GetDrives()` for disks, and `Get-Counter` (performance counters, not WMI) for load and memory. Registry and .NET reads are not restricted. + +"#; + +/// Antigravity cuts a long tool result down to its head and tail and saves the rest in its own +/// folder (#4098). Models acted on the preview and missed the middle, so it is told to bound what a +/// command prints and to read the saved file when the middle matters. +pub(crate) const ANTIGRAVITY_OUTPUT_NOTE: &str = "# Long command output +This harness cuts a long tool result down to a preview with the middle removed, and saves the whole output to a file it names in the result (\"You can find the full output in a file at …\"). Bound what a command prints so the answer fits: `| head -n 100`, `rg -m 20`, `git diff --stat`, `wc -l` before reading, or a narrower path. When a result says it was truncated and the part you need is in the middle, read that saved file (with a line range or `rg`) instead of acting on the preview. + +"; + +/// [`CODEX_WINDOWS_SANDBOX_NOTE`] on Windows, where Codex sandboxes the shell at all. +pub(crate) fn codex_windows_sandbox_note() -> &'static str { + if cfg!(windows) { + CODEX_WINDOWS_SANDBOX_NOTE + } else { + "" + } +} + +/// The tag [`runtime_reminder`] wraps [`harness_instructions`] in, and the +/// engine strips from an echo of it (`harness/acp_child.rs`). +pub(crate) const RUNTIME_REMINDER_START: &str = ""; +pub(crate) const RUNTIME_REMINDER_END: &str = ""; + +/// [`harness_instructions`] as the opening block of a first prompt, for an +/// agent that has no `sessionCapabilities.systemPrompt` (pi-acp, OpenCode): it +/// still has to hear where it runs, what the client draws and what RustCode +/// owns. Tagged and labelled so the model does not read it as the user's +/// words; the engine drops the agent's echo of it (`strip_runtime_echo`). +pub(crate) fn runtime_reminder(instructions: &str) -> String { + format!( + "{RUNTIME_REMINDER_START}\nRustCode's setup instructions for this thread, not the user's message.\n\n{instructions}{RUNTIME_REMINDER_END}" + ) +} + +/// The current skills note alone, as the opening block of the first prompt after a harness without a +/// client system prompt loaded a saved session: that session holds the setup text it was first sent, +/// so a skill turned off since is only heard of here. Tagged like [`runtime_reminder`] so the engine +/// drops the agent's echo of it. +pub(crate) fn skills_reminder(note: &str) -> String { + format!( + "{RUNTIME_REMINDER_START}\nRustCode's current skills for this thread (replaces the Skills section of its setup instructions), not the user's message.\n\n{note}{RUNTIME_REMINDER_END}" + ) +} + +/// Smart UI for a harness that has no root prompt and no `use_skill`: the +/// fence, when to write a view, the kit's names, and what the sandbox blocks. +/// The format itself is `docs/smart-ui.md`. +pub(crate) const SMART_UI_HARNESS_HINT: &str = "\ +# Smart UI +Views run in chat: a ```rustcode-ui v1 fence with a title, built from the `::` catalog (the app draws each block; HTML only for what it lacks), no imports or network, max 64 KB. \ +Answer visually, asked or not: data, numbers, results, status, comparisons, plans or 4+ items go in a view (chart, bars, stats, table), never a Markdown table. Only short explanations, one fact, code and diffs stay Markdown. Be brief: one line with the finding before the view, nothing after it. Sources go last inside the view, folded: details.rc-sources > ol > li > a[href]. A report to another thread stays plain Markdown. +Pick: a trend → line chart; parts → stacked bar, donut; ranking → bars; options → cards; exact rows → table; a choice → form. +Catalog: `::` opens a block, `- ` items split at |, a blank line ends it; items may end {ok|warn|bad|info}; `code`, **bold** work. A name after a block is its heading. +:: title T · :: head Title | caption · :: h · :: p · :: callout info|ok|warn|bad · :: divider · :: details Summary · :: tab Name … :: end +:: hero Label / - 503 | 3.4x | sentence · :: stats / - 128 | Runs | +12 | 1,4,2 (spark) · :: bars / - label | 75 | 75 s | tip · :: progress / - EU | 72% | note +:: chart line|bar|stacked|hbar|donut Title | size=lg | line=150 normal | band=75-270 | end / x | series… heading row, then rows · :: heatmap, :: compare (yes|no|partial), :: table / a | b rows +:: list / - Title | detail | value · :: kv / - Key | value · :: cards / - Title | body | badge · :: steps / - [x] [>] [!] [ ] · :: timeline / - 10:02 | event | detail +:: findings / - high | file:line | finding | note · :: files / - path | +12 -3 · :: tags · :: term · :: code lang · :: actions / - Label | message · :: sources / - Title | url +:: form Message | Button / - select|choice name | Label | a, *b · - text|number|date name | Label · - check name | Label · - range name | Label | 0-100 = 40 +Card and item text: one short line. HTML otherwise: kit classes (.rc-*), no colours, fonts or heights of your own; data-rc-send=\"text\" sends a follow-up. No outer border, background or repeated title; no vh. If `smart_ui_check` is listed, run it first. + +"; + +/// [`SMART_UI_HARNESS_HINT`] when the setting is off, else the off note the +/// root prompt uses; nothing for a client that cannot run the blocks. +pub(crate) fn harness_smart_ui_hint(smart_ui: crate::app::SmartUi) -> &'static str { + match smart_ui { + crate::app::SmartUi::On => SMART_UI_HARNESS_HINT, + crate::app::SmartUi::Off => SMART_UI_OFF_PROMPT_HINT, + crate::app::SmartUi::Unsupported => "", + } +} + +/// Append the output-style guidance to a root prompt. Subagent replies are +/// read by the parent, not rendered, and compact prompts are for small +/// models where every token counts. +pub(crate) fn append_output_style_hint( + prompt: &mut String, + policy: ToolSchemaPolicy, + visualization_level: u8, + smart_ui: crate::app::SmartUi, +) { + if !policy.is_subagent() && !policy.compact_text_prompt { + prompt.push_str(&output_style_hint(visualization_level, smart_ui)); + } +} + +/// Short guidance for `rustcode-viz` blocks; the full format lives in +/// `docs/visualizations.md` and the TUI renderer validates every payload. +pub(crate) const VISUALIZATION_PROMPT_HINT: &str = "# Visualizations\n\ +When a chart, table, or tree beats prose (trends, comparisons, breakdowns, hierarchies), add a ```rustcode-viz fence even if not asked with one JSON object: \ +{\"version\":1,\"type\":\"bar_chart\",\"title\":\"..\",\"summary\":\"..\",\"items\":[{\"label\":\"..\",\"value\":1}]}; \ +\"table\" takes columns, rows (arrays), optional sort_by {column,descending}; \"tree\" takes nodes [{label,note,children}]. Max 30 bars, 50 rows, 120 nodes.\n\n"; + +/// The widget types added at visualization level 2, appended after +/// [`VISUALIZATION_PROMPT_HINT`] for frontends that draw them. Level 1 +/// frontends keep exactly the level 1 prompt. +pub(crate) const VISUALIZATION_PROMPT_HINT_LEVEL_2: &str = "Also: \"line_chart\" takes labels [x] and series \ +[{name,values:[number|null]}] for trends (max 4 series, 100 points); \"stat_list\" takes items \ +[{label,value,unit,note}] for headline numbers (max 12); \"checklist\" takes items \ +[{label,status:done|todo|in_progress|failed|skipped,note}] for progress (max 50).\n\n"; + +/// The visualization prompt text for a frontend's visualization level: none +/// for 0, the level 1 types for 1, and the level 2 types added from 2. +pub(crate) fn visualization_prompt_hint(level: u8) -> String { + match level { + 0 => String::new(), + 1 => VISUALIZATION_PROMPT_HINT.to_owned(), + _ => format!("{VISUALIZATION_PROMPT_HINT}{VISUALIZATION_PROMPT_HINT_LEVEL_2}"), + } +} + +/// What an agent is taught of `rustcode-viz`. With Smart UI on, nothing: one +/// tool per client state, so the rules never conflict. The blocks still render. +pub(crate) fn taught_visualization_hint(level: u8, smart_ui: crate::app::SmartUi) -> String { + if smart_ui == crate::app::SmartUi::On { + String::new() + } else { + visualization_prompt_hint(level) + } +} + +/// Append the visualization hint when the frontend renders `rustcode-viz` +/// blocks. Only the root agent writes user-facing replies, and compact prompts +/// are for small models where every token counts. Frontends that cannot draw +/// the blocks never get the hint, so they never see the JSON fences, and each +/// frontend is taught only the types its level draws. +pub(crate) fn append_visualization_hint( + prompt: &mut String, + policy: ToolSchemaPolicy, + visualization_level: u8, + smart_ui: crate::app::SmartUi, +) { + if !policy.is_subagent() && !policy.compact_text_prompt { + prompt.push_str(&taught_visualization_hint(visualization_level, smart_ui)); + } +} + +/// Guidance for `rustcode-ui v1` blocks (#2484), sent only to frontends that +/// advertise `_meta.rustcode.smartUi`; the format lives in `docs/smart-ui.md`. +pub(crate) const SMART_UI_PROMPT_HINT: &str = "# Smart UI\n\ +This app runs small views in replies: a ```rustcode-ui v1 fence of `::` catalog blocks. \ +Answer visually, asked or not: data, numbers, results, status, comparisons, plans or 4+ items go in a view (chart, bars, stats, table), never a Markdown table. \ +Only short explanations, one fact, code and diffs stay Markdown. Be brief: one line with the finding before the view, nothing after it. Sources go last inside the view, folded: details.rc-sources > ol > li > a[href]. A report to another thread stays plain Markdown. \ +First call `use_skill` with `smart-ui` directly (no `list_skills`).\n\n"; + +/// Sent instead of [`SMART_UI_PROMPT_HINT`] when the frontend could run the +/// blocks but the user has the setting off. Without it an agent asked for +/// "Smart UI" guesses a fence the app shows as source. +pub(crate) const SMART_UI_OFF_PROMPT_HINT: &str = "# Smart UI\n\ +This app has Smart UI (interactive HTML components in the chat), but it is turned off. \ +If the user asks for Smart UI or an interactive view, tell them to turn on Settings › Chat › Smart UI \ +and restart the engine; until then answer with Markdown or rustcode-viz, never an HTML fence.\n\n"; + +/// The Smart UI hint, if any, for a root prompt. +pub(crate) fn smart_ui_hint(smart_ui: crate::app::SmartUi) -> &'static str { + match smart_ui { + crate::app::SmartUi::On => SMART_UI_PROMPT_HINT, + crate::app::SmartUi::Off => SMART_UI_OFF_PROMPT_HINT, + crate::app::SmartUi::Unsupported => "", + } +} + +/// Append the Smart UI hint for a root prompt whose frontend runs the blocks. +pub(crate) fn append_smart_ui_hint( + prompt: &mut String, + policy: ToolSchemaPolicy, + smart_ui: crate::app::SmartUi, +) { + if !policy.is_subagent() && !policy.compact_text_prompt { + prompt.push_str(smart_ui_hint(smart_ui)); + } +} + +/// Append the `localhost_preview` guidance for a request that offers the +/// tool, and the other threads' for one that offers those. +pub(crate) fn append_preview_hint(prompt: &mut String, policy: ToolSchemaPolicy) { + if policy.include_preview_tool { + prompt.push_str(crate::preview::PREVIEW_PROMPT_HINT); + } + if policy.include_desktop_tool { + prompt.push_str(crate::desktop_control::PROMPT_HINT); + } + if policy.include_smart_ui_preview_tool { + prompt.push_str(crate::smart_ui::PREVIEW_PROMPT_HINT); + } + if policy.include_orchestration_tools { + prompt.push_str(crate::orchestration::prompt_hint( + policy.orchestration_version, + )); + } +} + +/// MCP lines of a textual tool contract, bounded like the native schema +/// selection. Text protocols used to inline every connected MCP tool with its +/// full schema; with a dozen servers that was 18k of a 20k-token prompt for a +/// small model (#2587). Tools past the global or per-server byte budget are +/// listed by name only, and `list_mcp_tools` `select` returns their schemas. +pub(super) fn textual_mcp_listing( + entries: &[(String, String, String, Value)], + compact: bool, + budget_bytes: usize, +) -> String { + let mut listed = String::new(); + let mut used = 0usize; + let mut per_server: HashMap<&str, usize> = HashMap::new(); + let mut names_only: std::collections::BTreeMap<&str, Vec<&str>> = Default::default(); + for (name, server, desc, schema) in entries { + let args = serde_json::to_string(schema).unwrap_or_default(); + let line = if compact { + format!("- {name} | Args: {args}\n") + } else { + format!("- {name} | Args: {args} | {desc}\n") + }; + let server_used = per_server.entry(server.as_str()).or_default(); + if used + line.len() <= budget_bytes + && *server_used + line.len() <= MAX_MCP_PER_SERVER_SCHEMA_BYTES + { + used += line.len(); + *server_used += line.len(); + listed.push_str(&line); + } else { + names_only + .entry(server.as_str()) + .or_default() + .push(name.as_str()); + } + } + if !names_only.is_empty() { + listed.push_str( + "- More MCP tools, listed by name without arguments; call `list_mcp_tools` with `select` to get a schema before using one:\n", + ); + for (server, names) in names_only { + listed.push_str(&format!(" - {server}: {}\n", names.join(", "))); + } + } + listed +} + +pub(crate) fn tool_system_prompt_for_policy( + policy: ToolSchemaPolicy, + protocol: crate::config::ToolProtocol, + agent_mode: crate::config::AgentMode, +) -> String { + // The first-turn-only `set_session_title` tool must not vary the system + // prompt: a turn-1/turn-2 difference here invalidates the whole cached + // prefix. Its guidance (and, for text protocols, its call shape) rides in + // the per-turn context tail instead; see `session_title_turn_hint`. + // `localhost_preview` is described by its own hint, appended only for + // sessions that have it (`append_preview_hint`), so the shared prompt + // never lists a tool most clients cannot run. + let policy = ToolSchemaPolicy { + include_session_title_tool: false, + include_preview_tool: false, + include_desktop_tool: false, + include_smart_ui_preview_tool: false, + include_orchestration_tools: false, + include_orchestration_v2_tools: false, + include_orchestration_v3_tools: false, + include_orchestration_v4_tools: false, + include_orchestration_v6_tools: false, + include_orchestration_v7_tools: false, + include_orchestration_v9_tools: false, + ..policy + }; + let mut p = String::new(); + + p.push_str( + "\n# Skills\n\ +Skills stay on demand; never probe speculatively. Call `list_skills` only when the request names a skill, the Relevant-skills hint names a match, or built-ins/shell are stuck. \ +For local machine state check the shell first, never `list_skills` first. \ +`list_skills` returns metadata only; `use_skill` loads the selected SKILL.md.\n\n", + ); + + if agent_mode == crate::config::AgentMode::Plan { + p.push_str( + "CRITICAL: You are operating in PLAN MODE (Read-only / Design mode).\n\ + - File writing, deletion, shell commands, delegation, and unknown tools are disabled; you can read, search, ask questions, and design, but CANNOT modify files or execute commands.\n\ + - Investigate before planning with `grep`, `glob`, and `view_file`: read the manifest, real call sites, crates, and existing patterns.\n\ + - Make the plan specific to THIS repository: name files, functions/structs, and inspected line ranges; resolve unknowns now, never guess dependencies or module layout, and state verified facts and uncertainties.\n\ + - Explain the plan and tell the user to switch to Build Mode (press Shift+Tab) to implement it.\n\n" + ); + } + + p.push_str( + "You are rustcode, a terminal coding agent.\n\ +# Workflow\n\ +- Act on change requests: locate, inspect, edit, verify. Prefer the smallest focused sequence once grounded; do not restate tasks or narrate tools. Finish with changed files, verification, and blockers.\n\ +- For research/review answers, label verified findings, judgments, and gaps, and never claim comprehensive coverage without evidence. Avoid fixed long templates. Cite `path:line` with full repo-relative paths.\n\ +- Use `sandbox/` for temporary work and `artifacts/` for persistent reports. Run commands expected to exceed 2s in the background and keep working; results arrive automatically, so never poll.\n\ +- `run_command` uses the platform shell. Chained shell commands are fine when inspectable; use `&&` for dependent commands, show destructive operations, and never mask required failures. Check from the nearest project manifest. If in-scope dependencies are missing, run the deterministic lockfile install once, then retry. Never run `cargo check` on a standalone `.rs` file.\n\ +- Prefer write tools for file creation; heredoc only for small appends/pipes.\n\ +- Do not branch, commit, push or open a PR unless the user or the project's instructions ask; then, if `git-feature-workflow` is available, load and follow it. Preserve unrelated work; never use `git add .`, `git add -A`, or `git add --all`.\n\ +- Tool results are authoritative: claim checks only after an observed exit code 0. Fix compiler/tool errors or warnings, then rerun failed or stale checks. Subagent reports are advisory; inspect the workspace yourself.\n\ +- Use native `grep`/`glob` for exact discovery, `rg` through `run_command` for advanced searches, and SocratiCode `codebase_*` for semantic relationships. Inspect the exact range before editing; never guess lines, APIs, or dependencies.\n\ +- Batch independent reads in one response; mutations run in order, control-plane calls first. Wait for results before the next calls. Give each call a short `summary` for the user.\n\ +- Chained shell observations are fine when small and inspectable. `view_file` returns numbered text and continuation metadata; complete results are authoritative, so do not reread them—edit or verify next. For manual previews, use the user's exact port, do not start/probe/fallback, and let them run it after verification; do not start a server merely to inspect a static app.\n\ +- Match neighboring signatures, state/lock, and error conventions.\n\ +- Run focused checks and cover boundaries for complex logic.\n\ +- Read-only tools run immediately; modifying/destructive operations require confirmation. Use `ask_question` only for ambiguous requirements or explicit validation, never routine confirmation. The UI supplies the write-in slot; do not include `Other`. Finish with a plain-text summary.\n\n\ +# Avoiding loops\n\ +- Avoid unchanged rereads; use `view_file` with `start_line`/`end_line` or existing evidence. Correct errors and change empty queries. +- Repeated reads, no-ops, and failed attempts are advisory loop signals, not a hard stop. Avoid endlessly repeating an identical call, but continue when needed with a different `view_file` range, `grep`, edit, or test. Use cached replay content when supplied; if a replayed read is incomplete or unavailable, choose another useful inspection. An edit that reports \"already applied\" changed nothing on disk, so do not re-issue that identical edit without new evidence. +- Use `todo_write` only for complex 3+ step work, not routine edits, git, or simple questions; update it at milestones.\n\n" + ); + + // Gate on the same condition as the agent tool list below: promising a + // delegation workflow with zero callable subagent tools made the model + // probe `run_command` and `list_mcp_tools` for a `spawn_agent` that was + // never offered. (#1589) + if policy.include_agent_tools && agent_mode != crate::config::AgentMode::Plan { + p.push_str( + "# Delegation Policy\n\\ +- Subagent tools are available by default; use them when parallel work or independent review will help the task.\n\\ +- Before delegating, identify the critical path and keep blockers in the main agent. Delegate only bounded, self-contained side tasks with clear outputs and disjoint write scopes.\n\\ +- Review every subagent result and inspect its workspace changes before treating the task as complete.\n\\n", + ); + } else if policy.profile == ToolSchemaProfile::Coding + && agent_mode != crate::config::AgentMode::Plan + { + // Say why there is no agent tool instead of staying silent: with no + // hint the model spent rounds searching MCP for one. (#1710) + p.push_str( + "# Delegation\n\ +- No agent tools; don't search. `/delegate` unless config disables.\n\n", + ); + } + + p.push_str("# Tool Format\n"); + match protocol { + crate::config::ToolProtocol::Json => { + p.push_str( + "Active tool protocol: textual JSON fence. Call tools only as fenced `tool` blocks containing one JSON object; emit no prose before/after.\n\n\ + ```tool\n\ + {\"name\": \"tool_name\", \"arguments\": {...}}\n\ + ```\n\n\ + Rules: keys are \"name\" and \"arguments\"; argument values use their proper JSON types. Use only the ```tool fence (never ```tool_code, ```json, or another fence) and never duplicate a call. Batch independent reads as multiple fences; mutations run in order. Wait for results before the next calls.\n\n" + ); + } + crate::config::ToolProtocol::Native => { + p.push_str( + "Active tool protocol: textual native tags. Call tools only with native tags; emit no prose before/after.\n\n\ + [TOOL_CALLS]tool_name[ARGS]{\"arg_name\": \"value\"}\n\n\ + Rules: batch independent reads as multiple [TOOL_CALLS] markers; mutations run in order, control-plane calls first. Wait for results before the next calls. Arguments must be a valid JSON object matching the tool parameters.\n\n" + ); + } + crate::config::ToolProtocol::ApiNative => { + p.push_str( + "Active tool protocol: API-native. Tools use the API's native function-calling interface: invoke them directly; do NOT print tool calls as text or JSON. Batch independent reads together; mutations run in order, control-plane calls first. Wait for results before the next action. When complete, reply with a plain-text summary and no tool call.\n\n" + ); + } + } + + // Text protocols enumerate tools in the prompt. ApiNative carries the full + // tool schema in the request's `tools` field instead, so listing them here + // would only duplicate that and waste context. That also means a filtered + // `tools` block is the model's only view of the surface, so state the + // filtering and the discovery route before returning; it used to mention + // neither and left a silent-drop rejection as the only feedback. (#1589) + if matches!(protocol, crate::config::ToolProtocol::ApiNative) { + p.push_str( + "# Tool Surface\n\ +This request's tool list is filtered, not exhaustive. A listed tool is the only one carrying its argument schema here, and the list stays fixed for the whole turn. \ +Never guess MCP server names: see MCP Servers, then `list_mcp_tools` `select` for schemas. Any registered tool works by its exact name.\n\n", + ); + return p; + } + + p.push_str("For connected services with a matching MCP server listed, prefer their tools over shell. With no matching server, check the shell first; never probe `list_mcp_tools` speculatively.\n\n"); + p.push_str("Available tools:\n"); + for t in TOOLS { + if !text_builtin_is_advertised(t, policy, agent_mode) { + continue; + } + if policy.compact_text_prompt { + p.push_str(&format!("- {} | Args: {}\n", t.name, t.arguments)); + } else { + p.push_str(&format!( + "- {} | Args: {} | {}\n", + t.name, t.arguments, t.description + )); + } + } + if policy.include_mcp_tools && agent_mode != crate::config::AgentMode::Plan { + let entries = collect_mcp_tools_with_servers() + .into_iter() + .filter(|(name, ..)| policy.offers_mcp_tool(name)) + .map(|(name, server, _, desc, schema)| (name, server, desc, schema)) + .collect::>(); + p.push_str(&textual_mcp_listing( + &entries, + policy.compact_text_prompt, + mcp_schema_budget_bytes(), + )); + } + if policy.include_agent_tools && agent_mode != crate::config::AgentMode::Plan { + p.push_str("- spawn_agent | Args: {\"task\":\"task description\",\"context_inheritance\":\"minimal|evidence|recent|fork\",\"evidence\":\"selected facts\"} | Start a fresh child; default minimal. Optional agent_type explorer|worker|default. Writes require explicit write_access or agent_type worker, plus allowed_paths and verification. Returns JSON with agent_id.\n"); + p.push_str("- send_agent | Args: {\"id\": subagent_id, \"message\": \"message\", \"interrupt\": false} | Follow up an idle subagent or steer an active child at its next safe boundary; interrupt stops its current turn and redirects it now.\n"); + if policy.profile == ToolSchemaProfile::Coding { + p.push_str("- set_goal | Args: {\"goal\": \"goal description\"} | Set a new long-running task and switch the agent to continuous autoloop mode.\n"); + p.push_str("- todo_write | Args: {\"todos\": [{\"id\": \"t1\", \"content\": \"step\", \"status\": \"pending|in_progress|completed|blocked\", \"priority\": \"high|medium|low\"}], \"merge\": false} | Replace the persistent task plan; with merge true, update only the steps whose id you give. Use this at the start of multi-step work and update it as steps finish.\n"); + } + } + + if policy.compact_text_prompt { + p.push_str("\nUse the exact tool names and JSON argument shapes listed above.\n"); + return p; + } + + match protocol { + crate::config::ToolProtocol::Json => { + p.push_str( + "\nExample (task — needs a tool):\n\ +User: Where is the agent loop implemented?\n\ +Assistant:\n\ +```tool\n\ +{\"name\": \"grep\", \"arguments\": {\"pattern\": \"agent loop\", \"include\": \"*.rs\"}}\n\ +```\n\n\ +Example (conversation — no tool):\n\ +User: hello, how are you?\n\ +Assistant: Hi! Ready to help with your code. What are you working on?\n", + ); + } + crate::config::ToolProtocol::Native => { + p.push_str( + "\nExample (task — needs a tool):\n\ +User: Where is the agent loop implemented?\n\ +Assistant:\n\ +[TOOL_CALLS]grep[ARGS]{\"pattern\": \"agent loop\", \"include\": \"*.rs\"}\n\n\ +Example (conversation — no tool):\n\ +User: hello, how are you?\n\ +Assistant: Hi! Ready to help with your code. What are you working on?\n", + ); + } + // ApiNative returns early above (tools come from the request schema, not + // the prompt), so this arm is unreachable but keeps the match exhaustive. + crate::config::ToolProtocol::ApiNative => {} + } + + p +} + +/// First-turn guidance for `set_session_title`, injected into the per-turn +/// context tail so the cached system prompt stays byte-identical across turns. +/// Text protocols list tools only in the system prompt, so the hint also +/// carries the call shape there; API-native requests get the schema from the +/// request's `tools` field. +pub(crate) fn session_title_turn_hint(protocol: crate::config::ToolProtocol) -> String { + let mut hint = String::from( + "First-turn session title: a concise title is already saved from the user's request. Call `set_session_title` before doing other work. Name the main task in 2 to 4 plain words when possible, using at most 32 characters. Do not copy the full prompt, transcript, or secrets into the title.", + ); + if !matches!(protocol, crate::config::ToolProtocol::ApiNative) { + let tool = &crate::tools::misc::SET_SESSION_TITLE; + hint.push_str(&format!( + "\nAvailable this turn only:\n- {} | Args: {} | {}", + tool.name, tool.arguments, tool.description + )); + } + hint +} + +pub fn tool_system_prompt( + include_agent_tools: bool, + protocol: crate::config::ToolProtocol, + agent_mode: crate::config::AgentMode, +) -> String { + tool_system_prompt_for_policy( + ToolSchemaPolicy::root_for_mode(include_agent_tools, agent_mode), + protocol, + agent_mode, + ) +} diff --git a/rustcode/engine/src/tools/schema/response_limit_tests.rs b/rustcode/engine/src/tools/schema/response_limit_tests.rs new file mode 100644 index 000000000..5d99a0475 --- /dev/null +++ b/rustcode/engine/src/tools/schema/response_limit_tests.rs @@ -0,0 +1,58 @@ +use super::*; +use crate::config::{AgentMode, ModelProfile, ToolProtocol}; + +#[test] +fn mutation_guidance_matches_effective_policy_for_every_protocol() { + for protocol in [ + ToolProtocol::ApiNative, + ToolProtocol::Json, + ToolProtocol::Native, + ] { + for policy in [ + ToolSchemaPolicy::root_for_mode(false, AgentMode::Build), + ToolSchemaPolicy::subagent(), + ] { + let base = tool_system_prompt_for_policy(policy, protocol, AgentMode::Build); + // Reuse the same base as the root prompt cache does, including + // switching back to the default after a profile override. + for configured in [None, Some(3), Some(0), Some(usize::MAX), None] { + let profile = ModelProfile { + max_mutating_calls_per_response: configured, + ..ModelProfile::default() + }; + let limit = profile.max_mutating_calls_per_response(); + let mut prompt = base.clone(); + append_tool_response_limit(&mut prompt, limit); + assert!(prompt.contains(&format!( + "effective max_mutating_calls_per_response is {limit}." + ))); + assert_eq!(prompt.matches("# Tool response limit").count(), 1); + assert!(prompt.contains("Read-only inspection never consumes this limit")); + assert!(prompt.contains("Never assume an unexecuted call ran")); + + // The shell guidance must agree with the actual executor: + // mutating commands consume the mutation allowance while + // read-only inspection does not. + let calls = (0..=limit) + .map(|_| crate::tools::ToolCall { + name: "run_command".into(), + arguments: serde_json::json!({"command": "cargo test"}), + call_id: None, + }) + .collect(); + let (kept, dropped) = crate::tools::partition_tool_batch(calls, limit); + assert_eq!(kept.len(), limit); + assert_eq!(dropped.len(), 1); + } + } + } +} + +#[test] +fn native_protocol_batches_reads_and_limits_mutations() { + let prompt = tool_system_prompt(false, ToolProtocol::Native, AgentMode::Build); + + assert!(prompt.contains("multiple [TOOL_CALLS] markers")); + assert!(prompt.contains("mutations run in order")); + assert!(!prompt.contains("exactly one [TOOL_CALLS] marker")); +} diff --git a/rustcode/engine/src/tools/schema/schema_budget_tests.rs b/rustcode/engine/src/tools/schema/schema_budget_tests.rs new file mode 100644 index 000000000..99bbfb50f --- /dev/null +++ b/rustcode/engine/src/tools/schema/schema_budget_tests.rs @@ -0,0 +1,261 @@ +use super::*; + +/// Ceiling for the built-in half of the native `tools` block under the +/// root coding policy with agent tools, the widest menu a request carries. +/// +/// The block was 31,659 bytes before its descriptions were trimmed to +/// 23,583 (#1826). The 25 KiB ceiling accommodates archive retrieval and +/// MCP server management (#1890) while staying below the old size. It is +/// sent on every request, so keep new descriptions concise and measure +/// their cost. Run with `-- --nocapture` for the per-tool table. +const BUILTIN_SCHEMA_BYTE_BUDGET: usize = 25 * 1024; + +/// Room the plain root block must keep under that budget, so the next tool +/// does not use the last free byte. +const MIN_BUILTIN_SCHEMA_HEADROOM_BYTES: usize = 256; + +/// Serialized bytes of every built-in tool's native schema entry, largest +/// first, measured the way the request builder serializes it. Covers the +/// whole registry and the agent-control tools, advertised or not. +fn builtin_schema_sizes() -> Vec<(&'static str, usize)> { + let entry = |name: &str, description: &str, parameters: Value| { + // One array element, without the array's own brackets. + serialized_schema_bytes(&[serde_json::json!({ + "type": "function", + "function": { + "name": name, + "description": description, + "parameters": provider_compatible_schema(parameters), + } + })]) - 2 + }; + let mut sizes = TOOLS + .iter() + .map(|tool| { + ( + tool.name, + entry(tool.name, tool.description, schema_for_tool(tool.name)), + ) + }) + .chain(AGENT_TOOL_SPECS.iter().map(|(name, description, _)| { + (*name, entry(name, description, schema_for_agent_tool(name))) + })) + .collect::>(); + sizes.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + sizes +} + +/// Room the newest client's block must keep under the hard cap. Without +/// it the next tool added here fits the cap by 1 byte and the block still +/// shrinks on the request after that; the assertion turns the next +/// addition into a build failure with the number to free (#3376). +const MIN_ORCHESTRATION_HEADROOM_BYTES: usize = 2 * 1024; + +#[test] +fn the_orchestration_tools_fit_the_hard_cap() { + // Every supported client version gets every tool its version + // advertises in its built-in schema: the hard cap must never withhold + // one the client can answer, since the tool is then silently missing + // from the menu. This is the regression test for the 41 KiB cap that + // cut `thread_status`, `merge_when_green` and `cleanup_worktree` from a + // v9 client (#3376): the names are compared, not only the count, so a + // swap cannot pass as a match. + for version in 1..=crate::orchestration::VERSION { + let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); + let expected = crate::tools::TOOLS + .iter() + .filter(|tool| builtin_is_advertised(tool, policy)) + .map(|tool| tool.name) + .collect::>(); + let (tools, withheld) = build_builtin_native_tools_schema(policy); + let kept = tools + .iter() + .filter_map(|tool| tool["function"]["name"].as_str()) + .collect::>(); + let bytes = serialized_schema_bytes(&tools); + println!( + "orchestration v{version}: {bytes} bytes, {} of {} tools, {} bytes free, withheld {withheld:?}", + kept.len(), + expected.len(), + MAX_BUILTIN_NATIVE_SCHEMA_BYTES - bytes + ); + assert_eq!(kept, expected, "v{version} lost a tool to the cap"); + assert!(withheld.is_empty(), "v{version} withheld: {withheld:?}"); + assert!( + bytes < MAX_BUILTIN_NATIVE_SCHEMA_BYTES, + "v{version} is {bytes} bytes, over the hard cap" + ); + if version == crate::orchestration::VERSION { + let free = MAX_BUILTIN_NATIVE_SCHEMA_BYTES - bytes; + assert!( + free >= MIN_ORCHESTRATION_HEADROOM_BYTES, + "v{version} has {free} bytes free, under the {MIN_ORCHESTRATION_HEADROOM_BYTES} \ + a new tool needs: shorten descriptions in `tools/misc.rs` and `tools/schema.rs` first" + ); + } + } + // A client below 5 is not shown an argument its app cannot answer. + let start_schema = |version: u8| { + let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); + let (tools, _) = build_builtin_native_tools_schema(policy); + tools + .into_iter() + .find(|tool| tool["function"]["name"] == crate::orchestration::START_SESSION) + .expect("start_session") + }; + assert!(start_schema(4)["function"]["parameters"]["properties"]["account"].is_null()); + assert!(start_schema(5)["function"]["parameters"]["properties"]["account"].is_object()); + // A standalone thread arrived in v15 (issue 3443): v14 never sees the + // field, so an app that cannot start one is not offered it. + assert!(start_schema(14)["function"]["parameters"]["properties"]["standalone"].is_null()); + assert!(start_schema(15)["function"]["parameters"]["properties"]["standalone"].is_object()); + // Nor is v9 shown files to attach, which its app would drop. + let message_schema = |version: u8| { + let policy = ToolSchemaPolicy::root(true).with_orchestration_tools(version); + let (tools, _) = build_builtin_native_tools_schema(policy); + tools + .into_iter() + .find(|tool| tool["function"]["name"] == crate::orchestration::MESSAGE_SESSION) + .expect("message_session") + }; + assert!(message_schema(9)["function"]["parameters"]["properties"]["attachments"].is_null()); + assert!(message_schema(10)["function"]["parameters"]["properties"]["attachments"].is_object()); +} + +#[test] +fn the_block_check_is_not_a_built_in_tool() { + // It is listed by the `rustcode` MCP server an external harness runs, + // and answered there; a RustCode turn would only get the error handler. + assert!( + crate::tools::TOOLS + .iter() + .any(|tool| tool.name == crate::smart_ui::CHECK_TOOL_NAME) + ); + for policy in [ + ToolSchemaPolicy::root(true), + ToolSchemaPolicy::read_only_inspection(), + ] { + let (tools, _) = build_builtin_native_tools_schema(policy); + assert!( + !tools + .iter() + .any(|tool| tool["function"]["name"] == crate::smart_ui::CHECK_TOOL_NAME), + "the block check is never a built-in tool" + ); + } +} + +#[test] +fn the_link_tool_is_built_in_for_every_client() { + // The `rustcode` MCP server an external harness runs lists and answers + // it (`orchestration/mcp_server.rs`, #3369), and a RustCode turn + // answers it in `pull_watch::answer` through its own handler: since + // #3376 freed the room, it is advertised to every client instead of + // only to an external harness. + assert!( + crate::tools::TOOLS + .iter() + .any(|tool| tool.name == crate::pull_watch::LINK_TOOL_NAME) + ); + for policy in [ + ToolSchemaPolicy::root(false), + ToolSchemaPolicy::root(true), + ToolSchemaPolicy::root(true).with_orchestration_tools(crate::orchestration::VERSION), + ] { + let (tools, withheld) = build_builtin_native_tools_schema(policy); + assert!( + tools + .iter() + .any(|tool| tool["function"]["name"] == crate::pull_watch::LINK_TOOL_NAME), + "the link tool is missing from the built-in block: {policy:?}, withheld {withheld:?}" + ); + } + // It links a thread, so it is not a read-only inspection tool. + let (tools, _) = build_builtin_native_tools_schema(ToolSchemaPolicy::read_only_inspection()); + assert!( + !tools + .iter() + .any(|tool| tool["function"]["name"] == crate::pull_watch::LINK_TOOL_NAME) + ); +} + +#[test] +fn builtin_schema_bytes_stay_within_budget() { + let sizes = builtin_schema_sizes(); + for (name, bytes) in &sizes { + println!("{bytes:>6} {name}"); + } + println!( + "{:>6} all {} built-in and agent tools", + sizes.iter().map(|(_, bytes)| bytes).sum::(), + sizes.len() + ); + + let (tools, withheld) = build_builtin_native_tools_schema(ToolSchemaPolicy::root(true)); + let bytes = serialized_schema_bytes(&tools); + println!( + "{bytes:>6} advertised built-in block, {} tools (budget {BUILTIN_SCHEMA_BYTE_BUDGET})", + tools.len() + ); + assert!( + withheld.is_empty(), + "the byte cap withheld built-in tools: {withheld:?}" + ); + assert!( + bytes <= BUILTIN_SCHEMA_BYTE_BUDGET, + "built-in tool schemas grew to {bytes} bytes, over the {BUILTIN_SCHEMA_BYTE_BUDGET} budget; \ + shorten a description (largest first: {:?})", + &sizes[..5] + ); + // A budget reached to the last byte is a budget that fails the next + // tool that arrives, which is how the versioned block lost three tools + // under its old cap (#3376). Keep room for one modest addition. + let free = BUILTIN_SCHEMA_BYTE_BUDGET - bytes; + assert!( + free >= MIN_BUILTIN_SCHEMA_HEADROOM_BYTES, + "the built-in block has {free} bytes free, under the {MIN_BUILTIN_SCHEMA_HEADROOM_BYTES} \ + a new tool needs: shorten a description (largest first: {:?})", + &sizes[..5] + ); + // The budget only means something while it sits under the hard cap + // that starts withholding tools. + assert!(BUILTIN_SCHEMA_BYTE_BUDGET < MAX_BUILTIN_NATIVE_SCHEMA_BYTES); +} + +#[test] +fn cached_builtin_schema_matches_a_fresh_build_for_each_policy() { + for policy in [ + ToolSchemaPolicy::root(false), + ToolSchemaPolicy::root(true), + ToolSchemaPolicy::root(true).with_session_title_tool(), + ToolSchemaPolicy::read_only_inspection(), + ] { + let (tools, withheld) = build_builtin_native_tools_schema(policy); + let cached = cached_builtin_native_tools_schema(policy); + assert_eq!(cached.tools, tools, "{policy:?}"); + assert_eq!(cached.withheld, withheld, "{policy:?}"); + assert_eq!(cached.bytes, serialized_schema_bytes(&tools), "{policy:?}"); + assert!(Arc::ptr_eq( + &cached, + &cached_builtin_native_tools_schema(policy) + )); + } +} + +/// Trimming must never leave a tool undescribed, and a description pays +/// for every byte, including stray runs of spaces. +#[test] +fn every_builtin_tool_keeps_a_description() { + for tool in TOOLS { + assert!( + tool.description.trim().len() >= 20, + "{} lost its description", + tool.name + ); + assert!( + !tool.description.contains(" "), + "{} has a run of spaces in its description", + tool.name + ); + } +} diff --git a/scripts/comment-baseline.txt b/scripts/comment-baseline.txt index 2c92c890f..945247b04 100644 --- a/scripts/comment-baseline.txt +++ b/scripts/comment-baseline.txt @@ -1014,7 +1014,12 @@ 2 rustcode/engine/src/tools/misc/web.rs 44 rustcode/engine/src/tools/mod.rs 2 rustcode/engine/src/tools/scheduled_jobs_tests.rs -190 rustcode/engine/src/tools/schema.rs +42 rustcode/engine/src/tools/schema.rs +5 rustcode/engine/src/tools/schema/mcp_read_classification_tests.rs +90 rustcode/engine/src/tools/schema/mcp_selection.rs +23 rustcode/engine/src/tools/schema/prompts.rs +5 rustcode/engine/src/tools/schema/response_limit_tests.rs +25 rustcode/engine/src/tools/schema/schema_budget_tests.rs 7 rustcode/engine/src/tools/search.rs 93 rustcode/engine/src/tools/tests.rs 156 rustcode/engine/src/tools/tests/protocol.rs diff --git a/scripts/rust-size-baseline.txt b/scripts/rust-size-baseline.txt index ff8e412ae..ad54e9c52 100644 --- a/scripts/rust-size-baseline.txt +++ b/scripts/rust-size-baseline.txt @@ -41,5 +41,4 @@ 2300 rustcode/engine/src/skills.rs 2400 rustcode/engine/src/tools/exec.rs 3300 rustcode/engine/src/tools/exec/policy.rs -3700 rustcode/engine/src/tools/schema.rs 3700 rustcode/engine/src/worktrees.rs