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
merge main into prompt-budget
Steven Enamakel01d1e79dcea3
diff --cc src/openhuman/agent/harness/session/builder/builder_tests.rsindex 6b0e0c55aa,801ef5aaae..770d9bf690--- a/src/openhuman/agent/harness/session/builder/builder_tests.rs+++ b/src/openhuman/agent/harness/session/builder/builder_tests.rs@@@ -749,142 -269,46 +269,157 @@@ fn a_realistic_withheld_session_keeps_i);}- #[tokio::test]- async fn from_config_for_agent_still_errors_for_a_genuinely_unknown_id() {- // Building a session agent constructs a memory store, which reaches- // the embedding seam; before the extraction this needed no setup.- crate::openhuman::memory::host_impls::install_for_tests();- use crate::openhuman::agent::harness::session::types::Agent;-- let tmp = tempfile::TempDir::new().unwrap();- let config = test_config(&tmp);-- // No harness definition AND no config.agent_registry entry for this id —- // the factory must still hard-error rather than silently building an- // unfiltered/legacy agent.- //- // Note: `Agent` intentionally has no `Debug` impl (it holds `Box<dyn- // Tool>` / provider trait objects), so this must use `match` +- // `.is_err()` rather than `.expect_err()`, which requires `T: Debug`.- let result = Agent::from_config_for_agent(&config, "totally_unknown_agent_id_b38");+ /// **Listing visibility must not ride on the named-call permission ceiling.**+ ///+ /// `UseSkillTool::permission_level()` reports the MAX over every packed+ /// tool — correct for a *named* call, where the worst case genuinely is the+ /// most dangerous packed tool. But `tool_policy.is_allowed(&spec.name)` is+ /// built from that same argument-less ceiling, so a session excluding+ /// `use_skill` from `allowed_tool_names` (exactly what the real engine does+ /// when one packed tool exceeds the channel's permission ceiling) must not+ /// erase the whole proxy — `use_skill`'s own listing action+ /// (`skill` alone, no `tool`) is always `ReadOnly` per+ /// `permission_level_with_args`, and every OTHER pack's tools stay reachable+ /// through it regardless of what one dangerous tool in some other pack needs.+ #[test]+ fn use_skill_survives_a_ceiling_that_excludes_it_when_a_pack_is_still_reachable() {+ // `allowed_tool_names` deliberately omits `USE_SKILL` itself — simulating+ // the real engine having excluded it because *some* packed tool (not+ // `run_workflow`) exceeded the channel's permission ceiling.+ let session = session_allowing(&["run_workflow"]);assert!(- result.is_err(),- "an id with no harness definition and no custom entry must error"+ !session+ .allowed_tool_names+ .contains(crate::openhuman::tools::toolpacks::USE_SKILL),+ "precondition: use_skill itself is not in the allowlist");- let err = result.err().unwrap();++ let specs: Vec<std::sync::Arc<ToolSpec>> =+ vec![std::sync::Arc::new(use_skill_spec_from_registry())];+ let visible: std::collections::HashSet<String> = specs.iter().map(|s| s.name.clone()).collect();++ let out = visible_tool_specs_for_policy(&specs, &visible, &session);+ let load = out+ .iter()+ .find(|s| s.name == crate::openhuman::tools::toolpacks::USE_SKILL)+ .expect(+ "use_skill must survive even though it is not itself in allowed_tool_names — \+ its listing action is always ReadOnly and the workflows pack is reachable",+ );assert!(- err.to_string().contains("totally_unknown_agent_id_b38"),- "error should name the unresolved agent id: {err}"+ load.description.contains("`workflows`"),+ "the reachable pack must still be advertised: {}",+ load.description);}++// ─────────────────────────────────────────────────────────────────────────────+// `named = []` means zero tools, not every tool.+//+// The harness's visible-tool set uses empty as its "no filter" sentinel, so an+// agent declaring an empty named scope was handed the entire registry — the+// exact opposite of what it asked for. `summarizer` and `trigger_triage` both+// declare `named = []` in their shipped `agent.toml`, and both were carrying+// 109 tools / 82,986 B of schema apiece: 18% of the fleet's whole fixed prefix,+// on the two agents that had asked for none. `trigger_triage`'s own comment+// says local 1B-class models are unreliable at nested tool calls, "so we keep+// the turn flat" — so this was not only waste, it was actively working against+// the thing the author documented.+//+// `NO_TOOLS_SENTINEL` is how an empty belt survives a set whose empty state is+// already spoken for.+// ─────────────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn an_empty_named_scope_advertises_no_tools_at_all() {+ crate::openhuman::memory::host_impls::install_for_tests();+ use crate::openhuman::agent::harness::session::types::Agent;++ // `summarizer` is a shipped definition with `named = []`. Using the real+ // one rather than a fixture is deliberate: the bug was in how a real+ // declaration was read, and a fixture could drift away from it.+ // Tolerant of an already-initialised singleton: this binary shares one+ // `OnceLock` across every test, so whether we are first is a property of+ // test ordering, not of this test.+ let _ =+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins(+ );++ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let agent = Agent::from_config_for_agent(&config, "summarizer")+ .expect("summarizer is a shipped agent definition");++ let visible = agent.visible_tool_names_for_test();+ let real: Vec<&String> = visible+ .iter()+ .filter(|n| n.as_str() != crate::openhuman::agent::harness::definition::NO_TOOLS_SENTINEL)+ .collect();+ assert!(+ real.is_empty(),+ "an agent declaring `named = []` must advertise nothing, got: {real:?}"+ );+}++#[tokio::test]+async fn a_zero_tool_agent_does_not_gain_the_compaction_recovery_tool() {+ // `ensure_recovery_tool_visible` joins the recovery tool to any non-empty+ // named belt, and the sentinel makes a zero-tool belt non-empty for the+ // first time. Without `is_empty_tool_scope` there, "no tools" would have+ // quietly become "one tool" — and there is nothing for it to recover,+ // because an agent with no tools produces no tool output to truncate.+ crate::openhuman::memory::host_impls::install_for_tests();+ use crate::openhuman::agent::harness::session::types::Agent;+ use crate::openhuman::inference::tokenjuice::RETRIEVE_TOOL_NAME;++ // Tolerant of an already-initialised singleton: this binary shares one+ // `OnceLock` across every test, so whether we are first is a property of+ // test ordering, not of this test.+ let _ =+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins(+ );++ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let agent = Agent::from_config_for_agent(&config, "trigger_triage")+ .expect("trigger_triage is a shipped agent definition");++ assert!(+ !agent+ .visible_tool_names_for_test()+ .contains(RETRIEVE_TOOL_NAME),+ "a deliberately tool-less agent must not be handed the recovery tool"+ );+}++#[test]+fn the_no_tools_sentinel_can_never_name_a_real_tool() {+ // The value is load-bearing: it works only because no registry can contain+ // it. Leading underscores are not a legal tool name for any provider's+ // function-calling schema, which is why this shape was chosen.+ use crate::openhuman::agent::harness::definition::NO_TOOLS_SENTINEL;+ assert!(NO_TOOLS_SENTINEL.starts_with("__"));+ assert!(!NO_TOOLS_SENTINEL.chars().next().unwrap().is_alphanumeric());+}++#[test]+fn is_empty_tool_scope_distinguishes_the_three_states() {+ use crate::openhuman::agent::harness::definition::{is_empty_tool_scope, NO_TOOLS_SENTINEL};+ use std::collections::HashSet;++ // Unset — the historical "everything" sentinel.+ assert!(is_empty_tool_scope(&HashSet::new()));+ // Deliberately empty.+ let sentinel: HashSet<String> = [NO_TOOLS_SENTINEL.to_string()].into_iter().collect();+ assert!(is_empty_tool_scope(&sentinel));+ // A real belt is neither.+ let real: HashSet<String> = ["shell".to_string()].into_iter().collect();+ assert!(!is_empty_tool_scope(&real));+ // The sentinel alongside a real tool is not an empty scope — that+ // combination should never be built, but reading it as "empty" would hide+ // a real tool from the belt rather than surface the mistake.+ let mixed: HashSet<String> = [NO_TOOLS_SENTINEL.to_string(), "shell".to_string()]+ .into_iter()+ .collect();+ assert!(!is_empty_tool_scope(&mixed));+}diff --cc src/openhuman/agent/orchestration/tools.rsindex 58a3589e60,bd0986b426..f7786c33f1--- a/src/openhuman/agent/orchestration/tools.rs+++ b/src/openhuman/agent/orchestration/tools.rs@@@ -43,9 -41,8 +43,9 @@@ pub(crate) use dispatch::dispatch_subagpub use agent_prepare_context::{run_context_scout, run_context_scout_with_catalog, AgentPrepareContextTool,};- pub use archetype_delegation::ArchetypeDelegationTool;+ pub use archetype_delegation::{ArchetypeDelegationTool, DelegationTarget};pub use close_subagent::CloseSubagentTool;+pub use collapsed_delegation::{CollapsedDelegationTool, DelegateTarget, DELEGATE_TO_TOOL_NAME};pub use continue_subagent::ContinueSubagentTool;pub use delegate_graph::DelegateGraphTool;pub use list_subagents::ListSubagentsTool;diff --cc src/openhuman/flows/mod.rsindex 3fd7f07366,4a9cc9f41e..a937282535--- a/src/openhuman/flows/mod.rs+++ b/src/openhuman/flows/mod.rs@@@ -29,23 -29,18 +29,23 @@@//! `use`, this family must convert to the facade+stub shape (see `voice/`).pub mod agents;- mod build_registry;pub mod builder_tools;pub mod bus;+pub mod catalogue;pub mod discovery_tools;mod draft_store;+ #[cfg(test)]+ #[path = "import_tests.rs"]+ mod import_tests;pub mod medulla_bridge;pub mod memory_tools;- mod n8n_import;pub mod node_contracts;pub mod ops;- mod run_registry;mod schemas;+/// Skills this domain ships inside the binary. Needs BOTH gates: the pages+/// teach flows authoring, and `BundledSkill` is part of the skills subsystem.+#[cfg(feature = "skills")]+pub mod skills;mod store;/// The tinyflows engine seam (formerly `openhuman::tinyflows`).pub mod tinyflows;@@@ -66,11 -69,11 +74,11 @@@ pub use schemas::// lives in the sibling `tinyflows` domain and persists each finished step onto// the `flow_runs` row through this function as the run executes.pub use node_contracts::{- all_node_kind_contracts, node_kind_contract, render_node_kinds_line, ConfigField,- NodeKindContract, PortSpec, NODE_KINDS,+ all_node_kind_contracts, node_kind_contract, render_node_kinds_line,+ render_node_kinds_required, ConfigField, NodeKindContract, PortSpec, NODE_KINDS,};pub use store::{kv_get, kv_set, upsert_flow_run_step};- pub use types::{+ pub use tinyflows_catalog::{DraftOrigin, Flow, FlowConnection, FlowDraft, FlowImport, FlowRevision, FlowRun, FlowRunStep,FlowRunTrigger, FlowSuggestion, FlowValidation, FlowValidationError, SuggestionStatus,};diff --cc src/openhuman/memory/tools/recall.rsindex cf533b33a0,9f3174bad8..1f54e20be6--- a/src/openhuman/memory/tools/recall.rs+++ b/src/openhuman/memory/tools/recall.rs@@@ -1,6 -1,7 +1,7 @@@+ use crate::openhuman::agent::tinyagents::host::agent_memory::DEFAULT_AGENT_MEMORY_NAMESPACE;use crate::openhuman::memory::api::provider::MemoryRecall;use crate::openhuman::memory::ops::guard::active_memory_guard;-use crate::openhuman::tools::traits::{Tool, ToolResult};+use crate::openhuman::tools::traits::{Tool, ToolExposure, ToolResult};use async_trait::async_trait;use serde_json::json;use std::fmt::Write;diff --cc src/openhuman/memory/tools/store.rsindex 6c55c2d692,85e6ca150b..3d2970fd08--- a/src/openhuman/memory/tools/store.rs+++ b/src/openhuman/memory/tools/store.rs@@@ -4,9 -5,10 +5,10 @@@ use crate::openhuman::memory::ops::guaruse crate::openhuman::memory::safety;use crate::openhuman::security::policy::ToolOperation;use crate::openhuman::security::SecurityPolicy;-use crate::openhuman::tools::traits::{Tool, ToolResult};+use crate::openhuman::tools::traits::{Tool, ToolExposure, ToolResult};use async_trait::async_trait;use serde_json::json;+ use sha2::{Digest, Sha256};use std::sync::Arc;/// Let the agent store memories — its own brain writes@@@ -22,16 -24,76 +24,84 @@@ impl MemoryStoreTool}}+ /// Words of the content a derived key is built from.+ const DERIVED_KEY_WORDS: usize = 6;++ /// Longest stem a derived key carries before its hash suffix.+ const DERIVED_KEY_STEM_CHARS: usize = 48;++ /// Hex characters of digest a derived key carries — 16 hex, so 64 bits.+ ///+ /// The stem collides constantly by design (a mailbox of "meeting with …"+ /// notes opens the same way), so the suffix is the whole of what keeps two+ /// facts apart, and a collision does not merely duplicate — it overwrites an+ /// unrelated memory under the same key. 24 bits made that likely within a few+ /// thousand notes (review finding); 64 keeps it out of reach.+ const DERIVED_KEY_HASH_CHARS: usize = 16;++ /// The namespace to write to: the caller's, or the assistant's own scope.+ ///+ /// Absent means the default scope — the one `memory_recall` reads back from —+ /// so a one-line "remember X" needs no namespace at all (#6048). A value that+ /// is present but not a string is a caller mistake, not a request for the+ /// default: a `null` or a number must not silently widen the write. An explicit+ /// empty string is left for the caller to report, never defaulted.+ fn resolve_namespace(args: &serde_json::Value) -> anyhow::Result<String> {+ match args.get("namespace") {+ None => Ok(DEFAULT_AGENT_MEMORY_NAMESPACE.to_string()),+ Some(serde_json::Value::String(namespace)) => Ok(namespace.trim().to_string()),+ Some(other) => anyhow::bail!("'namespace' must be a string, got {other}"),+ }+ }++ /// The key to file under: the caller's, or one derived from the content.+ ///+ /// The model should not have to invent a key to honour "remember X". A derived+ /// key is deterministic for the same content, so re-saving the same sentence+ /// overwrites rather than duplicating, while different content lands under a+ /// different key. A present-but-non-string key is a caller mistake.+ fn resolve_key(args: &serde_json::Value, content: &str) -> anyhow::Result<String> {+ match args.get("key") {+ None => Ok(derive_key(content)),+ Some(serde_json::Value::String(key)) => Ok(key.trim().to_string()),+ Some(other) => anyhow::bail!("'key' must be a string, got {other}"),+ }+ }++ /// A stable, readable key for `content`: its first few words as a snake_case+ /// stem, plus a digest of the whole text so two notes that open the same way+ /// do not overwrite each other.+ ///+ /// SHA-256 rather than a cheap non-cryptographic hash: the input is user text,+ /// the cost is irrelevant beside the write it precedes, and the same digest ->+ /// same key property is what makes re-saving a sentence idempotent.+ fn derive_key(content: &str) -> String {+ let stem = content+ .split(|c: char| !c.is_alphanumeric())+ .filter(|word| !word.is_empty())+ .take(DERIVED_KEY_WORDS)+ .map(str::to_lowercase)+ .collect::<Vec<_>>()+ .join("_");+ let stem: String = if stem.is_empty() {+ "note".to_string()+ } else {+ stem.chars().take(DERIVED_KEY_STEM_CHARS).collect()+ };+ let digest = hex::encode(Sha256::digest(content.trim().as_bytes()));+ format!("{stem}_{}", &digest[..DERIVED_KEY_HASH_CHARS])+ }+#[async_trait]impl Tool for MemoryStoreTool {+ /// Superseded by the `memory` tool, which dispatches every memory+ /// operation on one `action` field. Kept registered and dispatchable so a+ /// replayed transcript or a saved skill naming `memory_*` keeps working;+ /// hidden from the wire so eleven schemas do not ship where one does.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Hidden+ }+fn name(&self) -> &str {"memory_store"}diff --cc src/openhuman/tools/toolpacks/ops.rsindex 3cdfaca6ab,6fa82c7243..7c54fd5d07--- a/src/openhuman/tools/toolpacks/ops.rs+++ b/src/openhuman/tools/toolpacks/ops.rs@@@ -81,28 -113,6 +113,28 @@@ pub fn strip_packed_from_visible(visibltracing::info!(agent = %agent_id,hidden = packed.len(),- "[toolpacks] withheld packed tool schemas; load_skill/use_skill advertised instead"+ "[toolpacks] withheld packed tool schemas; use_skill advertised instead");}++/// Is `tool` withheld from `agent_id` by the pack table right now?+///+/// The predicate behind [`strip_packed_from_visible`], exposed for callers that+/// build a *listing* of tools rather than a visible set — today the collapsed+/// `delegate_to` tool, whose `agent` enum is an advertised surface that no+/// `visible` subtraction can reach.+///+/// That distinction is load-bearing. Collapsing the archetype delegates without+/// it silently re-advertised seven routes the pack table deliberately withholds+/// (`do_crypto`, `setup_mcp_server`, `use_mcp_server`, `setup_skills`,+/// `run_skill`, `build_workflow`, `discover_workflows`): each one stopped being+/// a tool — so `strip_packed_from_visible` had nothing to remove — and became a+/// string inside another tool's schema instead. A collapse must never widen+/// what the pack posture narrowed.+pub fn is_withheld_from(agent_id: &str, tool: &str) -> bool {+ let groups = super::groups::current();+ groups.mode_for_tool(tool) == super::groups::GroupMode::Withheld+ && registry::packed_tool_names_for_agent(agent_id)+ .into_iter()+ .any(|name| name == tool)+}diff --cc src/openhuman/tools/traits.rsindex d1dce535f1,92e4bb9379..a0dfc8f666--- a/src/openhuman/tools/traits.rs+++ b/src/openhuman/tools/traits.rs@@@ -21,10 -21,10 +21,11 @@@pub use tinytools::{context_detail_from_args, humanize_tool_name, PermissionLevel, Tool, ToolCallOptions,- ToolCategory, ToolContent, ToolResult, ToolRunContext, ToolScope, ToolSpec, ToolTimeout,+ ToolCategory, ToolContent, ToolExposure, ToolResult, ToolRunContext, ToolScope, ToolSpec,+ ToolTimeout,};+ use crate::openhuman::agent::orchestration::tools::DelegationTarget;use crate::openhuman::agent::tool_policy::GeneratedToolRuntimeContext;use crate::openhuman::tools::toolpacks::PackRegistryHandle;