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
refactor(harness): split agent definition into focused modules
Steven Enamakel6216f064741d
diff --git a/crates/openhuman-core/src/agent/harness/definition.rs b/crates/openhuman-core/src/agent/harness/definition.rsdeleted file mode 100644index aa2c7549e6..0000000000--- a/crates/openhuman-core/src/agent/harness/definition.rs+++ /dev/null@@ -1,50 +0,0 @@-//! Data-driven agent definitions.-//!-//! An [`AgentDefinition`] fully specifies a sub-agent: its core prompt, model,-//! allowed tool set, runtime limits, and which sections of the parent system-//! prompt to omit. Built-in definitions live in-//! [`crate::agent::registry::agents`] — one subfolder per agent, each-//! holding an `agent.toml` (metadata) and `prompt.md` (system prompt). A-//! thin wrapper in [`super::builtin_definitions`] loads them and appends-//! the synthetic `fork` definition. Users can ship custom definitions as-//! TOML files under `$OPENHUMAN_WORKSPACE/agents/*.toml` (with a fallback-//! to `~/.openhuman/agents/*.toml` for user-global specialists) which-//! override built-ins on id collision. See [`super::definition_loader`]-//! for the directory scan + TOML parsing contract.-//!-//! Sub-agents are dispatched at runtime by the `spawn_subagent` tool, which-//! looks up an [`AgentDefinition`] by id in the global-//! [`AgentDefinitionRegistry`] and hands it to-//! [`crate::agent::subagent_host::run_subagent`].-//!-//! This file intentionally has zero references to the rest of the agent-//! runtime — it is pure data so the model can be unit-tested in isolation-//! and serialised straight from disk.--#[cfg(test)]-#[path = "definition_tests.rs"]-mod tests;--mod agent_definition;-mod execution_spec;-mod prompt_source;-mod registry;-mod source;-mod subagents;-mod tier;--pub use agent_definition::{AgentDefinition, IterationPolicy, EXTENDED_MAX_TOOL_ITERATIONS};-pub use execution_spec::{ModelSpec, SandboxMode, ToolScope, SPAWN_TOOL_NAMES};-pub use prompt_source::{PromptBuilder, PromptSource};-pub use registry::AgentDefinitionRegistry;-pub use source::DefinitionSource;-pub use subagents::{SkillsWildcard, SubagentEntry};-pub use tier::{validate_tier_transition, AgentTier};--/// Sentinel used to represent an explicit zero-tool scope.-pub const NO_TOOLS_SENTINEL: &str = "__no_tools__";--/// Returns whether a visible-tool set represents an explicit zero-tool scope.-pub fn is_empty_tool_scope(visible: &std::collections::HashSet<String>) -> bool {- visible.is_empty() || (visible.len() == 1 && visible.contains(NO_TOOLS_SENTINEL))-}diff --git a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rsdeleted file mode 100644index 9724a86948..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs+++ /dev/null@@ -1,322 +0,0 @@-//! The [`AgentDefinition`] record itself plus the small policy enums it-//! embeds directly ([`IterationPolicy`]) and the-//! serde default helpers its `#[serde(default = ...)]` attributes name.--use serde::{Deserialize, Serialize};--use super::execution_spec::{ModelSpec, SandboxMode, ToolScope};-use super::prompt_source::PromptSource;-use super::source::DefinitionSource;-use super::subagents::{deserialize_subagent_entries, SubagentEntry};-use super::tier::AgentTier;-use tinyjuice_bus::types::AgentTokenjuiceCompression;--/// Iteration ceiling for an [`IterationPolicy::Extended`] agent — the higher-/// bound a long-running agent (orchestrator, deep research) is allowed to reach-/// before the harness stops it. Lives here, the sole consumer, since the legacy-/// `tool_loop` that originally defined it was removed in the tinyagents-/// migration (issue #4249).-pub const EXTENDED_MAX_TOOL_ITERATIONS: usize = 50;--/// Iteration-cap policy for a sub-agent.-///-/// Controls how the harness enforces [`AgentDefinition::max_iterations`]:-///-/// * **Strict** — hard-fail at `max_iterations` (the current default).-/// Right for short-running agents (summarizer, triage) where hitting-/// the cap signals a likely loop.-/// * **Extended** — the per-agent `max_iterations` is replaced at runtime-/// by a higher harness-wide constant-/// ([`EXTENDED_MAX_TOOL_ITERATIONS`])-/// so the agent can complete realistic multi-tool workflows. The-/// repeated-failure circuit breaker and cost budget still apply. The-/// UI omits the denominator ("step N" instead of "turn N/M") to avoid-/// a misleading terminal countdown.-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum IterationPolicy {- /// Hard cap at `max_iterations`. Default for most agents.- #[default]- Strict,- /// Raised cap for multi-step specialists. Guards still apply.- Extended,-}--// ─────────────────────────────────────────────────────────────────────────────-// Agent definition-// ─────────────────────────────────────────────────────────────────────────────--/// A fully specified sub-agent archetype: what it knows, what it can do, and how to prompt it.-///-/// Definitions are used by the `spawn_subagent` tool to initialize a new-/// specialized agent. They can be built-in or loaded from custom TOML files.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AgentDefinition {- // ── identity ────────────────────────────────────────────────────────- /// Unique identifier for this archetype (e.g., `planner`, `code_executor`).- pub id: String,-- /// Human-readable description explaining when this agent should be used.- /// Shown to the parent model to help it decide whether to delegate.- pub when_to_use: String,-- /// Optional display name for UI and log output.- #[serde(default)]- pub display_name: Option<String>,-- // ── prompt ──────────────────────────────────────────────────────────- /// The core system prompt body for this specialized agent.- #[serde(default = "defaults::empty_inline_prompt")]- pub system_prompt: PromptSource,-- /// If `true`, the parent's identity section is stripped from the prompt.- #[serde(default = "defaults::true_")]- pub omit_identity: bool,-- /// If `true`, the compiled memory context (`context.md`) is not injected- /// as the first user message of a new session for this agent.- #[serde(default = "defaults::true_")]- pub omit_memory_context: bool,-- /// If `true`, the standard safety preamble is stripped.- #[serde(default = "defaults::true_")]- pub omit_safety_preamble: bool,-- // ── model ───────────────────────────────────────────────────────────- /// Strategy for picking which model to use for this sub-agent.- #[serde(default)]- pub model: ModelSpec,-- /// Sampling temperature for the model.- #[serde(default = "defaults::subagent_temperature")]- pub temperature: f64,-- // ── tools ───────────────────────────────────────────────────────────- /// Which tools from the parent's registry should be available to the sub-agent.- #[serde(default)]- pub tools: ToolScope,-- /// Explicit list of tool names to block, even if they match the scope.- #[serde(default)]- pub disallowed_tools: Vec<String>,-- /// Filter to only tools belonging to a specific skill (e.g., `notion`).- #[serde(default)]- pub skill_filter: Option<String>,-- /// Named tools that should always be visible to this agent in- /// addition to its [`ToolScope`]. Historically this was a bypass- /// list for the now-removed `category_filter`; kept as a generic- /// "also include these" hook for custom definitions.- ///- /// Entries are still subject to [`AgentDefinition::disallowed_tools`].- #[serde(default)]- pub extra_tools: Vec<String>,-- /// Tools in this agent's scope that should leave its wire and be served- /// through `tool_search` instead: still registered, found by a search,- /// and callable by their own name. Unlike `ToolExposure::Deferred`, which- /// defers a tool for every agent, this defers it for this agent only.- /// Takes effect only on a belt that opted into discovery (a wildcard- /// belt, or `named` listing `tool_search`).- #[serde(default)]- pub deferred_tools: Vec<String>,-- /// Pattern rules narrowing this agent's tools on every surface — the- /// catalogue, `tool_search` and each call — on top of [`ToolScope`] and- /// [`AgentDefinition::disallowed_tools`]. A `[tool_rules]` table in the- /// agent's TOML; see `tinytools::ToolRules` and `crate::tools::rules`.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub tool_rules: Option<tinytools::ToolRules>,-- // ── runtime limits ──────────────────────────────────────────────────- /// Maximum number of tool iterations for this sub-agent's task.- #[serde(default = "defaults::max_iterations")]- pub max_iterations: usize,-- /// Iteration-cap policy. See [`IterationPolicy`] for semantics.- /// Defaults to [`IterationPolicy::Strict`]; long-running specialists- /// set `iteration_policy = "extended"` in their `agent.toml`.- #[serde(default)]- pub iteration_policy: IterationPolicy,-- /// Maximum character length for this sub-agent's output before the- /// harness truncates it before feeding it back as a tool result to the- /// parent. `None` means no cap (the default for most agents). Set to- /// a value for research/planner/code agents to prevent context flooding- /// from large outputs.- #[serde(default)]- pub max_result_chars: Option<usize>,-- /// Optional per-LLM-call output token cap for this agent. When unset, the- /// shared agent-turn cap is used. Narrow agents can set a smaller cap so- /// a single verbose turn cannot flood the sub-agent loop before the final- /// result is truncated.- #[serde(default)]- pub max_turn_output_tokens: Option<u32>,-- /// Wall-clock timeout for the sub-agent's execution (seconds).- #[serde(default)]- pub timeout_secs: Option<u64>,-- /// Sandbox level for tool execution.- #[serde(default)]- pub sandbox_mode: SandboxMode,-- /// Reserved for background (asynchronous) execution support.- #[serde(default)]- pub background: bool,-- /// Per-agent TokenJuice tool-result compression profile.- ///- /// `auto` keeps compression on for normal agents, but resolves coding-model- /// agents to `light` so CCR-backed lossy compression does not replace raw- /// build/test/diff/search text that coding agents often need exactly.- #[serde(default)]- pub tokenjuice_compression: AgentTokenjuiceCompression,-- // ── delegation surface ─────────────────────────────────────────────- /// Subagents this agent is allowed to spawn via synthesised- /// `delegate_*` tools. Each entry expands at agent-build time into- /// one tool the LLM can call in its function-calling schema:- ///- /// * [`SubagentEntry::AgentId`] — one [`ArchetypeDelegationTool`]- /// whose name defaults to `delegate_{agent_id}` (or the target- /// agent's `delegate_name` override) and whose description is the- /// target agent's [`AgentDefinition::when_to_use`].- ///- /// * [`SubagentEntry::Skills`] — no delegation tool. The connected- /// Composio toolkits' actions join this agent's `Deferred` catalogue- /// (reached through `tool_search`, called directly), and the entry- /// admits no sub-agent id: see [`AgentDefinition::allowed_subagent_ids`].- ///- /// `subagents` is intentionally separate from [`AgentDefinition::tools`]- /// so that reading a TOML makes the distinction obvious: `tools` is- /// "what I execute directly", `subagents` is "what I can delegate to".- ///- /// [`ArchetypeDelegationTool`]: crate::agent::orchestration::tools::ArchetypeDelegationTool- #[serde(default, deserialize_with = "deserialize_subagent_entries")]- pub subagents: Vec<SubagentEntry>,-- /// Optional override for the tool name this agent is exposed as when- /// another agent lists it in its [`subagents`]. Defaults to- /// `delegate_{id}` when absent. Kept separate from `display_name` so- /// the UI display and the LLM tool name can diverge (e.g.- /// `display_name = "Researcher"`, `delegate_name = "research"`).- #[serde(default)]- pub delegate_name: Option<String>,-- // ── spawn hierarchy ────────────────────────────────────────────────- /// Tier this archetype occupies in the spawn hierarchy- /// (`chat` → `reasoning` → `worker`). Drives loader-time validation- /// of [`AgentDefinition::subagents`] and runtime depth gating in the- /// sub-agent runner. Defaults to [`AgentTier::Worker`] so existing- /// specialists fit the "leaf" role without per-file edits.- ///- /// **Hierarchy contract** (enforced by- /// [`super::super::agents::loader`] at registry build time):- ///- /// * `Chat` MUST NOT list another `Chat` agent in `subagents`. The- /// user-facing fast tier is a leaf in its own dimension — it- /// hands off to `Reasoning` or `Worker`, never to itself.- /// * `Reasoning` MUST NOT list another `Reasoning` agent in- /// `subagents`. Reasoning composes downward into `Worker`s.- /// * `Worker` MUST NOT list open-ended subagents. Workers execute;- /// they do not orchestrate.- /// * `{ skills = "*" }` entries admit no sub-agent, so they are always- /// allowed.- ///- /// Combined with the host's `MAX_SPAWN_DEPTH = 3` policy- /// gate, this means any execution chain bottoms out within three- /// hops: `chat → reasoning → worker` (or `chat → worker` for the- /// fast path).- #[serde(default)]- pub agent_tier: AgentTier,-- /// Whether this agent's turns can search and call the tools of every- /// connected MCP server (deferred, through `tool_search`). Set for the- /// user-facing orchestrator; specialists reach MCP only through it.- #[serde(default)]- pub searches_connected_mcp: bool,-- // ── source bookkeeping ──────────────────────────────────────────────- /// Tracks where the definition was loaded from (Builtin vs. File).- #[serde(skip)]- pub source: DefinitionSource,-}--impl AgentDefinition {- /// The agent ids this definition may spawn, derived from- /// [`AgentDefinition::subagents`]. Only [`SubagentEntry::AgentId`]- /// entries admit a target; the `{ skills = "*" }` wildcard admits none —- /// a chat agent searches for and calls an integration action itself. The runner's spawn gate (`parent.allowed_subagent_ids`) reads- /// this, so a definition without a bare id for an agent cannot reach it- /// through `spawn_async_subagent` either.- pub fn allowed_subagent_ids(&self) -> Vec<String> {- self.subagents- .iter()- .filter_map(|entry| match entry {- SubagentEntry::AgentId(id) => Some(id.clone()),- SubagentEntry::Skills(_) => None,- })- .collect()- }-- /// Display name with fallback to id.- pub fn display_name(&self) -> &str {- self.display_name.as_deref().unwrap_or(&self.id)- }-- /// Effective iteration cap after applying [`IterationPolicy`].- ///- /// * `Strict` → `self.max_iterations` unchanged.- /// * `Extended` → the higher of `self.max_iterations` and the- /// harness-wide [`EXTENDED_MAX_TOOL_ITERATIONS`].- pub fn effective_max_iterations(&self) -> usize {- match self.iteration_policy {- IterationPolicy::Strict => self.max_iterations,- IterationPolicy::Extended => self.max_iterations.max(EXTENDED_MAX_TOOL_ITERATIONS),- }- }-- /// Resolve the authored TokenJuice profile to the concrete per-call policy.- pub fn effective_tokenjuice_compression(&self) -> AgentTokenjuiceCompression {- match self.tokenjuice_compression {- AgentTokenjuiceCompression::Auto => match &self.model {- ModelSpec::Hint(hint) if hint.trim().eq_ignore_ascii_case("coding") => {- AgentTokenjuiceCompression::Light- }- _ => AgentTokenjuiceCompression::Full,- },- other => other,- }- }-}--// ─────────────────────────────────────────────────────────────────────────────-// Defaults module — referenced by `#[serde(default = ...)]`-// ─────────────────────────────────────────────────────────────────────────────--pub(crate) mod defaults {- use super::PromptSource;-- pub(crate) fn true_() -> bool {- true- }-- pub(crate) fn subagent_temperature() -> f64 {- 0.4- }-- pub(crate) fn max_iterations() -> usize {- 8- }-- /// Placeholder for [`super::AgentDefinition::system_prompt`] when the- /// TOML omits the field. The built-in loader overwrites this with- /// the rendered sibling `prompt.md`; custom TOMLs that omit the- /// field get a no-op empty prompt (and should not).- pub(crate) fn empty_inline_prompt() -> PromptSource {- PromptSource::Inline(String::new())- }-}diff --git a/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs b/crates/openhuman-core/src/agent/harness/definition/execution_spec.rsdeleted file mode 100644index e1ce5c484d..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs+++ /dev/null@@ -1,87 +0,0 @@-//! Runtime execution knobs of a definition: model selection-//! ([`ModelSpec`]), tool visibility ([`ToolScope`]) and sandboxing-//! ([`SandboxMode`]).--use serde::{Deserialize, Serialize};--/// Model selection for a sub-agent.-#[derive(Debug, Clone, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum ModelSpec {- /// Use the parent agent's currently-selected model at spawn time.- #[default]- Inherit,- /// Exact model name (e.g. `"neocortex-mk1"`).- Exact(String),- /// Router hint (e.g. `"reasoning"`, `"coding"`, `"local"`). Resolved- /// to a real model by the routing provider.- Hint(String),-}--impl ModelSpec {- /// Resolve this spec into the model name string the provider expects.- /// `parent_model` is the model the parent agent is using right now.- ///- /// Hints are resolved to the `hint:{hint}` role alias (e.g. `"agentic"` →- /// `"hint:agentic"`), which the inference factory translates to the role's- /// configured route — the managed default model, or the BYOK/local model- /// routed to that workload. When a `RouterProvider` is present its route- /// table takes priority over this default.- pub fn resolve(&self, parent_model: &str) -> String {- match self {- Self::Inherit => parent_model.to_string(),- Self::Exact(name) => name.clone(),- Self::Hint(hint) => format!("hint:{hint}"),- }- }-}--/// Which tools a sub-agent is allowed to call.-#[derive(Debug, Clone, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum ToolScope {- /// All tools the parent has (subject to `disallowed_tools` and- /// `skill_filter`).- #[default]- Wildcard,- /// An explicit allowlist of tool names. Names not present in the parent- /// registry at spawn time are silently dropped (logged at debug).- Named(Vec<String>),-}--/// The tools through which an agent spawns sub-agents of its own choosing.-/// A named scope that lists none of them delegates only to what its host-/// declared, never to an inherited roster.-pub const SPAWN_TOOL_NAMES: &[&str] = &[- "spawn_subagent",- "spawn_async_subagent",- "spawn_parallel_agents",- "spawn_worker_thread",-];--impl ToolScope {- /// Whether this is a named scope that lists one of [`SPAWN_TOOL_NAMES`].- pub fn names_a_spawn_tool(&self) -> bool {- matches!(self, ToolScope::Named(names)- if names.iter().any(|name| SPAWN_TOOL_NAMES.contains(&name.as_str())))- }-}--/// Sandbox mode for a sub-agent's tool execution. Serialises as a simple-/// `snake_case` string in TOML (`none` / `read_only` / `sandboxed`). In-/// the future this may map directly into a `SecurityPolicy` builder.-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum SandboxMode {- /// No additional sandboxing beyond what the parent already enforces.- #[default]- None,- /// Read-only — write/execute tools are filtered out.- ReadOnly,- /// Drop privileges, restrict filesystem (Landlock / Bubblewrap).- Sandboxed,-}--#[cfg(test)]-#[path = "execution_spec_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/definition/execution_spec_tests.rs b/crates/openhuman-core/src/agent/harness/definition/execution_spec_tests.rsdeleted file mode 100644index bc1d66ab2b..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/execution_spec_tests.rs+++ /dev/null@@ -1,15 +0,0 @@-use super::*;--#[test]-fn only_a_named_scope_listing_a_spawn_tool_names_one() {- let named = |names: &[&str]| ToolScope::Named(names.iter().map(|n| (*n).to_string()).collect());- for spawn in SPAWN_TOOL_NAMES {- assert!(named(&["memory", spawn]).names_a_spawn_tool(), "{spawn}");- }- assert!(!named(&["memory", "cron"]).names_a_spawn_tool());- assert!(!named(&[]).names_a_spawn_tool());- assert!(- !ToolScope::Wildcard.names_a_spawn_tool(),- "a wildcard names nothing"- );-}diff --git a/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs b/crates/openhuman-core/src/agent/harness/definition/prompt_source.rsdeleted file mode 100644index 027da03e36..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs+++ /dev/null@@ -1,89 +0,0 @@-//! Where a sub-agent's system prompt comes from: inline text, a prompt-//! file, or a runtime [`PromptBuilder`] function (built-ins only).--use serde::ser::SerializeMap;-use serde::{Deserialize, Serialize};--/// Builder function signature for [`PromptSource::Dynamic`]. Takes the-/// full runtime [`crate::agent::prompts::PromptContext`]-/// (tools, skills, memory, connected integrations, dispatcher, model,-/// …) and returns the final system prompt body — typically assembled-/// by calling the `render_*` section helpers in-/// [`crate::agent::prompts`] in the order the builder-/// wants.-pub type PromptBuilder = fn(&crate::agent::prompts::PromptContext<'_>) -> anyhow::Result<String>;--/// Where the sub-agent's core system prompt comes from.-#[derive(Clone)]-pub enum PromptSource {- /// Inline prompt string (custom TOML-defined agents).- Inline(String),- /// Relative path under the workspace's `prompts/` directory or under- /// `crates/openhuman-core/src/agent/prompts/` for built-ins. Resolved by the runner- /// at spawn time.- File { path: String },- /// Function-driven prompt: the builder is invoked at spawn time with- /// a [`crate::agent::prompts::PromptContext`] so the returned body can depend on runtime- /// state (available tools, user profile, connected skills, etc.).- ///- /// Only constructed in-process (by built-in agent loaders). Not- /// deserializable from TOML — TOML-authored agents must use `inline`- /// or `file`.- Dynamic(PromptBuilder),- /// The whole system prompt, verbatim: no identity, safety, tools,- /// workspace or memory section is composed around it. For a library host- /// that owns its prompt outright (`AgentDefinitionSpec::bare_prompt` in- /// `openhuman-embed`).- Verbatim(String),-}--impl std::fmt::Debug for PromptSource {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- PromptSource::Inline(s) => f.debug_tuple("Inline").field(&s).finish(),- PromptSource::File { path } => f.debug_struct("File").field("path", path).finish(),- PromptSource::Dynamic(_) => f.debug_tuple("Dynamic").field(&"<fn>").finish(),- PromptSource::Verbatim(s) => f.debug_tuple("Verbatim").field(&s).finish(),- }- }-}--impl Serialize for PromptSource {- fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {- let mut map = serializer.serialize_map(Some(1))?;- match self {- PromptSource::Inline(s) => map.serialize_entry("inline", s)?,- PromptSource::File { path } => {- #[derive(Serialize)]- struct FileBody<'a> {- path: &'a str,- }- map.serialize_entry("file", &FileBody { path })?;- }- // Opaque marker — runtime-only. Round-trips back through- // Deserialize would produce an error (Dynamic is unsupported- // there) which is intentional: RPC consumers treat Dynamic- // sources as "built-in, runtime-generated".- PromptSource::Dynamic(_) => map.serialize_entry("dynamic", &serde_json::Value::Null)?,- PromptSource::Verbatim(s) => map.serialize_entry("verbatim", s)?,- }- map.end()- }-}--impl<'de> Deserialize<'de> for PromptSource {- fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {- #[derive(Deserialize)]- #[serde(rename_all = "snake_case")]- enum Shape {- Inline(String),- File { path: String },- Verbatim(String),- }- Shape::deserialize(deserializer).map(|s| match s {- Shape::Inline(body) => PromptSource::Inline(body),- Shape::File { path } => PromptSource::File { path },- Shape::Verbatim(body) => PromptSource::Verbatim(body),- })- }-}diff --git a/crates/openhuman-core/src/agent/harness/definition/registry.rs b/crates/openhuman-core/src/agent/harness/definition/registry.rsdeleted file mode 100644index a86e29e247..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/registry.rs+++ /dev/null@@ -1,202 +0,0 @@-//! In-memory [`AgentDefinitionRegistry`] and its process-wide singleton.--use super::agent_definition::AgentDefinition;-use anyhow::Result;-use std::collections::HashMap;-use std::path::Path;-use std::sync::{Arc, OnceLock};--/// Whether two definitions serialise identically, which covers every-/// authored field (the process-local `source` and `graph` are not serialised).-fn same_definition(a: &AgentDefinition, b: &AgentDefinition) -> bool {- match (serde_json::to_value(a), serde_json::to_value(b)) {- (Ok(a), Ok(b)) => a == b,- _ => false,- }-}--/// In-memory registry of all known [`AgentDefinition`]s.-///-/// One singleton instance is initialised at startup via-/// [`AgentDefinitionRegistry::init_global`]. Built-ins are registered-/// unconditionally; custom TOML definitions (if a workspace is provided)-/// are loaded next and override built-ins on `id` collision.-#[derive(Debug, Default)]-pub struct AgentDefinitionRegistry {- by_id: HashMap<String, AgentDefinition>,- /// Insertion-stable order for predictable `list()` output.- order: Vec<String>,-}--static GLOBAL: OnceLock<Arc<AgentDefinitionRegistry>> = OnceLock::new();--impl AgentDefinitionRegistry {- /// Build a registry containing only the built-in definitions- /// (no TOML loading). Useful for tests.- pub fn builtins_only() -> Self {- let mut reg = Self::default();- for def in super::super::builtin_definitions::all() {- reg.insert(def);- }- reg- }-- /// Build a registry containing built-ins plus any custom TOML- /// definitions found under `<workspace>/agents/*.toml` (and the- /// `~/.openhuman/agents/*.toml` fallback). Custom definitions- /// override built-ins on `id` collision. Files that fail to parse- /// are logged and skipped rather than aborting startup.- pub fn load(workspace: &Path) -> Result<Self> {- let mut reg = Self::builtins_only();- let custom = super::super::definition_loader::load_from_workspace(workspace)?;- for def in custom {- tracing::info!(- id = %def.id,- source = ?def.source,- "[agent_defs] loaded custom definition (overrides any built-in with the same id)"- );- reg.insert(def);- }-- // Re-validate the tier hierarchy after custom overrides are- // merged in — a workspace TOML can legally replace a built-in- // (same id) and is held to the same spawn-hierarchy contract- // as the bundled set. See- // [`crate::agent::registry::agents::loader::validate_tier_hierarchy`].- let snapshot: Vec<AgentDefinition> = reg.list().into_iter().cloned().collect();- crate::agent::registry::agents::validate_tier_hierarchy(&snapshot).map_err(|e| {- anyhow::anyhow!(- "agent registry rejected after merging workspace overrides from {}: {}",- workspace.display(),- e- )- })?;-- Ok(reg)- }-- /// Convenience: resolve the default workspace via- /// [`crate::config::Config::load_or_init`] and load from- /// it. Built for sync CLI call sites (`openhuman agent list`,- /// future inspection tools) so they don't re-implement the Config- /// → workspace resolution dance. Must NOT be called from an- /// existing tokio runtime — construct a runtime and `block_on`.- pub async fn load_for_default_workspace() -> Result<Self> {- let config = crate::config::Config::load_or_init().await?;- Self::load(&config.workspace_dir)- }-- /// Insert (or replace) a definition by id.- pub fn insert(&mut self, def: AgentDefinition) {- let id = def.id.clone();- if self.by_id.insert(id.clone(), def).is_none() {- self.order.push(id);- }- }-- /// Look up a definition by id.- pub fn get(&self, id: &str) -> Option<&AgentDefinition> {- self.by_id.get(id)- }-- /// All definitions, in insertion order.- pub fn list(&self) -> Vec<&AgentDefinition> {- self.order- .iter()- .filter_map(|id| self.by_id.get(id))- .collect()- }-- /// Number of registered definitions.- pub fn len(&self) -> usize {- self.by_id.len()- }-- /// True when the registry has no definitions.- pub fn is_empty(&self) -> bool {- self.by_id.is_empty()- }-- /// Whether this registry is exactly the built-in set: the same ids- /// and contents as [`Self::builtins_only`], and no definition loaded from- /// a file or synthesized from a user entry. SaaS boot refuses anything else.- pub fn holds_builtins_only(&self) -> bool {- let builtins = Self::builtins_only();- self.len() == builtins.len()- && self.list().iter().all(|def| {- def.source == super::DefinitionSource::Builtin- && builtins- .get(&def.id)- .is_some_and(|builtin| same_definition(def, builtin))- })- }-- // ── singleton API ──────────────────────────────────────────────────-- /// Initialise the global registry. Subsequent calls are no-ops (the- /// `OnceLock` only fires once); use [`Self::reload_global`] to refresh- /// custom definitions during development.- pub fn init_global(workspace: &Path) -> Result<()> {- let registry = Self::load(workspace)?;- match GLOBAL.set(Arc::new(registry)) {- Ok(()) => {- tracing::info!(- "[agent_defs] global registry initialised with {} definitions",- GLOBAL.get().map(|r| r.len()).unwrap_or(0)- );- Ok(())- }- Err(_) => {- tracing::debug!("[agent_defs] global registry already initialised; ignoring");- Ok(())- }- }- }-- /// Initialise the global registry with builtins only (no workspace- /// scan). Used by tests and by callers that don't have a workspace.- pub fn init_global_builtins() -> Result<()> {- let registry = Self::builtins_only();- let _ = GLOBAL.set(Arc::new(registry));- Ok(())- }-- /// Borrow the global registry, if initialised.- pub fn global() -> Option<&'static Self> {- GLOBAL.get().map(Arc::as_ref)- }-- /// Clones the durable process registry for a host capability bundle.- ///- /// Hosted invocations need owned authority because their capability bundle- /// outlives the factory stack frame. This is the owned counterpart of- /// [`Self::global`], not a rebuilt or global lookup performed mid-turn.- pub fn global_arc() -> Option<Arc<Self>> {- GLOBAL.get().cloned()- }-- /// The catalogue sub-agent lookups resolve through: the ambient agent- /// context's own registry when it carries one, else the process registry.- pub fn current() -> Option<Arc<Self>> {- crate::core::runtime::CoreContext::current()- .and_then(|ctx| ctx.definitions())- .or_else(Self::global_arc)- }-- /// A copy of this registry with `definitions` added, replacing any- /// definition with the same id.- pub fn with_definitions(&self, definitions: impl IntoIterator<Item = AgentDefinition>) -> Self {- let mut registry = Self::default();- for definition in self.list() {- registry.insert(definition.clone());- }- for definition in definitions {- registry.insert(definition);- }- registry- }-}--#[cfg(test)]-#[path = "registry_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/definition/registry_tests.rs b/crates/openhuman-core/src/agent/harness/definition/registry_tests.rsdeleted file mode 100644index ba1c17cb6e..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/registry_tests.rs+++ /dev/null@@ -1,83 +0,0 @@-use super::*;-use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};--fn named(id: &str, when: &str) -> AgentDefinition {- let mut definition = AgentDefinitionRegistry::builtins_only()- .get("orchestrator")- .cloned()- .expect("built-in orchestrator");- definition.id = id.to_string();- definition.when_to_use = when.to_string();- definition-}--#[test]-fn with_definitions_adds_and_replaces_without_touching_the_source() {- let base = AgentDefinitionRegistry::builtins_only();- let before = base.len();- let own = base.with_definitions([- named("own-worker", "added"),- named("orchestrator", "replaced"),- ]);- assert_eq!(own.len(), before + 1);- assert_eq!(own.get("own-worker").unwrap().when_to_use, "added");- assert_eq!(own.get("orchestrator").unwrap().when_to_use, "replaced");- assert!(base.get("own-worker").is_none());- assert_ne!(base.get("orchestrator").unwrap().when_to_use, "replaced");-}--#[tokio::test]-async fn current_follows_the_agent_context_and_falls_back_to_the_process() {- let own = Arc::new(- AgentDefinitionRegistry::builtins_only().with_definitions([named("ctx-only", "mine")]),- );- let parent = CoreContext::for_test(DomainSet::full(), Some(std::env::temp_dir()));- let agent = parent.derive_with(- ContextOverlay::new(- crate::config::Config::default(),- DomainSet::kernel(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent("catalogue-agent")- .definitions(Arc::clone(&own)),- );-- let seen = CoreContext::scope(agent, async { AgentDefinitionRegistry::current() })- .await- .expect("the agent's registry");- assert!(Arc::ptr_eq(&seen, &own));-- let outside = CoreContext::scope(parent, async { AgentDefinitionRegistry::current() }).await;- assert!(- outside.is_none_or(|registry| registry.get("ctx-only").is_none()),- "a context without its own catalogue resolves through the process"- );-}--#[test]-fn builtins_only_registry_holds_builtins_only() {- assert!(AgentDefinitionRegistry::builtins_only().holds_builtins_only());-}--#[test]-fn an_extra_definition_is_not_builtins_only() {- let extra =- AgentDefinitionRegistry::builtins_only().with_definitions([named("own-worker", "added")]);- assert!(!extra.holds_builtins_only());-}--#[test]-fn a_file_sourced_override_is_not_builtins_only() {- let mut overridden = named("orchestrator", "from a workspace file");- overridden.source =- crate::agent::harness::DefinitionSource::File("/ws/agents/orchestrator.toml".into());- let registry = AgentDefinitionRegistry::builtins_only().with_definitions([overridden]);- assert!(!registry.holds_builtins_only());-}--#[test]-fn a_builtin_tagged_override_with_other_contents_is_not_builtins_only() {- let registry = AgentDefinitionRegistry::builtins_only()- .with_definitions([named("orchestrator", "replaced but still tagged Builtin")]);- assert!(!registry.holds_builtins_only());-}diff --git a/crates/openhuman-core/src/agent/harness/definition/source.rs b/crates/openhuman-core/src/agent/harness/definition/source.rsdeleted file mode 100644index 833acfaf66..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/source.rs+++ /dev/null@@ -1,26 +0,0 @@-//! Provenance of a definition: built-in, custom TOML file, or the-//! config-backed custom registry.--use serde::{Deserialize, Serialize};-use std::path::PathBuf;--/// Where an [`super::AgentDefinition`] was loaded from. Used for telemetry and-/// the `agent::list_definitions` RPC reply.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(tag = "kind", content = "path")]-pub enum DefinitionSource {- /// Built-in definition shipped as part of the binary (loaded from- /// [`crate::agent::registry::agents`]).- #[default]- Builtin,- /// Loaded from a TOML file at the given absolute path.- File(PathBuf),- /// Synthesized at lookup time from a user-authored- /// [`AgentRegistryEntry`](crate::agent::registry::AgentRegistryEntry)- /// (`AgentRegistrySource::Custom`) by `agent_registry::defaults::definition_from_registry_entry`.- /// Never persisted in the [`super::AgentDefinitionRegistry`] — built fresh per- /// factory call so config edits take effect immediately (closes the gap- /// where custom agents ran persona-only instead of with their real tool- /// belt).- CustomRegistry,-}diff --git a/crates/openhuman-core/src/agent/harness/definition/subagents.rs b/crates/openhuman-core/src/agent/harness/definition/subagents.rsdeleted file mode 100644index 954dd8249c..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/subagents.rs+++ /dev/null@@ -1,69 +0,0 @@-//! `subagents` allowlist entries: agent ids and the `{ skills = "*" }`-//! wildcard, plus the lenient deserializer that accepts both TOML shapes.--use serde::{Deserialize, Deserializer, Serialize};--/// One entry in [`super::AgentDefinition::subagents`]. Parses from TOML as either-/// a bare string (agent id) or an inline table (`{ skills = "*" }`) thanks-/// to `#[serde(untagged)]`.-///-/// # TOML shapes-///-/// ```toml-/// [subagents]-/// allowlist = [-/// "task_manager_agent", # AgentId("task_manager_agent")-/// "vision_agent", # AgentId("vision_agent")-/// { skills = "*" }, # Skills { pattern: "*" }-/// ]-/// ```-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-#[serde(untagged)]-pub enum SubagentEntry {- /// Delegate to a specific built-in or custom agent by id.- AgentId(String),- /// Expand at build time to the connected Composio toolkits' actions as- /// `Deferred` tools — off the wire, found through the harness's- /// `tool_search`, and called directly by this agent. No sub-agent is- /// reachable through this entry: it widens the searchable catalogue,- /// not the spawnable set.- Skills(SkillsWildcard),-}--/// The `{ skills = "*" }` inline table in a `subagents` list.-///-/// Today only `"*"` is meaningful (expand to every connected toolkit).-/// Future: a `Vec<String>` variant to restrict expansion to specific-/// toolkit slugs (e.g. `{ skills = ["gmail", "notion"] }`).-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-pub struct SkillsWildcard {- /// Glob / wildcard pattern. Only `"*"` is currently supported.- pub skills: String,-}--pub(super) fn deserialize_subagent_entries<'de, D>(- deserializer: D,-) -> Result<Vec<SubagentEntry>, D::Error>-where- D: Deserializer<'de>,-{- #[derive(Deserialize)]- #[serde(untagged)]- enum Wire {- Section { allowlist: Vec<SubagentEntry> },- LegacyList(Vec<SubagentEntry>),- }-- match Option::<Wire>::deserialize(deserializer)? {- Some(Wire::Section { allowlist }) => Ok(allowlist),- Some(Wire::LegacyList(entries)) => Ok(entries),- None => Ok(Vec::new()),- }-}--impl SkillsWildcard {- /// True when this wildcard should expand to every connected toolkit.- pub fn matches_all(&self) -> bool {- self.skills == "*"- }-}diff --git a/crates/openhuman-core/src/agent/harness/definition/tier.rs b/crates/openhuman-core/src/agent/harness/definition/tier.rsdeleted file mode 100644index 2f3f6e1f4d..0000000000--- a/crates/openhuman-core/src/agent/harness/definition/tier.rs+++ /dev/null@@ -1,100 +0,0 @@-//! Spawn-hierarchy tier ([`AgentTier`]) and the single tier-transition rule-//! shared by the loader's static check and the runtime spawn gate.--use serde::{Deserialize, Serialize};--/// Role an agent plays in the spawn hierarchy.-///-/// See [`super::AgentDefinition::agent_tier`] for the full contract. In short:-///-/// ```text-/// Chat (fast, UX-focused)-/// └─► Reasoning (slow, deep-thinking)-/// └─► Worker (leaf executors)-/// └─► Worker (direct fast-path delegation)-/// ```-///-/// `Chat` and `Reasoning` are forbidden from spawning their own tier;-/// `Worker` is forbidden from spawning anything. Total depth is capped-/// at three hops by the harness regardless of tier (defence in depth-/// against custom TOMLs that drop the tier annotation).-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum AgentTier {- /// User-facing fast-tier agent (e.g. the Orchestrator on the- /// `chat` model hint). Optimised for TTFT, not for long-horizon- /// reasoning. May delegate to `Reasoning` or `Worker`; must NOT- /// delegate to another `Chat` agent.- Chat,- /// Deep-thinking agent on a `hint:reasoning`-style model (e.g. the- /// Planner). Decomposes long-running tasks and delegates execution- /// to one or more `Worker`s. Must NOT delegate to another- /// `Reasoning` agent.- Reasoning,- /// Leaf executor — code executors, critics, summarizers,- /// integration specialists, etc. Workers do the actual work and must- /// NOT spawn further subagents (a `Worker` with a non-empty- /// `subagents` list is rejected by the loader).- #[default]- Worker,-}--impl AgentTier {- /// Human-readable tier name used in error messages.- pub fn as_str(self) -> &'static str {- match self {- Self::Chat => "chat",- Self::Reasoning => "reasoning",- Self::Worker => "worker",- }- }-}--impl std::fmt::Display for AgentTier {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(self.as_str())- }-}--/// Single source of truth for the spawn-hierarchy rule: is a `parent`-tier-/// agent allowed to delegate to a `child`-tier agent?-///-/// Returns `Ok(())` for the legal handoffs and `Err(reason)` for the three-/// forbidden shapes, where `reason` is a tier-only human-readable explanation-/// (no agent ids — callers prepend their own context):-///-/// - `Worker → *` — workers are leaf executors and must not spawn anything.-/// - `Chat → Chat` — the chat tier is a leaf in its own dimension; cloning it-/// defeats the fast-path and risks unbounded `chat → chat → …` chains.-/// - `Reasoning → Reasoning` — reasoning agents compose downward into workers,-/// not into each other (a depth-blowing recursion of slow models).-///-/// Note this forbids same-tier and worker-as-parent hops, **not** upward hops:-/// `reasoning → chat` is a legal edge (a reasoning agent can hand a follow-up-/// back to the `orchestrator` chat agent), so it must stay allowed. The host's `MAX_SPAWN_DEPTH` cap bounds chain length-/// independently of tier direction.-///-/// This is the static authoring rule the loader walks over declared `subagents`-/// pairs at boot (see-/// [`crate::agent::registry::agents::validate_tier_hierarchy`]). The-/// runtime spawn gate (`run_subagent`) reuses it as defense-in-depth, but-/// deliberately exempts worker *parents* — a worker's `subagents` list holds-/// no agent id (the loader rejects one), so the only runtime spawn a worker-/// reaches is one the host dispatched for it, not one it chose.-pub fn validate_tier_transition(parent: AgentTier, child: AgentTier) -> Result<(), String> {- match (parent, child) {- (AgentTier::Worker, _) => Err(format!(- "a `worker` tier agent must not spawn `{}` — workers are leaf executors",- child.as_str()- )),- (AgentTier::Chat, AgentTier::Chat) => Err(- "the chat tier is a leaf in its own dimension — hand off to a `reasoning` or \- `worker` agent instead"- .to_string(),- ),- (AgentTier::Reasoning, AgentTier::Reasoning) => {- Err("reasoning agents compose downward into workers, not into each other".to_string())- }- _ => Ok(()),- }-}diff --git a/crates/openhuman-core/src/agent/harness/definition_loader.rs b/crates/openhuman-core/src/agent/harness/definition_loader.rsdeleted file mode 100644index abb42f335a..0000000000--- a/crates/openhuman-core/src/agent/harness/definition_loader.rs+++ /dev/null@@ -1,140 +0,0 @@-//! Loads custom [`AgentDefinition`] files from disk.-//!-//! Custom definitions live as TOML files under `<workspace>/agents/*.toml`,-//! with a fallback to `~/.openhuman/agents/*.toml` for user-global-//! specialists. Each file defines exactly one definition.-//!-//! TOML (rather than YAML) is used for consistency with the rest of-//! OpenHuman's config system, which already depends on the `toml` crate-//! and uses TOML for its main config file.-//!-//! The loader is intentionally lenient: it logs and skips files that fail-//! to parse rather than aborting startup, so a single broken specialist-//! never breaks the rest of the system.--use super::definition::{AgentDefinition, DefinitionSource, PromptSource};-use anyhow::{bail, Context, Result};-use std::fs;-use std::path::{Path, PathBuf};--/// Load all custom definitions from `<workspace>/agents/` and the-/// `~/.openhuman/agents/` fallback. Returns an empty Vec when neither-/// directory exists.-pub fn load_from_workspace(workspace: &Path) -> Result<Vec<AgentDefinition>> {- let mut out = Vec::new();- let mut seen_dirs: Vec<PathBuf> = Vec::new();-- let workspace_dir = workspace.join("agents");- if workspace_dir.is_dir() {- load_dir(&workspace_dir, &mut out)?;- seen_dirs.push(workspace_dir);- }-- if let Some(home_dir) = user_home_agents_dir() {- if home_dir.is_dir() && !seen_dirs.contains(&home_dir) {- load_dir(&home_dir, &mut out)?;- }- }-- Ok(out)-}--/// Load every `.toml` file in a single directory (non-recursive). Files-/// that fail to parse are logged and skipped.-pub fn load_dir(dir: &Path, out: &mut Vec<AgentDefinition>) -> Result<()> {- let entries =- fs::read_dir(dir).with_context(|| format!("reading agents dir {}", dir.display()))?;-- for entry in entries {- let entry = match entry {- Ok(e) => e,- Err(err) => {- tracing::warn!(- dir = %dir.display(),- error = %err,- "[agent_defs] failed to read directory entry, skipping"- );- continue;- }- };-- let path = entry.path();- if !path.is_file() {- continue;- }- let Some(ext) = path.extension().and_then(|e| e.to_str()) else {- continue;- };- if ext != "toml" {- continue;- }-- match load_file(&path) {- Ok(def) => {- tracing::debug!(- id = %def.id,- path = %path.display(),- "[agent_defs] loaded custom definition"- );- out.push(def);- }- Err(err) => {- tracing::warn!(- path = %path.display(),- error = %err,- "[agent_defs] failed to load custom definition, skipping"- );- }- }- }- Ok(())-}--/// Load a single TOML file as an [`AgentDefinition`]. Stamps `source` to-/// the absolute path.-///-/// Rejects definitions that omit (or leave blank) their `system_prompt`-/// — built-in agents are loaded separately and have their prompts-/// injected by [`crate::agent::registry::agents::load_builtins`], so a-/// file-loaded definition that arrives with the-/// [`defaults::empty_inline_prompt`] placeholder is always a caller-/// mistake. Custom definitions must set either-/// `[system_prompt] inline = "…"` or `[system_prompt] file = "…"`.-pub fn load_file(path: &Path) -> Result<AgentDefinition> {- let content =- fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;- let mut def: AgentDefinition = toml::from_str(&content)- .with_context(|| format!("parsing {} as AgentDefinition TOML", path.display()))?;- if let PromptSource::Inline(body) = &def.system_prompt {- if body.is_empty() {- bail!(- "{}: missing `system_prompt` — custom definitions must set an inline string \- or a file path",- path.display()- );- }- }- def.source = DefinitionSource::File(path.to_path_buf());- Ok(def)-}--fn user_home_agents_dir() -> Option<PathBuf> {- // Honour OPENHUMAN_HOME first if set; otherwise ~/.openhuman.- if let Ok(custom) = std::env::var("OPENHUMAN_HOME") {- return Some(PathBuf::from(custom).join("agents"));- }- match crate::config::default_root_openhuman_dir() {- Ok(dir) => Some(dir.join("agents")),- Err(error) => {- tracing::debug!(- error = %error,- "[agent-definition-loader] resolving root openhuman dir failed"- );- None- }- }-}--#[cfg(test)]-#[path = "definition_loader_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/definition_loader_tests.rs b/crates/openhuman-core/src/agent/harness/definition_loader_tests.rsdeleted file mode 100644index 20aedf8ae2..0000000000--- a/crates/openhuman-core/src/agent/harness/definition_loader_tests.rs+++ /dev/null@@ -1,155 +0,0 @@-use super::*;-use std::io::Write;--fn write_toml(path: &Path, contents: &str) {- let mut f = fs::File::create(path).unwrap();- f.write_all(contents.as_bytes()).unwrap();-}--fn fresh_workspace() -> tempfile::TempDir {- tempfile::tempdir().unwrap()-}--// NOTE: TOML parsing is positional. Top-level scalars MUST come-// before any `[table]` header — once a header opens, every line-// below it lives inside that table.-const NOTION_TOML: &str = r#"-id = "notion_specialist"-when_to_use = "Delegate Notion queries to a focused specialist."-display_name = "Notion Specialist"-temperature = 0.4-skill_filter = "notion"-max_iterations = 5--[system_prompt]-inline = "You are the Notion specialist. Use only Notion tools."--[model]-hint = "agentic"-"#;--#[test]-fn loads_single_definition_from_workspace() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- write_toml(&agents_dir.join("notion.toml"), NOTION_TOML);-- let defs = load_from_workspace(ws.path()).unwrap();- assert_eq!(defs.len(), 1);- let def = &defs[0];- assert_eq!(def.id, "notion_specialist");- assert_eq!(def.skill_filter.as_deref(), Some("notion"));- assert_eq!(def.max_iterations, 5);- assert!(matches!(def.source, DefinitionSource::File(_)));-}--#[test]-fn empty_when_no_agents_dir() {- let ws = fresh_workspace();- let defs = load_from_workspace(ws.path()).unwrap();- assert!(defs.is_empty());-}--#[test]-fn ignores_non_toml_files() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- write_toml(&agents_dir.join("readme.md"), "not a definition");- write_toml(&agents_dir.join("notion.toml"), NOTION_TOML);-- let defs = load_from_workspace(ws.path()).unwrap();- assert_eq!(defs.len(), 1);-}--#[test]-fn skips_malformed_files_without_aborting() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- write_toml(&agents_dir.join("broken.toml"), "id = \"broken\" [oops");- write_toml(&agents_dir.join("notion.toml"), NOTION_TOML);-- let defs = load_from_workspace(ws.path()).unwrap();- // The broken file is skipped; the valid one still loads.- assert_eq!(defs.len(), 1);- assert_eq!(defs[0].id, "notion_specialist");-}--#[test]-fn registry_load_merges_builtins_and_custom() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- write_toml(&agents_dir.join("notion.toml"), NOTION_TOML);-- let reg = super::super::definition::AgentDefinitionRegistry::load(ws.path()).unwrap();- // The built-in set is allowed to grow over time (new archetypes,- // additional synthetic definitions), so assert presence of the- // specific ids we care about rather than a fixed total count.- assert!(- reg.len() > 1,- "expected at least one built-in plus the custom definition"- );- assert!(reg.get("notion_specialist").is_some());- assert!(reg.get("critic").is_some());-}--#[test]-fn rejects_definition_with_missing_system_prompt() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- // No `[system_prompt]` table — serde falls back to the empty- // inline placeholder, which the loader must reject.- write_toml(- &agents_dir.join("broken.toml"),- r#"-id = "broken"-when_to_use = "should be rejected"-"#,- );- let defs = load_from_workspace(ws.path()).unwrap();- assert!(- defs.is_empty(),- "expected loader to reject definition without system_prompt"- );-}--#[test]-fn custom_definition_overrides_same_id_builtin() {- let ws = fresh_workspace();- let agents_dir = ws.path().join("agents");- fs::create_dir_all(&agents_dir).unwrap();- // Override the built-in `critic` with a custom one.- write_toml(- &agents_dir.join("critic.toml"),- r#"-id = "critic"-when_to_use = "CUSTOM OVERRIDE"--[system_prompt]-inline = "custom prompt"--[tools]-wildcard = {}-"#,- );-- // Load a baseline registry (no custom overrides) to get the- // built-in count dynamically — avoids coupling to a hardcoded number.- let baseline = super::super::definition::AgentDefinitionRegistry::load(- &tempfile::TempDir::new().unwrap().path().join("empty"),- )- .unwrap();- let expected_count = baseline.len();-- let reg = super::super::definition::AgentDefinitionRegistry::load(ws.path()).unwrap();- // Same id replaced the built-in `critic` in place, so the- // registry size doesn't grow when the custom TOML collides.- assert_eq!(reg.len(), expected_count);- let def = reg.get("critic").unwrap();- assert_eq!(def.when_to_use, "CUSTOM OVERRIDE");- assert!(matches!(def.source, DefinitionSource::File(_)));-}diff --git a/crates/openhuman-core/src/agent/harness/host_definition.rs b/crates/openhuman-core/src/agent/harness/host_definition.rsnew file mode 100644index 0000000000..4abcc07106--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/host_definition.rs@@ -0,0 +1,282 @@+//! Host side of the agent-definition vocabulary.+//!+//! The portable record (`AgentDefinition<X>`), its model/tool/tier/iteration+//! vocabulary, the TOML loader and the layered [`DefinitionSet`] live in+//! `tinyagents-definition`. OpenHuman keeps only what it owns here: the+//! [`AgentExt`] extension slot (prompt omissions, TokenJuice profile, the MCP+//! flag and the runtime-only prompt builder), the process-wide and per-context+//! [`AgentDefinitionRegistry`], and path resolution for user definitions+//! (`<workspace>/agents`, `$OPENHUMAN_HOME/agents`).++use std::path::{Path, PathBuf};+use std::sync::{Arc, OnceLock};++use anyhow::Result;+use serde::{Deserialize, Serialize};+use tinyagents_definition::{DefinitionSet, DefinitionSource, DefinitionValidation, ModelSpec};+use tinyjuice_bus::types::AgentTokenjuiceCompression;++#[cfg(test)]+#[path = "host_definition_tests.rs"]+mod tests;++/// Sentinel used to represent an explicit zero-tool scope.+pub const NO_TOOLS_SENTINEL: &str = "__no_tools__";++/// Returns whether a visible-tool set represents an explicit zero-tool scope.+pub fn is_empty_tool_scope(visible: &std::collections::HashSet<String>) -> bool {+ visible.is_empty() || (visible.len() == 1 && visible.contains(NO_TOOLS_SENTINEL))+}++/// Builder function for a function-driven system prompt. Built-in agents only;+/// the portable definition carries an inert `PromptSource::Dynamic(())` marker+/// and the executable builder rides in [`AgentExt::prompt_builder`].+pub type PromptBuilder = fn(&crate::agent::prompts::PromptContext<'_>) -> anyhow::Result<String>;++/// An agent definition with OpenHuman's host fields.+pub type AgentDefinition = tinyagents_definition::AgentDefinition<AgentExt>;++fn true_() -> bool {+ true+}++/// OpenHuman-only authored and runtime fields of an [`AgentDefinition`].+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AgentExt {+ /// Strip the parent's identity section from the prompt.+ #[serde(default = "true_")]+ pub omit_identity: bool,+ /// Do not inject the compiled memory context as the first user message.+ #[serde(default = "true_")]+ pub omit_memory_context: bool,+ /// Strip the standard safety preamble.+ #[serde(default = "true_")]+ pub omit_safety_preamble: bool,+ /// Per-agent TokenJuice tool-result compression profile. `auto` keeps+ /// compression on for normal agents and resolves coding-model agents to+ /// `light`; see [`AgentExt::effective_tokenjuice_compression`].+ #[serde(default)]+ pub tokenjuice_compression: AgentTokenjuiceCompression,+ /// Whether this agent's turns can search and call the tools of every+ /// connected MCP server (deferred, through `tool_search`).+ #[serde(default)]+ pub searches_connected_mcp: bool,+ /// Function-driven system prompt, set with `PromptSource::Dynamic(())`.+ /// Runtime only: never serialised and not authorable in TOML.+ #[serde(skip)]+ pub prompt_builder: Option<PromptBuilder>,+}++impl Default for AgentExt {+ fn default() -> Self {+ Self {+ omit_identity: true,+ omit_memory_context: true,+ omit_safety_preamble: true,+ tokenjuice_compression: AgentTokenjuiceCompression::default(),+ searches_connected_mcp: false,+ prompt_builder: None,+ }+ }+}++impl AgentExt {+ /// Resolve the authored TokenJuice profile to the concrete per-call policy+ /// for an agent whose model pin is `model`.+ pub fn effective_tokenjuice_compression(&self, model: &ModelSpec) -> AgentTokenjuiceCompression {+ match self.tokenjuice_compression {+ AgentTokenjuiceCompression::Auto => match model {+ ModelSpec::Hint(hint) if hint.trim().eq_ignore_ascii_case("coding") => {+ AgentTokenjuiceCompression::Light+ }+ _ => AgentTokenjuiceCompression::Full,+ },+ other => other,+ }+ }+}++/// Whether two definitions serialise identically, which covers every authored+/// field (the process-local `source` and `prompt_builder` are not serialised).+fn same_definition(a: &AgentDefinition, b: &AgentDefinition) -> bool {+ match (serde_json::to_value(a), serde_json::to_value(b)) {+ (Ok(a), Ok(b)) => a == b,+ _ => false,+ }+}++/// Re-check the spawn-hierarchy contract over a slice of definitions.+pub fn validate_tier_hierarchy(defs: &[AgentDefinition]) -> Result<()> {+ let mut set = DefinitionSet::<AgentExt>::new();+ for def in defs {+ set.insert(def.clone());+ }+ set.validate_tier_hierarchy()+}++/// Directories scanned for user definitions, in override order: the workspace+/// `agents/` folder, then `$OPENHUMAN_HOME/agents` (or `~/.openhuman/agents`).+fn user_definition_dirs(workspace: &Path) -> Vec<PathBuf> {+ let mut dirs = vec![workspace.join("agents")];+ if let Some(home) = user_home_agents_dir() {+ dirs.push(home);+ }+ dirs+}++fn user_home_agents_dir() -> Option<PathBuf> {+ if let Ok(custom) = std::env::var("OPENHUMAN_HOME") {+ return Some(PathBuf::from(custom).join("agents"));+ }+ match crate::config::default_root_openhuman_dir() {+ Ok(dir) => Some(dir.join("agents")),+ Err(error) => {+ tracing::debug!(+ error = %error,+ "[agent-definition-loader] resolving root openhuman dir failed"+ );+ None+ }+ }+}++/// In-memory registry of all known [`AgentDefinition`]s.+///+/// One singleton instance is initialised at startup via+/// [`AgentDefinitionRegistry::init_global`]. Built-ins are registered+/// unconditionally; custom TOML definitions (if a workspace is provided) are+/// loaded next and override built-ins on `id` collision.+#[derive(Debug, Default)]+pub struct AgentDefinitionRegistry {+ set: DefinitionSet<AgentExt>,+}++static GLOBAL: OnceLock<Arc<AgentDefinitionRegistry>> = OnceLock::new();++impl AgentDefinitionRegistry {+ /// Build a registry containing only the built-in definitions.+ pub fn builtins_only() -> Self {+ let mut reg = Self::default();+ for def in super::builtin_definitions::all() {+ reg.insert(def);+ }+ reg+ }++ /// Built-ins plus any custom TOML definitions found under+ /// `<workspace>/agents/*.toml` and the user-global agents directory.+ /// Custom definitions override built-ins on `id` collision; files that+ /// fail to parse are logged and skipped, and the merged spawn hierarchy is+ /// re-validated.+ pub fn load(workspace: &Path) -> Result<Self> {+ let mut reg = Self::builtins_only();+ let dirs = user_definition_dirs(workspace);+ let dir_refs: Vec<&Path> = dirs.iter().map(PathBuf::as_path).collect();+ reg.set+ .load_dirs(&dir_refs, DefinitionValidation::NonemptyInlinePrompt)+ .map_err(|e| {+ anyhow::anyhow!(+ "agent registry rejected after merging workspace overrides from {}: {}",+ workspace.display(),+ e+ )+ })?;+ Ok(reg)+ }++ /// Resolve the default workspace via [`crate::config::Config::load_or_init`]+ /// and load from it. Must NOT be called from an existing tokio runtime.+ pub async fn load_for_default_workspace() -> Result<Self> {+ let config = crate::config::Config::load_or_init().await?;+ Self::load(&config.workspace_dir)+ }++ /// Insert (or replace) a definition by id.+ pub fn insert(&mut self, def: AgentDefinition) {+ self.set.insert(def);+ }++ /// Look up a definition by id.+ pub fn get(&self, id: &str) -> Option<&AgentDefinition> {+ self.set.get(id)+ }++ /// All definitions, in insertion order.+ pub fn list(&self) -> Vec<&AgentDefinition> {+ self.set.list()+ }++ /// Number of registered definitions.+ pub fn len(&self) -> usize {+ self.set.len()+ }++ /// True when the registry has no definitions.+ pub fn is_empty(&self) -> bool {+ self.set.is_empty()+ }++ /// Whether this registry is exactly the built-in set: the same ids and+ /// contents as [`Self::builtins_only`], and no definition loaded from a+ /// file or synthesized from a user entry. SaaS boot refuses anything else.+ pub fn holds_builtins_only(&self) -> bool {+ let builtins = Self::builtins_only();+ self.len() == builtins.len()+ && self.list().iter().all(|def| {+ def.source == DefinitionSource::Builtin+ && builtins+ .get(&def.id)+ .is_some_and(|builtin| same_definition(def, builtin))+ })+ }++ /// Initialise the global registry. Subsequent calls are no-ops.+ pub fn init_global(workspace: &Path) -> Result<()> {+ let registry = Self::load(workspace)?;+ match GLOBAL.set(Arc::new(registry)) {+ Ok(()) => {+ tracing::info!(+ "[agent_defs] global registry initialised with {} definitions",+ GLOBAL.get().map(|r| r.len()).unwrap_or(0)+ );+ Ok(())+ }+ Err(_) => {+ tracing::debug!("[agent_defs] global registry already initialised; ignoring");+ Ok(())+ }+ }+ }++ /// Initialise the global registry with builtins only (no workspace scan).+ pub fn init_global_builtins() -> Result<()> {+ let _ = GLOBAL.set(Arc::new(Self::builtins_only()));+ Ok(())+ }++ /// Borrow the global registry, if initialised.+ pub fn global() -> Option<&'static Self> {+ GLOBAL.get().map(Arc::as_ref)+ }++ /// Clones the durable process registry for a host capability bundle.+ pub fn global_arc() -> Option<Arc<Self>> {+ GLOBAL.get().cloned()+ }++ /// The catalogue sub-agent lookups resolve through: the ambient agent+ /// context's own registry when it carries one, else the process registry.+ pub fn current() -> Option<Arc<Self>> {+ crate::core::runtime::CoreContext::current()+ .and_then(|ctx| ctx.definitions())+ .or_else(Self::global_arc)+ }++ /// A copy of this registry with `definitions` added, replacing any+ /// definition with the same id.+ pub fn with_definitions(&self, definitions: impl IntoIterator<Item = AgentDefinition>) -> Self {+ Self {+ set: self.set.with_definitions(definitions),+ }+ }+}