The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(tool_prep_tests): update test to match new tool preparation logic
Steven Enamakelf588ab0373b4
diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rsindex f77a1015f1..c75c89b126 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs@@ -49,434 +49,8 @@ fn unprefixed_delegate_name_overrides_are_treated_as_spawn_tools() {}}-// ── Essential-action reservation (#6033) ────────────────────────────────--use crate::agent::prompts::ConnectedIntegrationTool;-use tinyagents_harness::tool::{rank_tools_by_prompt, SelectableTool};--fn action(name: &str) -> ConnectedIntegrationTool {- ConnectedIntegrationTool {- name: name.to_string(),- description: format!("{name} description"),- parameters: None,- }-}--/// The catalogue the ranker sees for Gmail in the failing case: every-/// content-returning action gated out, twelve `LIST_*` slots kept.-fn gmail_catalogue() -> Vec<ConnectedIntegrationTool> {- [- "GMAIL_LIST_CSE_IDENTITIES",- "GMAIL_LIST_DRAFTS",- "GMAIL_LIST_LABELS",- "GMAIL_LIST_MESSAGES",- "GMAIL_LIST_THREADS",- "GMAIL_FETCH_EMAILS",- "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",- "GMAIL_SEND_EMAIL",- ]- .iter()- .map(|n| action(n))- .collect()-}--#[test]-fn essentials_are_reserved_ahead_of_ranked_hits() {- let actions = gmail_catalogue();- // The ranker picked only LIST_* actions — the #6033 repro.- let hits = vec![0, 1, 2, 3, 4];- let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);- let names: Vec<&str> = selected.iter().map(|&i| actions[i].name.as_str()).collect();-- assert_eq!(- &names[..2],- &["GMAIL_FETCH_EMAILS", "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID"],- "essentials come first, in table order"- );- assert!(- !names.contains(&"GMAIL_SEND_EMAIL"),- "a read prompt must not be handed the send action: {names:?}"- );- assert!(- names.contains(&"GMAIL_LIST_MESSAGES"),- "ranked hits still follow the essentials"- );-}--#[test]-fn an_essential_the_ranker_already_picked_costs_no_extra_slot() {- let actions = gmail_catalogue();- // Index 5 is GMAIL_FETCH_EMAILS — already ranked.- let hits = vec![5, 0, 1];- let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);-- let fetches = selected- .iter()- .filter(|&&i| actions[i].name == "GMAIL_FETCH_EMAILS")- .count();- assert_eq!(- fetches, 1,- "no duplicate index for an already-ranked essential"- );- assert_eq!(- selected.len(),- selected- .iter()- .collect::<std::collections::HashSet<_>>()- .len(),- "selection is duplicate-free"- );-}--#[test]-fn selection_never_exceeds_the_top_k_budget() {- let actions = gmail_catalogue();- let hits: Vec<usize> = (0..actions.len()).collect();- for top_k in [0_usize, 1, 3, 4, 12] {- let selected = select_actions_with_essentials("gmail", &actions, &hits, top_k);- assert!(- selected.len() <= top_k,- "top_k={top_k} budget exceeded: {} kept",- selected.len()- );- assert_eq!(- selected.len(),- selected- .iter()- .collect::<std::collections::HashSet<_>>()- .len(),- "top_k={top_k} produced a duplicate index"- );- }-}--#[test]-fn an_unlisted_toolkit_is_an_exact_passthrough() {- let actions: Vec<_> = ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]- .iter()- .map(|n| action(n))- .collect();- let hits = vec![1, 0];- assert_eq!(- select_actions_with_essentials("slack", &actions, &hits, 12),- hits,- "a toolkit with no essentials must rank exactly as before"- );-}--#[test]-fn an_essential_absent_from_the_toolkit_is_skipped_not_guessed() {- // Connected Gmail exposing none of the essentials: the helper must not- // invent an index or panic.- let actions: Vec<_> = ["GMAIL_LIST_LABELS", "GMAIL_LIST_THREADS"]- .iter()- .map(|n| action(n))- .collect();- let hits = vec![0, 1];- let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);- assert_eq!(selected, hits);- assert!(selected.iter().all(|&i| i < actions.len()));-}--#[test]-fn toolkit_lookup_is_case_insensitive() {- assert_eq!(- essential_actions_for_toolkit("Gmail"),- essential_actions_for_toolkit("gmail")- );- assert!(!essential_actions_for_toolkit("GMAIL").is_empty());- assert!(essential_actions_for_toolkit("slack").is_empty());-}--#[test]-fn every_essential_name_exists_in_the_real_toolkit_fixture() {- // A stale table entry would silently spend no slot and hide the bug it- // was added for, so pin the names against the real Composio dump.- for (toolkit, essentials) in TOOLKIT_ESSENTIAL_ACTIONS {- let path = format!(- "{}/tests/fixtures/composio_{}.json",- env!("OPENHUMAN_REPOSITORY_ROOT"),- toolkit- );- let raw = std::fs::read_to_string(&path)- .unwrap_or_else(|e| panic!("failed to read fixture {path}: {e}"));- let parsed: serde_json::Value =- serde_json::from_str(&raw).unwrap_or_else(|e| panic!("failed to parse {path}: {e}"));- let names: Vec<String> = parsed- .pointer("/result/result/tools")- .and_then(|t| t.as_array())- .unwrap_or_else(|| panic!("missing /result/result/tools in {path}"))- .iter()- .filter_map(|t| {- t.pointer("/function/name")- .and_then(|n| n.as_str())- .map(str::to_string)- })- .collect();- for essential in *essentials {- assert!(- names.iter().any(|n| n == essential),- "{toolkit} essential {essential} is not a real action in {path}"- );- }- }-}--#[test]-fn gmail_read_prompt_keeps_a_content_returning_action() {- // The two prompts from #6033: the ranker returns twelve LIST_* actions- // and nothing that returns a message body. After reservation the- // sub-agent can actually read an email.- let path = format!(- "{}/tests/fixtures/composio_gmail.json",- env!("OPENHUMAN_REPOSITORY_ROOT")- );- let raw = std::fs::read_to_string(&path).expect("gmail fixture");- let parsed: serde_json::Value = serde_json::from_str(&raw).expect("gmail fixture parses");- let actions: Vec<ConnectedIntegrationTool> = parsed- .pointer("/result/result/tools")- .and_then(|t| t.as_array())- .expect("fixture tools")- .iter()- .map(|t| ConnectedIntegrationTool {- name: t- .pointer("/function/name")- .and_then(|n| n.as_str())- .unwrap_or_default()- .to_string(),- description: t- .pointer("/function/description")- .and_then(|d| d.as_str())- .unwrap_or_default()- .to_string(),- parameters: t.pointer("/function/parameters").cloned(),- })- .collect();-- for prompt in [- "find job opportunities from the last 5 days",- "Search the user's Gmail inbox for job opportunity emails from the last 5 days and summarize sender, subject and date",- ] {- let candidates: Vec<_> = actions- .iter()- .map(|tool| SelectableTool::new(&tool.name, &tool.description))- .collect();- let hits = rank_tools_by_prompt(prompt, &candidates, 12);- let selected = select_actions_with_essentials("gmail", &actions, &hits, 12);- let names: Vec<&str> = selected.iter().map(|&i| actions[i].name.as_str()).collect();-- assert!(- names.contains(&"GMAIL_FETCH_EMAILS"),- "prompt {prompt:?} must keep a content-returning action; got {names:?}"- );- assert!(- selected.len() <= 12,- "prompt {prompt:?} exceeded the budget"- );- assert_eq!(- selected.len(),- selected- .iter()- .collect::<std::collections::HashSet<_>>()- .len(),- "prompt {prompt:?} produced a duplicate index"- );- }-}--#[test]-fn every_essential_action_is_read_only() {- // Essentials are forced onto a delegation whatever it asked for, so a- // write action here would hand a read task an unrequested- // side-effecting capability that the approval middleware does not gate- // (a ComposioActionTool does not override `external_effect`).- const WRITE_VERBS: &[&str] = &[- "SEND", "CREATE", "DELETE", "UPDATE", "PATCH", "MOVE", "MODIFY", "ADD", "REMOVE", "TRASH",- "REPLY", "FORWARD", "DRAFT",- ];- for (toolkit, essentials) in TOOLKIT_ESSENTIAL_ACTIONS {- for essential in *essentials {- let verb = essential- .split('_')- .nth(1)- .unwrap_or_default()- .to_ascii_uppercase();- assert!(- !WRITE_VERBS.contains(&verb.as_str()),- "{toolkit} essential {essential} is a write action; essentials must be read-only"- );- }- }-}--// ── Dynamic-tool spawn strip (#6157) ────────────────────────────────────--use async_trait::async_trait;-use tinytools::Tool;--/// A tool that is nothing but its name — the strip reads no other field.-struct NamedTool(&'static str);--#[async_trait]-impl Tool for NamedTool {- /// The caller-chosen name.- fn name(&self) -> &str {- self.0- }-- /// Unused by the strip.- fn description(&self) -> &str {- "stub"- }-- /// Unused by the strip.- fn parameters_schema(&self) -> serde_json::Value {- serde_json::json!({})- }-- /// Never called: the strip only inspects names.- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {- Ok(tinytools::ToolResult::success(String::new()))- }-}--/// A dynamic-tool list carrying exactly these names, in this order.-fn dynamic(names: &[&'static str]) -> Vec<Box<dyn Tool>> {- names- .iter()- .map(|name| Box::new(NamedTool(name)) as Box<dyn Tool>)- .collect()-}--/// The surviving names, so a test can assert on content *and* order.-fn names_of(tools: &[Box<dyn Tool>]) -> Vec<&str> {- tools.iter().map(|t| t.name()).collect()-}--/// The shape the runner actually builds: Composio actions plus the-/// progressive-disclosure handoff tool, with spawn tools interleaved.-#[test]-fn dynamic_tools_keep_ordinary_actions_and_lose_spawn_tools() {- let mut tools = dynamic(&[- "GMAIL_FETCH_EMAILS",- "spawn_subagent",- "extract_from_result",- "delegate_graph",- "spawn_worker_thread",- "GMAIL_SEND_EMAIL",- ]);- strip_spawn_tools_from_dynamic(&mut tools, "researcher");-- assert_eq!(- names_of(&tools),- vec![- "GMAIL_FETCH_EMAILS",- "extract_from_result",- "GMAIL_SEND_EMAIL"- ],- "only spawn/delegate tools are dropped, and surviving order is preserved"- );-}--/// The whole reason the strip lives here rather than relying on the-/// registration-time backstop: that backstop matches `delegate_*` by prefix and-/// would keep `plan`, which is `planner`'s `delegate_name`.-#[test]-fn dynamic_tools_lose_unprefixed_delegate_name_overrides() {- let tmp = tempfile::TempDir::new().unwrap();- crate::agent::harness::definition::AgentDefinitionRegistry::init_global(tmp.path()).unwrap();-- let mut tools = dynamic(&["plan", "run_code", "shell", "web_fetch"]);- strip_spawn_tools_from_dynamic(&mut tools, "researcher");-- assert_eq!(- names_of(&tools),- vec!["shell", "web_fetch"],- "`delegate_name` overrides are spawn tools even without the prefix"- );-}--/// The live case today: no dynamic tool is named after a spawn tool, so the-/// strip must be a no-op rather than a silent narrowing of the surface.-#[test]-fn a_dynamic_tool_list_without_spawn_tools_is_untouched() {- let mut tools = dynamic(&["GMAIL_FETCH_EMAILS", "extract_from_result"]);- strip_spawn_tools_from_dynamic(&mut tools, "researcher");-- assert_eq!(- names_of(&tools),- vec!["GMAIL_FETCH_EMAILS", "extract_from_result"]- );-}--/// Render the `## Tools` section the way a sub-agent prompt does, at `format`.-fn render_tools_at(format: crate::agent::prompts::ToolCallFormat, instructions: &str) -> String {- use crate::agent::prompts::{LearnedContextData, PromptTool};- let tools = [PromptTool::with_schema(- "composio_execute",- "Run one Composio action.",- r#"{"type":"object","properties":{"action":{"type":"string"}}}"#.into(),- )];- let visible = std::collections::HashSet::new();- let ctx = PromptContext {- workspace_dir: std::path::Path::new("/tmp"),- model_name: "test-model",- agent_id: "integrations_agent",- tools: &tools,- workflows: &[],- dispatcher_instructions: instructions,- learned: LearnedContextData::default(),- visible_tool_names: &visible,- tool_call_format: format,- connected_integrations: &[],- connected_identities_md: String::new(),- include_profile: false,- include_memory_md: false,- curated_snapshot: None,- user_identity: None,- personality_roster: vec![],- agents_md_global: None,- agents_md_local: None,- };- crate::agent::prompts::render_tools(&ctx).unwrap()-}--/// A text-mode child of a native-tool parent is sent no native `tools`, so its-/// prompt must list them. Rendering at the parent's format is what used to-/// happen: no catalogue at all, plus the native JSON protocol.-#[test]-fn text_mode_child_of_a_native_parent_renders_its_tool_catalogue() {- use crate::agent::prompts::ToolCallFormat;-- let specs = [tinytools::ToolSpec {- name: "composio_execute".into(),- description: "Run one Composio action.".into(),- parameters: serde_json::json!({- "type": "object",- "properties": {"action": {"type": "string"}}- }),- }];- let (format, instructions) = subagent_prompt_protocol(ToolCallFormat::Native, true, &specs);- assert_eq!(format, ToolCallFormat::Json);- assert!(- !instructions.is_empty(),- "TinyTools must supply the text-mode protocol: {instructions}"- );- let rendered = render_tools_at(format, &instructions);- assert!(- rendered.contains("**composio_execute**:"),- "text-mode child has no tool catalogue: {rendered:?}"- );-- let parents = render_tools_at(ToolCallFormat::Native, "");- assert!(- !parents.contains("- **composio_execute**:"),- "a native-format render is expected to omit the catalogue: {parents:?}"- );-}-#[test]-fn native_child_keeps_the_parents_protocol() {+fn child_keeps_the_parents_protocol() {use crate::agent::prompts::ToolCallFormat;for parent in [@@ -484,7 +58,7 @@ fn native_child_keeps_the_parents_protocol() {ToolCallFormat::PFormat,ToolCallFormat::Json,] {- let (format, _) = subagent_prompt_protocol(parent, false, &[]);+ let (format, _) = subagent_prompt_protocol(parent, &[]);assert_eq!(format, parent);}}