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(triage): restructure evaluator module into smaller focused files
Steven Enamakelc8a6fc76df4f
diff --git a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rsnew file mode 100644index 0000000000..93babe6fa7--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs@@ -0,0 +1,338 @@+//! The [`AgentDefinition`] record itself plus the small policy enums it+//! embeds directly ([`IterationPolicy`], [`TriggerMemoryAgent`]) and the+//! serde default helpers its `#[serde(default = ...)]` attributes name.++use serde::{Deserialize, Serialize};+use std::path::PathBuf;++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 crate::inference::tokenjuice::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,+}++/// Policy for running the memory retrieval agent before a normal agent turn.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "snake_case")]+pub enum TriggerMemoryAgent {+ /// Do not run the memory agent automatically.+ #[default]+ Never,+ /// Run `agent_memory` once before the user's prompt is sent to this agent.+ Always,+}++// ─────────────────────────────────────────────────────────────────────────────+// 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., `researcher`, `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 parent's memory context is stripped.+ #[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,++ /// If `true`, the user's `PROFILE.md` (generated by the onboarding+ /// enrichment pipeline — LinkedIn scrape, etc.) is NOT injected into+ /// the rendered prompt. Defaults to `true` so sub-agents stay lean:+ /// only agents that need to personalise user-facing output (welcome,+ /// orchestrator, the trigger pair) opt in with `omit_profile = false`.+ #[serde(default = "defaults::true_")]+ pub omit_profile: bool,++ /// If `true`, the archivist-curated `MEMORY.md` (long-term distilled+ /// memory file) is NOT injected into the rendered prompt. Defaults+ /// to `true` for the same reason as `omit_profile` — narrow+ /// specialists stay lean; user-facing agents opt in.+ ///+ /// **KV-cache contract:** like every workspace file, once MEMORY.md+ /// is rendered into a session's system prompt the bytes are frozen+ /// for that session's lifetime. Archivist writes that land+ /// mid-session do not retroactively update the in-flight prompt —+ /// they are picked up on the next session. This matches the+ /// byte-stability invariant documented on+ /// [`crate::agent::context::prompt::render_subagent_system_prompt`].+ #[serde(default = "defaults::true_")]+ pub omit_memory_md: 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>,++ // ── 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,++ /// Optional pre-turn memory retrieval hook. When set to `always`, the+ /// harness runs the built-in `agent_memory` agent once with the user+ /// prompt and prepends its result to the prompt sent to this agent.+ #[serde(default)]+ pub trigger_memory_agent: TriggerMemoryAgent,++ /// 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`] — a single collapsed+ /// [`SkillDelegationTool`] named `delegate_to_integrations_agent`+ /// that takes the toolkit slug as an argument and routes to the+ /// generic `integrations_agent` with the corresponding+ /// `skill_filter` pre-populated (#1335).+ ///+ /// `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+ /// [`SkillDelegationTool`]: crate::agent::orchestration::tools::SkillDelegationTool+ #[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. Pre-turn memory retrieval is configured+ /// separately via [`AgentDefinition::trigger_memory_agent`].+ /// * `{ skills = "*" }` entries expand to the generic+ /// `integrations_agent` (a `Worker`) so they are always allowed.+ ///+ /// Combined with the harness's `MAX_SPAWN_DEPTH = 3` task-local+ /// 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,++ // ── source bookkeeping ──────────────────────────────────────────────+ /// Tracks where the definition was loaded from (Builtin vs. File).+ #[serde(skip)]+ pub source: DefinitionSource,++ // ── turn graph ──────────────────────────────────────────────────────+ /// How this agent's turn is driven (issue #4249). Injected post-load from+ /// the agent folder's `graph.rs::graph()` (mirrors how+ /// [`PromptSource::Dynamic`] is injected from `prompt.rs::build`); TOML-+ /// authored agents cannot set it, so it is `#[serde(skip)]` and defaults to+ /// [`AgentGraph::Default`] (the shared default turn graph).+ #[serde(skip, default)]+ pub graph: crate::agent::harness::agent_graph::AgentGraph,+}+++impl AgentDefinition {+ /// 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.rsnew file mode 100644index 0000000000..e8b8657da3--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/execution_spec.rs@@ -0,0 +1,71 @@+//! 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 `{hint}-v1` (e.g. `"agentic"` → `"agentic-v1"`)+ /// which matches the backend's standard model naming convention. When+ /// a `RouterProvider` is present its route table takes priority over+ /// this default; when no router is configured (empty `model_routes`)+ /// the resolved name goes directly to the backend.+ 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}-v1"),+ }+ }+}++++/// 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>),+}++++/// 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,+}+diff --git a/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs b/crates/openhuman-core/src/agent/harness/definition/prompt_source.rsnew file mode 100644index 0000000000..6281655580--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/prompt_source.rs@@ -0,0 +1,83 @@+//! 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::context::prompt::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::context::prompt`] in the order the builder+/// wants.+pub type PromptBuilder =+ fn(&crate::agent::context::prompt::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 [`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),+}++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(),+ }+ }+}++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)?,+ }+ 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 },+ }+ Shape::deserialize(deserializer).map(|s| match s {+ Shape::Inline(body) => PromptSource::Inline(body),+ Shape::File { path } => PromptSource::File { path },+ })+ }+}+diff --git a/crates/openhuman-core/src/agent/harness/definition/registry.rs b/crates/openhuman-core/src/agent/harness/definition/registry.rsnew file mode 100644index 0000000000..f7d96b450b--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/registry.rs@@ -0,0 +1,147 @@+//! 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::OnceLock;++/// 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<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()+ }++ // ── 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(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(registry);+ Ok(())+ }++ /// Borrow the global registry, if initialised.+ pub fn global() -> Option<&'static Self> {+ GLOBAL.get()+ }+}diff --git a/crates/openhuman-core/src/agent/harness/definition/source.rs b/crates/openhuman-core/src/agent/harness/definition/source.rsnew file mode 100644index 0000000000..44487e9fb4--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/source.rs@@ -0,0 +1,26 @@+//! Provenance of a definition: built-in, custom TOML file, or the+//! config-backed custom registry.++use serde::{Deserialize, Serialize};++/// Where an [`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 [`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.rsnew file mode 100644index 0000000000..c95ea348f0--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/subagents.rs@@ -0,0 +1,71 @@+//! `subagents` allowlist entries: agent ids and the `{ skills = "*" }`+//! wildcard, plus the lenient deserializer that accepts both TOML shapes.++use serde::{Deserialize, Deserializer, Serialize};++use super::agent_definition::AgentDefinition;+++/// One entry in [`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 = [+/// "researcher", # AgentId("researcher")+/// "code_executor", # AgentId("code_executor")+/// { 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 a single collapsed+ /// `delegate_to_integrations_agent` tool whose `toolkit` argument+ /// selects which connected Composio toolkit to route to, with+ /// `skill_filter` pre-set on the underlying `integrations_agent`+ /// dispatch (#1335).+ 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,+}++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.rsnew file mode 100644index 0000000000..8cd5f3ef1e--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/definition/tier.rs@@ -0,0 +1,106 @@+//! 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};++use super::agent_definition::AgentDefinition;+++/// Role an agent plays in the spawn hierarchy.+///+/// See [`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 `reasoning-v1`-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 — researchers, code executors, critics, archivists,+ /// 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 real, intentional builtin edge (the `subconscious`+/// reasoner can hand a follow-up back to the `orchestrator` chat agent), so it+/// must stay legal. The harness'es `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* — at runtime a worker only reaches the+/// spawn chokepoint via the documented collapsed `delegate_to_integrations_agent`+/// path (→ `integrations_agent`, itself a worker), which the loader intentionally+/// leaves untouched.+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/learning/linkedin_enrichment.rs b/crates/openhuman-core/src/agent/learning/linkedin_enrichment.rsindex a1d8a23b8b..565d98e2c5 100644--- a/crates/openhuman-core/src/agent/learning/linkedin_enrichment.rs+++ b/crates/openhuman-core/src/agent/learning/linkedin_enrichment.rs@@ -32,19 +32,19 @@ pub use profile_markdown::{render_profile_markdown, summarise_profile_with_llm};mod tests;/// Apify actor slug for the LinkedIn profile scraper.-pub(super) const LINKEDIN_SCRAPER_ACTOR: &str = "dev_fusion/linkedin-profile-scraper";+const LINKEDIN_SCRAPER_ACTOR: &str = "dev_fusion/linkedin-profile-scraper";/// Regex that captures a LinkedIn username from profile URLs.////// Matches both the canonical form (`linkedin.com/in/<slug>`) and the/// notification-email form (`linkedin.com/comm/in/<slug>`). The username/// is captured in group 1 so we can reconstruct a clean canonical URL.-pub(super) static LINKEDIN_USERNAME_RE: LazyLock<Regex> = LazyLock::new(|| {+static LINKEDIN_USERNAME_RE: LazyLock<Regex> = LazyLock::new(|| {Regex::new(r"https?://(?:www\.)?linkedin\.com/(?:comm/)?in/([a-zA-Z0-9_-]+)").unwrap()});/// Build the canonical profile URL from a username slug.-pub(super) fn canonical_linkedin_url(username: &str) -> String {+fn canonical_linkedin_url(username: &str) -> String {format!("https://www.linkedin.com/in/{username}")}diff --git a/crates/openhuman-core/src/agent/learning/linkedin_enrichment/profile_markdown.rs b/crates/openhuman-core/src/agent/learning/linkedin_enrichment/profile_markdown.rsindex a8bfa54d89..0481d91737 100644--- a/crates/openhuman-core/src/agent/learning/linkedin_enrichment/profile_markdown.rs+++ b/crates/openhuman-core/src/agent/learning/linkedin_enrichment/profile_markdown.rs@@ -226,5 +226,3 @@ pub fn render_profile_markdown(url: &str, data: &serde_json::Value) -> String {md}--// ── Internal helpers ─────────────────────────────────────────────────diff --git a/crates/openhuman-core/src/agent/triage/evaluator.rs b/crates/openhuman-core/src/agent/triage/evaluator.rsindex ec8e2af56a..81f71d290c 100644--- a/crates/openhuman-core/src/agent/triage/evaluator.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator.rs@@ -28,8 +28,27 @@//! sending no tool schemas to the backend — the turn degrades to a plain//! chat completion.++mod arm;+mod chain;+mod outcome;+mod prompt;++pub use arm::TRIGGER_TRIAGE_AGENT_ID;+pub use chain::{run_triage, run_triage_with_arms};+pub use outcome::{TriageOutcome, TriageResolutionPath, TriageRun};++#[cfg(test)]+pub(crate) use arm::{classify_error, ArmError};+#[cfg(test)]+pub(crate) use chain::run_triage_with_arms_for_test;+#[cfg(test)]+pub(crate) use prompt::{extract_inline_prompt, render_user_message, truncate_payload};+#[cfg(test)]+use super::envelope::TriggerEnvelope;+#[cfg(test)]+use super::routing::ResolvedProvider;+#[cfg(test)]#[path = "evaluator_tests.rs"]mod tests;-include!("evaluator_part_01.rs");-include!("evaluator_part_02.rs");diff --git a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs b/crates/openhuman-core/src/agent/triage/evaluator/arm.rsindex ead9f78d6a..30e4e0f7e4 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/arm.rs@@ -29,7 +29,7 @@ pub const TRIGGER_TRIAGE_AGENT_ID: &str = "trigger_triage";/// Single-arm execution result. `Retryable` lets the orchestrator/// decide whether to sleep + retry on the same arm (cloud) or to fall/// through (local). `Fatal` short-circuits the whole chain.-enum ArmError {+pub(super) enum ArmError {/// 429 / 5xx / timeout / connection — the kind of failure where/// trying again later might help.Retryable {@@ -62,7 +62,7 @@ enum ArmError {/// Run a single arm: dispatch the agent turn through the native bus/// and parse the reply. Classifies any error so the caller can decide/// what to do next.-async fn try_arm(+pub(super) async fn try_arm(resolved: &ResolvedProvider,envelope: &TriggerEnvelope,intended_path: TriageResolutionPath,@@ -223,7 +223,7 @@ async fn try_arm(/// Classify a handler-failure message string from the agent bus into/// either a retryable (sleep + try again) or fatal (give up) error.-fn classify_error(message: String) -> ArmError {+pub(super) fn classify_error(message: String) -> ArmError {let err = anyhow!("{message}");if is_rate_limited(&err) {return ArmError::Retryable {diff --git a/crates/openhuman-core/src/agent/triage/evaluator/prompt.rs b/crates/openhuman-core/src/agent/triage/evaluator/prompt.rsindex 2f821faa97..5ea4f56a65 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/prompt.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/prompt.rs@@ -9,7 +9,7 @@ use super::super::envelope::TriggerEnvelope;/// How much of the raw payload we inline into the user message.const PAYLOAD_INLINE_LIMIT_BYTES: usize = 8 * 1024;-fn extract_inline_prompt(def: &AgentDefinition) -> Option<String> {+pub(super) fn extract_inline_prompt(def: &AgentDefinition) -> Option<String> {match &def.system_prompt {PromptSource::Inline(body) if !body.is_empty() => Some(body.clone()),PromptSource::Dynamic(build) => {@@ -58,7 +58,7 @@ fn extract_inline_prompt(def: &AgentDefinition) -> Option<String> {}}-fn render_user_message(envelope: &TriggerEnvelope) -> String {+pub(super) fn render_user_message(envelope: &TriggerEnvelope) -> String {let payload_string = truncate_payload(&envelope.payload, PAYLOAD_INLINE_LIMIT_BYTES);format!("SOURCE: {source}\n\@@ -72,7 +72,7 @@ fn render_user_message(envelope: &TriggerEnvelope) -> String {)}-fn format_parse_error(err: &ParseError) -> String {+pub(super) fn format_parse_error(err: &ParseError) -> String {match err {ParseError::NoJsonObject => "classifier reply had no JSON object".to_string(),ParseError::InvalidJson(src) => format!("classifier JSON invalid: {src}"),@@ -82,7 +82,7 @@ fn format_parse_error(err: &ParseError) -> String {}}-fn truncate_payload(payload: &serde_json::Value, max_bytes: usize) -> String {+pub(super) fn truncate_payload(payload: &serde_json::Value, max_bytes: usize) -> String {let pretty = serde_json::to_string_pretty(payload).unwrap_or_else(|_| payload.to_string());if pretty.len() <= max_bytes {return pretty;diff --git a/crates/openhuman-core/src/agent/triage/evaluator_tests_part_02_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rssimilarity index 100%rename from crates/openhuman-core/src/agent/triage/evaluator_tests_part_02_tests.rsrename to crates/openhuman-core/src/agent/triage/evaluator_deferral_tests.rsdiff --git a/crates/openhuman-core/src/agent/triage/evaluator_tests_part_01_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rssimilarity index 100%rename from crates/openhuman-core/src/agent/triage/evaluator_tests_part_01_tests.rsrename to crates/openhuman-core/src/agent/triage/evaluator_fallback_chain_tests.rsdiff --git a/crates/openhuman-core/src/agent/triage/evaluator_part_01.rs b/crates/openhuman-core/src/agent/triage/evaluator_part_01.rsdeleted file mode 100644index ce002c0962..0000000000--- a/crates/openhuman-core/src/agent/triage/evaluator_part_01.rs+++ /dev/null@@ -1,657 +0,0 @@-use std::future::Future;-use std::sync::Arc;-use std::time::{Duration, Instant};--use anyhow::{anyhow, Context};--use crate::core::bus::BUS;-use crate::agent::bus::{AgentTurnRequest, AgentTurnResponse, AGENT_RUN_TURN_METHOD};-use crate::agent::harness::definition::{AgentDefinition, PromptSource};-use crate::agent::harness::AgentDefinitionRegistry;-use crate::agent::messages::ChatMessage;-use crate::config::Config;-use crate::config::MultimodalConfig;-use crate::cron::scheduler_gate::LlmPermit;-use crate::inference::provider::error_classify::{- is_rate_limited, is_upstream_unhealthy, parse_retry_after_ms,-};-use tinybus::NativeRequestError;--use super::decision::{parse_triage_decision, ParseError, TriageDecision};-use super::envelope::TriggerEnvelope;-use super::events;-use super::routing::{- build_local_provider_with_config, resolve_provider_with_config, ResolvedProvider,-};--/// Agent definition id for the built-in triage classifier.-pub const TRIGGER_TRIAGE_AGENT_ID: &str = "trigger_triage";--/// How much of the raw payload we inline into the user message.-const PAYLOAD_INLINE_LIMIT_BYTES: usize = 8 * 1024;--/// Cap on how long to wait for a server-supplied `Retry-After` before-/// giving up on the cloud arm and falling through to local. Mirrors-/// the cap in `ReliableProvider::compute_backoff`.-const RETRY_AFTER_CAP: Duration = Duration::from_millis(30_000);--/// Default backoff for transient (non-rate-limit) cloud failures-/// before the single retry. Short enough to keep tail latency-/// bounded; long enough for a wedged TCP connection to give up.-const TRANSIENT_BACKOFF: Duration = Duration::from_millis(500);--/// How far in the future a Deferred outcome asks the caller to retry.-/// A short tick mirrors the issue's "next tick retries the whole-/// chain" language — long enough to shed a thundering herd, short-/// enough that user-visible latency on transient outages stays in the-/// tens of seconds.-const DEFER_WAKEUP_MS: i64 = 30_000;--/// Which arm produced this triage decision. Surfaced on `TriageRun`-/// so the orchestrator can colour-code degraded turns and show the-/// state in `/debug` views.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum TriageResolutionPath {- /// Cloud succeeded on the initial attempt.- Cloud,- /// Cloud succeeded on the retry after a 429 / transient failure.- CloudAfterRetry,- /// Cloud failed twice; the local arm produced the decision.- LocalFallback,-}--impl TriageResolutionPath {- pub fn as_str(self) -> &'static str {- match self {- Self::Cloud => "cloud",- Self::CloudAfterRetry => "cloud-after-retry",- Self::LocalFallback => "local-fallback",- }- }-}--/// Final output of a single triage run when a decision was produced.-#[derive(Debug, Clone)]-pub struct TriageRun {- pub decision: TriageDecision,- /// `true` when the producing arm was local — kept for telemetry- /// compatibility with subscribers that read this field. Equivalent- /// to `resolution_path == LocalFallback`.- pub used_local: bool,- pub latency_ms: u64,- pub resolution_path: TriageResolutionPath,-}--/// Outcome of [`run_triage`]. Either a parsed decision or a-/// deferral asking the caller to retry the whole chain after-/// `defer_until_ms` (Unix epoch millis).-#[derive(Debug, Clone)]-pub enum TriageOutcome {- Decision(TriageRun),- Deferred {- /// Unix epoch millis at which the caller should re-run the- /// triage chain.- defer_until_ms: i64,- /// Short human-readable reason — already scrubbed; safe to log.- reason: String,- },-}--impl TriageOutcome {- pub fn into_decision(self) -> Option<TriageRun> {- match self {- TriageOutcome::Decision(run) => Some(run),- TriageOutcome::Deferred { .. } => None,- }- }-}--/// Run the triage classifier with the full tiered fallback chain.-///-/// 1. Resolve the cloud provider.-/// 2. Try cloud; on 429 / transient, sleep and retry once.-/// 3. On a second 429 / transient, build the local provider and-/// fall back to it (acquiring the global LLM permit).-/// 4. On local failure, return `TriageOutcome::Deferred` so the-/// caller (typically a trigger-handler RPC) can reschedule.-pub async fn run_triage(envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutcome> {- let config = Config::load_or_init()- .await- .context("loading config for triage turn")?;- let cloud = resolve_provider_with_config(&config)- .await- .context("resolving provider for triage turn")?;- let local = build_local_provider_with_config(&config);-- let outcome = run_triage_with_arms_inner(cloud, local, envelope, || {- crate::cron::scheduler_gate::wait_for_capacity()- })- .await;- if let Err(err) = &outcome {- events::publish_failed(envelope, &format!("{err}"));- }- outcome-}--/// Production entry point that takes already-resolved arms and acquires-/// the global LLM permit via [`scheduler_gate::wait_for_capacity`].-///-/// Use [`run_triage_with_arms_for_test`] in tests to bypass the shared-/// semaphore. This function is `pub` for integration callers outside-/// this module that supply pre-resolved providers.-pub async fn run_triage_with_arms(- cloud: ResolvedProvider,- local: Option<ResolvedProvider>,- envelope: &TriggerEnvelope,-) -> anyhow::Result<TriageOutcome> {- run_triage_with_arms_inner(cloud, local, envelope, || {- crate::cron::scheduler_gate::wait_for_capacity()- })- .await-}--/// Test-only entry point: skip the global LLM permit acquisition so the-/// triage tests don't contend with `scheduler_gate`'s process-wide-/// 1-slot semaphore or get trapped by a stale `Paused` policy left in-/// `STATE` by another test's `init_global` call.-#[cfg(test)]-pub async fn run_triage_with_arms_for_test(- cloud: ResolvedProvider,- local: Option<ResolvedProvider>,- envelope: &TriggerEnvelope,-) -> anyhow::Result<TriageOutcome> {- run_triage_with_arms_inner(cloud, local, envelope, || async { None }).await-}--/// Core implementation of the tiered cloud→retry→local fallback.-///-/// `acquire_permit` is called exactly once, on the local-fallback arm,-/// to obtain the global LLM permit. Production callers pass-/// `scheduler_gate::wait_for_capacity`; tests pass `|| async { None }`-/// to skip the shared semaphore.-async fn run_triage_with_arms_inner<F, Fut>(- cloud: ResolvedProvider,- local: Option<ResolvedProvider>,- envelope: &TriggerEnvelope,- acquire_permit: F,-) -> anyhow::Result<TriageOutcome>-where- F: FnOnce() -> Fut,- Fut: Future<Output = Option<LlmPermit>>,-{- // Track whether the cloud arm bailed because of user budget so the- // eventual Deferred reason explains *why* we're sitting idle rather- // than the generic "both arms failed" copy.- let mut cloud_budget_exhausted: Option<anyhow::Error> = None;- // Track whether the cloud arm bailed because the prompt-guard- // flagged the content (OPENHUMAN-TAURI-X). The guard runs before- // dispatch and is shared across arms, so a flag on cloud will- // repeat on local — surface the verdict in the Deferred reason- // for operator-facing telemetry.- let mut cloud_safety_flagged: Option<anyhow::Error> = None;-- // ── Cloud arm ──────────────────────────────────────────────────- match try_arm(&cloud, envelope, TriageResolutionPath::Cloud).await {- Ok(run) => return Ok(TriageOutcome::Decision(run)),- Err(ArmError::Fatal(err)) => return Err(err),- Err(ArmError::BudgetExhausted(err)) => {- tracing::warn!(- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- path = TriageResolutionPath::Cloud.as_str(),- error = %err,- "[triage::evaluator] cloud rejected for budget; \- skipping retry and falling back to local arm"- );- cloud_budget_exhausted = Some(err);- }- Err(ArmError::SafetyFlagged(err)) => {- tracing::warn!(- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- path = TriageResolutionPath::Cloud.as_str(),- error = %err,- "[triage::evaluator] cloud rejected by prompt-guard; \- skipping retry and falling back to local arm"- );- cloud_safety_flagged = Some(err);- }- Err(ArmError::Retryable { retry_after_ms, .. }) => {- // Sleep before the cloud retry. Honour Retry-After when- // present; otherwise use a short backoff so the second- // attempt has a real chance of finding the upstream- // recovered.- let sleep_ms = retry_after_ms- .map(|ms| Duration::from_millis(ms).min(RETRY_AFTER_CAP))- .unwrap_or(TRANSIENT_BACKOFF);- tracing::info!(- sleep_ms = sleep_ms.as_millis() as u64,- had_retry_after = retry_after_ms.is_some(),- "[triage::evaluator] cloud retry pending after retryable failure"- );- tokio::time::sleep(sleep_ms).await;-- match try_arm(&cloud, envelope, TriageResolutionPath::CloudAfterRetry).await {- Ok(run) => return Ok(TriageOutcome::Decision(run)),- Err(ArmError::Fatal(err)) => return Err(err),- Err(ArmError::BudgetExhausted(err)) => {- tracing::warn!(- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- path = TriageResolutionPath::CloudAfterRetry.as_str(),- error = %err,- "[triage::evaluator] cloud rejected for budget on retry; \- falling back to local arm"- );- cloud_budget_exhausted = Some(err);- }- Err(ArmError::SafetyFlagged(err)) => {- tracing::warn!(- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- path = TriageResolutionPath::CloudAfterRetry.as_str(),- error = %err,- "[triage::evaluator] cloud rejected by prompt-guard on retry; \- falling back to local arm"- );- cloud_safety_flagged = Some(err);- }- Err(ArmError::Retryable { .. }) => {- // Exhausted cloud budget — fall through to local.- tracing::warn!(- "[triage::evaluator] cloud retry budget exhausted; \- falling back to local arm"- );- }- }- }- }-- // ── Local fallback ─────────────────────────────────────────────- let Some(local) = local else {- // No local arm available at all (runtime disabled, no model- // configured) — the only honest outcome is a deferral so the- // next tick retries the whole chain.- //- // `reason` is part of `TriageOutcome::Deferred` and may be- // forwarded into telemetry / UI, so it must stay a stable,- // scrubbed string. Raw upstream error text goes to the debug- // log instead, where it is operator-visible but not surfaced.- let reason = if let Some(err) = cloud_safety_flagged.as_ref() {- tracing::debug!(- target: "[triage::evaluator]",- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- error = %err,- "prompt-guard rejected on cloud; no local arm — full guard verdict"- );- "prompt-guard rejection; local arm unavailable".to_string()- } else if let Some(err) = cloud_budget_exhausted.as_ref() {- tracing::debug!(- target: "[triage::evaluator]",- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- error = %err,- "cloud budget exhausted; no local arm — full upstream error"- );- "cloud budget exhausted; local arm unavailable".to_string()- } else {- "cloud retry exhausted; local arm unavailable".to_string()- };- return Ok(TriageOutcome::Deferred {- defer_until_ms: now_ms().saturating_add(DEFER_WAKEUP_MS),- reason,- });- };-- // Hold the global LLM permit for the lifetime of the local turn —- // protects laptop RAM from concurrent local model calls (#1073).- let _gate_permit = acquire_permit().await;-- match try_arm(&local, envelope, TriageResolutionPath::LocalFallback).await {- Ok(run) => Ok(TriageOutcome::Decision(run)),- Err(ArmError::Fatal(err))- | Err(ArmError::BudgetExhausted(err))- | Err(ArmError::SafetyFlagged(err))- | Err(ArmError::Retryable { source: err, .. }) => {- // Local also failed — defer rather than surface a hard- // error. Today's "hard fail" is the wrong default for a- // transient blocker per #1257.- //- // `reason` is part of the public Deferred outcome and may- // flow into telemetry / UI, so keep it scrubbed. Raw error- // text from cloud + local lives in the structured warn- // fields below — visible to operators, not callers.- let reason = if cloud_safety_flagged.is_some() {- "prompt-guard rejection; local arm also failed".to_string()- } else if cloud_budget_exhausted.is_some() {- "cloud budget exhausted; local arm also failed".to_string()- } else {- "cloud retry exhausted; local arm also failed".to_string()- };- tracing::warn!(- target: "[triage::evaluator]",- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- local_error = %err,- cloud_error = cloud_budget_exhausted- .as_ref()- .or(cloud_safety_flagged.as_ref())- .map(|e| e.to_string())- .unwrap_or_default(),- defer_ms = DEFER_WAKEUP_MS,- reason = %reason,- "both arms failed; deferring"- );- Ok(TriageOutcome::Deferred {- defer_until_ms: now_ms().saturating_add(DEFER_WAKEUP_MS),- reason,- })- }- }-}--/// Single-arm execution result. `Retryable` lets the orchestrator-/// decide whether to sleep + retry on the same arm (cloud) or to fall-/// through (local). `Fatal` short-circuits the whole chain.-enum ArmError {- /// 429 / 5xx / timeout / connection — the kind of failure where- /// trying again later might help.- Retryable {- retry_after_ms: Option<u64>,- source: anyhow::Error,- },- /// Auth failure, missing model, prompt parse error, registry- /// missing, etc. — retry / fallback would not change the result.- Fatal(anyhow::Error),- /// Cloud upstream rejected the call because the user is out of- /// budget / credits. Retrying the cloud arm would just burn the- /// same wall, but the local arm has no upstream cost — so we- /// skip cloud retry, try local, and defer if local also fails.- /// This is **not** a fatal error: the user takes an explicit- /// action (top up) to fix it, so it must not page Sentry.- BudgetExhausted(anyhow::Error),- /// Our prompt-injection guard (`agent::bus`'s `enforce_prompt_input`,- /// also used by `agent::harness::session::runtime`) flagged the- /// incoming content as adversarial / unsafe and refused to dispatch- /// the turn. The guard runs *before* either model is contacted, so- /// trying the same prompt again — on cloud or local — produces the- /// same verdict. This is **not** a fatal error: the guard is doing- /// its job (OPENHUMAN-TAURI-X regression: an adversarial Gmail- /// message reliably trips the guard, and every fire paged Sentry).- /// Route the same way as `BudgetExhausted` so the local-arm fallthrough- /// lands in `TriageOutcome::Deferred` rather than `Err(_)`.- SafetyFlagged(anyhow::Error),-}--/// Run a single arm: dispatch the agent turn through the native bus-/// and parse the reply. Classifies any error so the caller can decide-/// what to do next.-async fn try_arm(- resolved: &ResolvedProvider,- envelope: &TriggerEnvelope,- intended_path: TriageResolutionPath,-) -> Result<TriageRun, ArmError> {- let started = Instant::now();-- tracing::debug!(- source = %envelope.source.slug(),- label = %envelope.display_label,- external_id = %envelope.external_id,- provider = %resolved.provider_name,- used_local = resolved.used_local,- path = intended_path.as_str(),- "[triage::evaluator] starting triage turn"- );-- let registry = AgentDefinitionRegistry::global().ok_or_else(|| {- ArmError::Fatal(anyhow!(- "AgentDefinitionRegistry not initialised — did startup wiring \- skip `init_global`?"- ))- })?;- let definition = registry.get(TRIGGER_TRIAGE_AGENT_ID).ok_or_else(|| {- ArmError::Fatal(anyhow!(- "built-in `{TRIGGER_TRIAGE_AGENT_ID}` definition missing from registry"- ))- })?;-- let system_prompt = extract_inline_prompt(definition).ok_or_else(|| {- ArmError::Fatal(anyhow!(- "trigger_triage agent definition must ship an inline prompt body"- ))- })?;- let user_message = render_user_message(envelope);- let history = vec![- ChatMessage::system(&system_prompt),- ChatMessage::user(&user_message),- ];-- let request = AgentTurnRequest {- turn_model_source: resolved.turn_model_source.clone(),- history,- tools_registry: Arc::new(Vec::new()),- provider_name: resolved.provider_name.clone(),- model: resolved.model.clone(),- temperature: definition.temperature,- silent: true,- channel_name: "triage".to_string(),- multimodal: MultimodalConfig::default(),- // Triage receives untrusted text from third-party channel- // payloads (Slack/Telegram/Discord/WhatsApp). Disable- // file-marker resolution outright so an attacker can't smuggle- // `[FILE:/etc/passwd]` (or any other local-path marker) into- // an inbound message and have triage exfiltrate the contents- // into an LLM call. The hardened constructor sets max_files=0,- // which `prepare_messages_for_provider` short-circuits before- // any disk read happens. The same constructor is used at the- // main channel-dispatch site in `channels::runtime::dispatch`.- multimodal_files:- crate::config::MultimodalFileConfig::for_untrusted_channel_input(),- max_tool_iterations: 1,- on_delta: None,- target_agent_id: Some("trigger_triage".to_string()),- visible_tool_names: None,- extra_tools: Vec::new(),- on_progress: None,- // Triage processes untrusted inbound channel text. Label it as- // ExternalChannel so the approval gate treats any external_effect- // tool call originating from this turn as remote-attacker input- // (the triage agent doesn't usually invoke such tools — it- // classifies and routes — but label correctly for defense in depth).- origin: crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {- channel: envelope.source.slug().to_string(),- // Triage runs over an upstream envelope (composio / webhook /- // cron / external caller) that doesn't carry a per-user sender- // at this layer. Leave it unset and let the gate apply the- // strict per-channel TTL-deny default.- sender: None,- reply_target: envelope.display_label.clone(),- message_id: envelope.external_id.clone(),- },- };-- let response = match BUS- .native()- .request::<AgentTurnRequest, AgentTurnResponse>(AGENT_RUN_TURN_METHOD, request)- .await- {- Ok(r) => r,- Err(err) => {- let message = match &err {- NativeRequestError::HandlerFailed { message, .. } => message.clone(),- other => format!("[agent.run_turn dispatch] {other}"),- };- tracing::warn!(- error = %message,- path = intended_path.as_str(),- "[triage::evaluator] agent turn dispatch failed"- );- return Err(classify_error(message));- }- };-- let decision = match parse_triage_decision(&response.text) {- Ok(d) => d,- Err(parse_err) => {- tracing::warn!(- error = %parse_err,- reply_chars = response.text.chars().count(),- path = intended_path.as_str(),- "[triage::evaluator] classifier reply did not parse"- );- // A parse failure means the model produced unusable- // output. Retrying the same arm with the same prompt- // won't usually help, but on the cloud arm one retry is- // cheap enough because hosted models can be- // non-deterministic across calls. If the cloud retry also- // returns malformed output, let the outer chain fall- // through to local/Deferred instead of surfacing Err to- // background callers like Composio trigger triage.- return Err(match intended_path {- TriageResolutionPath::Cloud | TriageResolutionPath::CloudAfterRetry => {- ArmError::Retryable {- retry_after_ms: None,- source: anyhow!(- "classifier reply did not parse on {} arm: {}",- intended_path.as_str(),- format_parse_error(&parse_err)- ),- }- }- TriageResolutionPath::LocalFallback => ArmError::Fatal(anyhow!(- "classifier reply did not parse on {} arm: {}",- intended_path.as_str(),- format_parse_error(&parse_err)- )),- });- }- };-- let latency_ms = started.elapsed().as_millis() as u64;- let used_local = matches!(intended_path, TriageResolutionPath::LocalFallback);- tracing::info!(- source = %envelope.source.slug(),- action = %decision.action.as_str(),- path = intended_path.as_str(),- latency_ms = latency_ms,- "[triage::evaluator] classifier decision produced"- );-- Ok(TriageRun {- decision,- used_local,- latency_ms,- resolution_path: intended_path,- })-}--/// Classify a handler-failure message string from the agent bus into-/// either a retryable (sleep + try again) or fatal (give up) error.-fn classify_error(message: String) -> ArmError {- let err = anyhow!("{message}");- if is_rate_limited(&err) {- return ArmError::Retryable {- retry_after_ms: parse_retry_after_ms(&err),- source: err,- };- }- if is_upstream_unhealthy(&err) || is_transient_string(&message) {- return ArmError::Retryable {- retry_after_ms: None,- source: err,- };- }- // Budget-exceeded is technically a 400 (not 5xx/429), so the- // generic transient checks above won't catch it — but it is a- // user-actionable upstream blocker, not a code bug, so we route- // it through `BudgetExhausted` to avoid Sentry pages.- if is_inference_budget_exceeded(&message) {- return ArmError::BudgetExhausted(err);- }- // Prompt-guard rejection (`agent::bus::enforce_prompt_input` →- // `ReviewBlocked` / `Blocked`). The guard fires *before* either- // arm contacts a model, so the verdict is identical on cloud and- // local — no point retrying. Treat as Deferred-eligible so the- // chain ends in `TriageOutcome::Deferred` rather than Fatal,- // which was paging Sentry for adversarial-email triage attempts- // (OPENHUMAN-TAURI-X regression).- if is_prompt_guard_rejection(&message) {- return ArmError::SafetyFlagged(err);- }- ArmError::Fatal(err)-}--/// Returns `true` when `message` is the verbatim string our prompt-injection-/// guard returns when it rejects a turn before dispatch.-///-/// Canonical sources:-/// - `crates/openhuman-core/src/agent/bus.rs` — `Blocked` / `ReviewBlocked` arms of the-/// `enforce_prompt_input` decision (the path the triage evaluator hits via-/// `agent.run_turn`).-/// - `crates/openhuman-core/src/agent/harness/session/runtime.rs` — same strings in the-/// tool-call loop, kept identical so this classifier covers both.-/// - `crates/openhuman-core/src/inference/local/ops.rs` — user-facing variants with the-/// `"Please rephrase clearly."` suffix; we match the leading phrase so-/// either form classifies.-///-/// Kept narrow on purpose: the guard's full output strings are private to-/// our code, so a substring match against the leading phrase will not collide-/// with anything coming back from upstream providers.-fn is_prompt_guard_rejection(message: &str) -> bool {- let lower = message.to_ascii_lowercase();- lower.contains("prompt flagged for security review")- || lower.contains("prompt blocked by security policy")-}--/// Returns `true` when `message` signals that the upstream rejected the-/// call because the user's inference budget or credit balance is empty —-/// meaning a retry would hit the same wall.-///-/// The vocabulary matches the OpenHuman backend's error copy and common-/// third-party provider phrasing. It does **not** mirror the-/// *semantics* of `web_chat/` (a different code path);-/// it is an independent, conservative allowlist evaluated inline so the-/// triage evaluator carries no cross-domain import.-///-/// Kept conservative on purpose: a false positive would silently-/// reclassify a real `Fatal` error as `BudgetExhausted`, hiding it from-/// Sentry.-fn is_inference_budget_exceeded(message: &str) -> bool {- // Normalize: lowercase, replace non-alphanumeric with spaces, then- // split into whitespace-separated tokens. This lets us do- // whole-word matching: a raw `contains("top up")` against the- // normalized text would also fire on "stop updating" (which- // contains the substring "top up" across word boundaries).- let normalized: String = message- .trim()- .to_ascii_lowercase()- .chars()- .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })- .collect();- let words: Vec<&str> = normalized.split_whitespace().collect();- const NEEDLES: &[&str] = &[- "budget exceeded",- "budget exceeds",- "top up",- "add credits",- "out of credits",- "no remaining credits",- ];- NEEDLES.iter().any(|needle| {- let needle_tokens: Vec<&str> = needle.split_whitespace().collect();- if needle_tokens.is_empty() || words.len() < needle_tokens.len() {- return false;- }- words- .windows(needle_tokens.len())- .any(|window| window == needle_tokens.as_slice())- })-}diff --git a/crates/openhuman-core/src/agent/triage/evaluator_part_02.rs b/crates/openhuman-core/src/agent/triage/evaluator_part_02.rsdeleted file mode 100644index ce67f5962f..0000000000--- a/crates/openhuman-core/src/agent/triage/evaluator_part_02.rs+++ /dev/null@@ -1,117 +0,0 @@--/// Heuristic for transient cloud failures the provider stack didn't-/// already classify — connection resets, timeouts, generic 5xx text.-/// Mirrors the conservative match shape used by `is_upstream_unhealthy`.-fn is_transient_string(msg: &str) -> bool {- let lower = msg.to_lowercase();- let hints = [- "timed out",- "timeout",- "connection",- "connect error",- "broken pipe",- "reset by peer",- "deadline exceeded",- "temporarily unavailable",- ];- if hints.iter().any(|h| lower.contains(h)) {- return true;- }- // Bare 5xx in the message body. Be careful not to match arbitrary- // numerals — only treat 5xx as transient.- for token in lower.split(|c: char| !c.is_ascii_digit()) {- if let Ok(code) = token.parse::<u16>() {- if (500..600).contains(&code) {- return true;- }- }- }- false-}--fn now_ms() -> i64 {- chrono::Utc::now().timestamp_millis()-}--fn extract_inline_prompt(def: &AgentDefinition) -> Option<String> {- match &def.system_prompt {- PromptSource::Inline(body) if !body.is_empty() => Some(body.clone()),- PromptSource::Dynamic(build) => {- use crate::agent::context::prompt::{- ConnectedIntegration, LearnedContextData, PromptContext, PromptTool, ToolCallFormat,- };- let empty_tools: Vec<PromptTool<'_>> = Vec::new();- let empty_integrations: Vec<ConnectedIntegration> = Vec::new();- let empty_visible: std::collections::HashSet<String> = std::collections::HashSet::new();- let ctx = PromptContext {- workspace_dir: std::path::Path::new("."),- model_name: "",- agent_id: &def.id,- tools: &empty_tools,- workflows: &[],- dispatcher_instructions: "",- learned: LearnedContextData::default(),- visible_tool_names: &empty_visible,- tool_call_format: ToolCallFormat::PFormat,- connected_integrations: &empty_integrations,- connected_identities_md: String::new(),- include_profile: false,- include_memory_md: false,- curated_snapshot: None,- user_identity: None,- personality_soul_md: None,- personality_memory_md: None,- personality_roster: vec![],- agents_md_global: None,- agents_md_local: None,- };- match build(&ctx) {- Ok(body) if !body.is_empty() => Some(body),- Ok(_) => None,- Err(e) => {- tracing::warn!(- agent_id = %def.id,- error = %e,- "[triage::evaluator] dynamic prompt builder failed"- );- None- }- }- }- _ => None,- }-}--fn render_user_message(envelope: &TriggerEnvelope) -> String {- let payload_string = truncate_payload(&envelope.payload, PAYLOAD_INLINE_LIMIT_BYTES);- format!(- "SOURCE: {source}\n\- DISPLAY_LABEL: {label}\n\- EXTERNAL_ID: {eid}\n\- PAYLOAD:\n{payload}",- source = envelope.source.slug(),- label = envelope.display_label,- eid = envelope.external_id,- payload = payload_string,- )-}--fn format_parse_error(err: &ParseError) -> String {- match err {- ParseError::NoJsonObject => "classifier reply had no JSON object".to_string(),- ParseError::InvalidJson(src) => format!("classifier JSON invalid: {src}"),- ParseError::MissingTarget { action } => {- format!("action `{action}` missing required target_agent/prompt")- }- }-}--fn truncate_payload(payload: &serde_json::Value, max_bytes: usize) -> String {- let pretty = serde_json::to_string_pretty(payload).unwrap_or_else(|_| payload.to_string());- if pretty.len() <= max_bytes {- return pretty;- }- let dropped = pretty.len() - max_bytes;- let end = crate::util::floor_char_boundary(&pretty, max_bytes);- format!("{}\n[...truncated {dropped} bytes]", &pretty[..end])-}diff --git a/crates/openhuman-core/src/agent/triage/evaluator_tests.rs b/crates/openhuman-core/src/agent/triage/evaluator_tests.rsindex a47587feab..7aca5b1878 100644--- a/crates/openhuman-core/src/agent/triage/evaluator_tests.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator_tests.rs@@ -60,7 +60,7 @@ fn envelope() -> TriggerEnvelope {const VALID_JSON_REPLY: &str = "{\"action\":\"acknowledge\",\"reason\":\"all good\"}";-#[path = "evaluator_tests_part_01_tests.rs"]-mod part_01_tests;-#[path = "evaluator_tests_part_02_tests.rs"]-mod part_02_tests;+#[path = "evaluator_fallback_chain_tests.rs"]+mod fallback_chain_tests;+#[path = "evaluator_deferral_tests.rs"]+mod deferral_tests;diff --git a/crates/openhuman-core/src/config/schemas/controllers/agent.rs b/crates/openhuman-core/src/config/schemas/controllers/agent.rsnew file mode 100644index 0000000000..422f78d61f--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/agent.rs@@ -0,0 +1,152 @@+//! Handlers for agent behaviour settings: autonomy, privacy, browser, sandbox, activity level, and memory sync.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;++use super::super::helpers::{deserialize_params, to_json, ActivityLevelSettingsUpdate, AgentSettingsUpdate, AutonomySettingsUpdate, BrowserSettingsUpdate, MemorySyncSettingsUpdate, PrivacyModeUpdate, SandboxSettingsUpdate, SetBrowserAllowAllParams};++pub(super) fn handle_get_autonomy_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(config_rpc::get_autonomy_settings().await?) })+}++pub(super) fn handle_update_autonomy_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<AutonomySettingsUpdate>(params)?;+ let patch = config_rpc::AutonomySettingsPatch {+ level: update.level,+ workspace_only: update.workspace_only,+ allowed_commands: update.allowed_commands,+ forbidden_paths: update.forbidden_paths,+ trusted_roots: update.trusted_roots,+ allow_tool_install: update.allow_tool_install,+ max_actions_per_hour: update+ .max_actions_per_hour+ .map(|v| u32::try_from(v).unwrap_or(u32::MAX)),+ auto_approve: update.auto_approve,+ require_task_plan_approval: update.require_task_plan_approval,+ auto_approve_all: update.auto_approve_all,+ };+ to_json(config_rpc::load_and_apply_autonomy_settings(patch).await?)+ })+}++pub(super) fn handle_get_privacy_mode(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(config_rpc::get_privacy_mode().await?) })+}++pub(super) fn handle_set_privacy_mode(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<PrivacyModeUpdate>(params)?;+ let patch = config_rpc::PrivacySettingsPatch { mode: update.mode };+ to_json(config_rpc::load_and_apply_privacy_settings(patch).await?)+ })+}++pub(super) fn handle_get_agent_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ log::debug!("[config][rpc] get_agent_settings enter");+ match config_rpc::get_agent_settings().await {+ Ok(outcome) => {+ log::debug!("[config][rpc] get_agent_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] get_agent_settings failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_update_agent_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] update_agent_settings enter");+ let update = match deserialize_params::<AgentSettingsUpdate>(params) {+ Ok(u) => u,+ Err(err) => {+ log::warn!("[config][rpc] update_agent_settings invalid params: {err}");+ return Err(err);+ }+ };+ let patch = config_rpc::AgentSettingsPatch {+ agent_timeout_secs: update.agent_timeout_secs,+ };+ match config_rpc::load_and_apply_agent_settings(patch).await {+ Ok(outcome) => {+ log::debug!("[config][rpc] update_agent_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] update_agent_settings failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_update_browser_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<BrowserSettingsUpdate>(params)?;+ let patch = config_rpc::BrowserSettingsPatch {+ enabled: update.enabled,+ backend: update.backend,+ };+ to_json(config_rpc::load_and_apply_browser_settings(patch).await?)+ })+}++pub(super) fn handle_set_browser_allow_all(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let payload = deserialize_params::<SetBrowserAllowAllParams>(params)?;+ to_json(config_rpc::set_browser_allow_all(payload.enabled)?)+ })+}++pub(super) fn handle_get_activity_level_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(config_rpc::get_activity_level_settings().await?) })+}++pub(super) fn handle_update_activity_level_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<ActivityLevelSettingsUpdate>(params)?;+ let patch = config_rpc::ActivityLevelSettingsPatch {+ level: update.level,+ };+ to_json(config_rpc::load_and_apply_activity_level_settings(patch).await?)+ })+}++pub(super) fn handle_get_memory_sync_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(config_rpc::get_memory_sync_settings().await?) })+}++pub(super) fn handle_update_memory_sync_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<MemorySyncSettingsUpdate>(params)?;+ let patch = config_rpc::MemorySyncSettingsPatch {+ sync_interval_secs: update.sync_interval_secs,+ };+ to_json(config_rpc::load_and_apply_memory_sync_settings(patch).await?)+ })+}++pub(super) fn handle_get_sandbox_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(config_rpc::get_sandbox_settings().await?) })+}++pub(super) fn handle_update_sandbox_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<SandboxSettingsUpdate>(params)?;+ let patch = config_rpc::SandboxSettingsPatch {+ backend: update.backend,+ enabled: update.enabled,+ docker_image: update.docker_image,+ docker_memory_limit_mb: update.docker_memory_limit_mb,+ docker_cpu_limit: update.docker_cpu_limit,+ env_passthrough: update.env_passthrough,+ };+ to_json(config_rpc::load_and_apply_sandbox_settings(patch).await?)+ })+}diff --git a/crates/openhuman-core/src/config/schemas/controllers/inference.rs b/crates/openhuman-core/src/config/schemas/controllers/inference.rsnew file mode 100644index 0000000000..11a4eae6b9--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/inference.rs@@ -0,0 +1,207 @@+//! Handlers for config snapshot reads and model, memory, runtime, and local-AI inference settings.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;++use super::super::helpers::{deserialize_params, to_json, LocalAiSettingsUpdate, MemorySettingsUpdate, ModelSettingsUpdate, RuntimeSettingsUpdate};++pub(super) fn handle_get_config(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::load_and_get_config_snapshot().await?) })+}++pub(super) fn handle_get_client_config(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] get_client_config enter");+ match config_rpc::load_and_get_client_config_snapshot().await {+ Ok(snapshot) => to_json(snapshot),+ Err(err) => {+ log::warn!("[config][rpc] get_client_config load failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_update_model_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<ModelSettingsUpdate>(params)?;+ let patch = config_rpc::ModelSettingsPatch {+ api_url: update.api_url,+ inference_url: update.inference_url,+ api_key: update.api_key,+ default_model: update.default_model,+ default_temperature: update.default_temperature,+ model_routes: update.model_routes.map(|routes| {+ routes+ .into_iter()+ .map(|r| crate::config::ModelRouteConfig {+ hint: r.hint,+ model: r.model,+ })+ .collect()+ }),+ cloud_providers: update+ .cloud_providers+ .map(|entries| {+ use crate::config::schema::cloud_providers::{+ generate_provider_id, is_slug_reserved, migrate_legacy_fields, AuthStyle,+ CloudProviderCreds,+ };+ let reserved_count = entries+ .iter()+ .filter(|e| {+ let t = e.slug.trim();+ !t.is_empty() && is_slug_reserved(t)+ })+ .count();+ if reserved_count > 0 {+ log::debug!(+ "[config] update_model_settings: dropping {} reserved cloud provider slug(s)",+ reserved_count+ );+ }+ entries+ .into_iter()+ // Silently drop entries whose (non-empty) slug is reserved —+ // typically the migration-seeded "openhuman" / "cloud" /+ // "pid" built-ins that the frontend echoes back on every+ // save (see `migrations::unify_ai_provider_settings`).+ // Empty slugs still fall through so the explicit+ // validation error below fires for actual frontend+ // bugs. `apply_model_settings` re-injects the existing+ // reserved entries from the stored config so they+ // aren't dropped on save.+ .filter(|e| {+ let trimmed = e.slug.trim();+ trimmed.is_empty() || !is_slug_reserved(trimmed)+ })+ .map(|e| {+ let slug = e.slug.trim().to_string();+ if slug.is_empty() {+ return Err(+ "cloud provider slug must not be empty".to_string()+ );+ }+ let auth_style = match e+ .auth_style+ .as_deref()+ .unwrap_or("bearer")+ .to_ascii_lowercase()+ .as_str()+ {+ "bearer" => AuthStyle::Bearer,+ "anthropic" => AuthStyle::Anthropic,+ "openhuman_jwt" | "openhumanjwt" => AuthStyle::OpenhumanJwt,+ "none" => AuthStyle::None,+ other => {+ return Err(format!(+ "unknown auth_style '{}'; valid: bearer, anthropic, openhuman_jwt, none",+ other+ ))+ }+ };+ let id = e+ .id+ .filter(|s| !s.trim().is_empty())+ .unwrap_or_else(|| generate_provider_id(&slug));+ let label = e+ .label+ .filter(|s| !s.trim().is_empty())+ .unwrap_or_else(|| slug.clone());+ let mut entry = CloudProviderCreds {+ id,+ slug,+ label,+ endpoint: e.endpoint,+ auth_style,+ legacy_type: e.legacy_type,+ default_model: e.default_model,+ };+ // Apply any remaining legacy-field migration.+ migrate_legacy_fields(&mut entry);+ Ok(entry)+ })+ .collect::<Result<Vec<_>, String>>()+ })+ .transpose()?,+ // The config-domain RPC doesn't carry a model-registry payload — the+ // per-model vision registry is updated via the inference-domain+ // `inference_update_model_settings` path.+ model_registry: None,+ primary_cloud: update.primary_cloud,+ chat_provider: update.chat_provider,+ reasoning_provider: update.reasoning_provider,+ agentic_provider: update.agentic_provider,+ coding_provider: update.coding_provider,+ vision_provider: update.vision_provider,+ memory_provider: update.memory_provider,+ embeddings_provider: update.embeddings_provider,+ heartbeat_provider: update.heartbeat_provider,+ learning_provider: update.learning_provider,+ subconscious_provider: update.subconscious_provider,+ };+ to_json(config_rpc::load_and_apply_model_settings(patch).await?)+ })+}++pub(super) fn handle_update_memory_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<MemorySettingsUpdate>(params)?;+ let patch = config_rpc::MemorySettingsPatch {+ backend: update.backend,+ auto_save: update.auto_save,+ embedding_provider: update.embedding_provider,+ embedding_model: update.embedding_model,+ embedding_dimensions: update.embedding_dimensions,+ memory_window: update.memory_window,+ };+ to_json(config_rpc::load_and_apply_memory_settings(patch).await?)+ })+}++pub(super) fn handle_update_runtime_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<RuntimeSettingsUpdate>(params)?;+ let patch = config_rpc::RuntimeSettingsPatch {+ kind: update.kind,+ reasoning_enabled: update.reasoning_enabled,+ };+ to_json(config_rpc::load_and_apply_runtime_settings(patch).await?)+ })+}++pub(super) fn handle_update_local_ai_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<LocalAiSettingsUpdate>(params)?;+ let base_url = match update.base_url {+ None => None,+ Some(Value::Null) => Some(None),+ Some(Value::String(value)) => Some(Some(value)),+ Some(_) => return Err("invalid params: base_url must be a string or null".to_string()),+ };+ let patch = config_rpc::LocalAiSettingsPatch {+ runtime_enabled: update.runtime_enabled,+ opt_in_confirmed: update.opt_in_confirmed,+ provider: update.provider,+ base_url,+ model_id: update.model_id,+ chat_model_id: update.chat_model_id,+ usage_embeddings: update.usage_embeddings,+ usage_heartbeat: update.usage_heartbeat,+ usage_learning_reflection: update.usage_learning_reflection,+ usage_subconscious: update.usage_subconscious,+ api_key: update.api_key,+ };+ to_json(config_rpc::load_and_apply_local_ai_settings(patch).await?)+ })+}++pub(super) fn handle_resolve_api_url(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::load_and_resolve_api_url().await?) })+}++pub(super) fn handle_get_runtime_flags(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::get_runtime_flags()) })+}diff --git a/crates/openhuman-core/src/config/schemas/controllers/integrations.rs b/crates/openhuman-core/src/config/schemas/controllers/integrations.rsnew file mode 100644index 0000000000..638a50db14--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/integrations.rs@@ -0,0 +1,102 @@+//! Handlers for third-party integration settings: web search and Composio triggers.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;++use super::super::helpers::{deserialize_params, to_json, ComposioTriggerSettingsUpdate, SearchSettingsUpdate};++pub(super) fn handle_update_search_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] update_search_settings enter");+ let update = match deserialize_params::<SearchSettingsUpdate>(params) {+ Ok(u) => u,+ Err(err) => {+ log::warn!("[config][rpc] update_search_settings invalid params: {err}");+ return Err(err);+ }+ };+ let patch = config_rpc::SearchSettingsPatch {+ engine: update.engine,+ max_results: update.max_results,+ timeout_secs: update.timeout_secs,+ parallel_api_key: update.parallel_api_key,+ brave_api_key: update.brave_api_key,+ querit_api_key: update.querit_api_key,+ exa_api_key: update.exa_api_key,+ tavily_api_key: update.tavily_api_key,+ allowed_domains: update.allowed_domains,+ allow_all: update.allow_all,+ };+ match config_rpc::load_and_apply_search_settings(patch).await {+ Ok(outcome) => {+ log::debug!("[config][rpc] update_search_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] update_search_settings failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_get_search_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ log::debug!("[config][rpc] get_search_settings enter");+ match config_rpc::get_search_settings().await {+ Ok(outcome) => {+ log::debug!("[config][rpc] get_search_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] get_search_settings failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_update_composio_trigger_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] update_composio_trigger_settings enter");+ let update = match deserialize_params::<ComposioTriggerSettingsUpdate>(params) {+ Ok(u) => u,+ Err(err) => {+ log::warn!("[config][rpc] update_composio_trigger_settings invalid params: {err}");+ return Err(err);+ }+ };+ let patch = config_rpc::ComposioTriggerSettingsPatch {+ triage_disabled: update.triage_disabled,+ triage_disabled_toolkits: update.triage_disabled_toolkits,+ };+ match config_rpc::load_and_apply_composio_trigger_settings(patch).await {+ Ok(outcome) => {+ log::debug!("[config][rpc] update_composio_trigger_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] update_composio_trigger_settings failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_get_composio_trigger_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ log::debug!("[config][rpc] get_composio_trigger_settings enter");+ match config_rpc::get_composio_trigger_settings().await {+ Ok(outcome) => {+ log::debug!("[config][rpc] get_composio_trigger_settings ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] get_composio_trigger_settings failed: {err}");+ Err(err)+ }+ }+ })+}diff --git a/crates/openhuman-core/src/config/schemas/controllers/registry.rs b/crates/openhuman-core/src/config/schemas/controllers/registry.rsnew file mode 100644index 0000000000..af935e786f--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/registry.rs@@ -0,0 +1,231 @@+//! Controller registry for the `config` namespace: schema list and handler wiring.++use crate::core::all::RegisteredController;+use crate::core::ControllerSchema;++use super::super::schema_defs::schemas;+use super::inference::{handle_get_config, handle_get_client_config, handle_update_model_settings, handle_update_memory_settings, handle_update_runtime_settings, handle_update_local_ai_settings, handle_resolve_api_url, handle_get_runtime_flags};+use super::agent::{handle_get_autonomy_settings, handle_update_autonomy_settings, handle_get_privacy_mode, handle_set_privacy_mode, handle_get_agent_settings, handle_update_agent_settings, handle_update_browser_settings, handle_set_browser_allow_all, handle_get_activity_level_settings, handle_update_activity_level_settings, handle_get_memory_sync_settings, handle_update_memory_sync_settings, handle_get_sandbox_settings, handle_update_sandbox_settings};+use super::workspace::{handle_workspace_onboarding_flag_exists, handle_workspace_onboarding_flag_set, handle_update_analytics_settings, handle_get_analytics_settings, handle_get_dashboard_settings, handle_agent_server_status, handle_reset_local_data, handle_get_data_paths, handle_get_agent_paths, handle_update_agent_paths, handle_get_onboarding_completed, handle_set_onboarding_completed};+use super::voice::{handle_get_dictation_settings, handle_update_dictation_settings, handle_get_voice_server_settings, handle_update_voice_server_settings};+use super::integrations::{handle_update_search_settings, handle_get_search_settings, handle_update_composio_trigger_settings, handle_get_composio_trigger_settings};++pub fn all_controller_schemas() -> Vec<ControllerSchema> {+ vec![+ schemas("get_config"),+ schemas("get_client_config"),+ schemas("update_model_settings"),+ schemas("update_memory_settings"),+ schemas("update_runtime_settings"),+ schemas("update_browser_settings"),+ schemas("update_local_ai_settings"),+ schemas("resolve_api_url"),+ schemas("get_runtime_flags"),+ schemas("set_browser_allow_all"),+ schemas("workspace_onboarding_flag_exists"),+ schemas("workspace_onboarding_flag_set"),+ schemas("update_analytics_settings"),+ schemas("get_analytics_settings"),+ schemas("get_dashboard_settings"),+ schemas("agent_server_status"),+ schemas("reset_local_data"),+ schemas("get_data_paths"),+ schemas("get_agent_paths"),+ schemas("update_agent_paths"),+ schemas("get_onboarding_completed"),+ schemas("set_onboarding_completed"),+ schemas("get_dictation_settings"),+ schemas("update_dictation_settings"),+ schemas("get_voice_server_settings"),+ schemas("update_voice_server_settings"),+ schemas("update_composio_trigger_settings"),+ schemas("get_composio_trigger_settings"),+ schemas("get_autonomy_settings"),+ schemas("update_autonomy_settings"),+ schemas("get_privacy_mode"),+ schemas("set_privacy_mode"),+ schemas("get_agent_settings"),+ schemas("update_agent_settings"),+ schemas("update_search_settings"),+ schemas("get_search_settings"),+ schemas("get_activity_level_settings"),+ schemas("update_activity_level_settings"),+ schemas("get_memory_sync_settings"),+ schemas("update_memory_sync_settings"),+ schemas("get_sandbox_settings"),+ schemas("update_sandbox_settings"),+ ]+}++pub fn all_registered_controllers() -> Vec<RegisteredController> {+ vec![+ RegisteredController {+ schema: schemas("get_config"),+ handler: handle_get_config,+ },+ RegisteredController {+ schema: schemas("get_client_config"),+ handler: handle_get_client_config,+ },+ RegisteredController {+ schema: schemas("update_model_settings"),+ handler: handle_update_model_settings,+ },+ RegisteredController {+ schema: schemas("update_memory_settings"),+ handler: handle_update_memory_settings,+ },+ RegisteredController {+ schema: schemas("update_runtime_settings"),+ handler: handle_update_runtime_settings,+ },+ RegisteredController {+ schema: schemas("update_browser_settings"),+ handler: handle_update_browser_settings,+ },+ RegisteredController {+ schema: schemas("update_local_ai_settings"),+ handler: handle_update_local_ai_settings,+ },+ RegisteredController {+ schema: schemas("resolve_api_url"),+ handler: handle_resolve_api_url,+ },+ RegisteredController {+ schema: schemas("get_runtime_flags"),+ handler: handle_get_runtime_flags,+ },+ RegisteredController {+ schema: schemas("set_browser_allow_all"),+ handler: handle_set_browser_allow_all,+ },+ RegisteredController {+ schema: schemas("workspace_onboarding_flag_exists"),+ handler: handle_workspace_onboarding_flag_exists,+ },+ RegisteredController {+ schema: schemas("workspace_onboarding_flag_set"),+ handler: handle_workspace_onboarding_flag_set,+ },+ RegisteredController {+ schema: schemas("update_analytics_settings"),+ handler: handle_update_analytics_settings,+ },+ RegisteredController {+ schema: schemas("get_analytics_settings"),+ handler: handle_get_analytics_settings,+ },+ RegisteredController {+ schema: schemas("get_dashboard_settings"),+ handler: handle_get_dashboard_settings,+ },+ RegisteredController {+ schema: schemas("agent_server_status"),+ handler: handle_agent_server_status,+ },+ RegisteredController {+ schema: schemas("reset_local_data"),+ handler: handle_reset_local_data,+ },+ RegisteredController {+ schema: schemas("get_data_paths"),+ handler: handle_get_data_paths,+ },+ RegisteredController {+ schema: schemas("get_agent_paths"),+ handler: handle_get_agent_paths,+ },+ RegisteredController {+ schema: schemas("update_agent_paths"),+ handler: handle_update_agent_paths,+ },+ RegisteredController {+ schema: schemas("get_onboarding_completed"),+ handler: handle_get_onboarding_completed,+ },+ RegisteredController {+ schema: schemas("set_onboarding_completed"),+ handler: handle_set_onboarding_completed,+ },+ RegisteredController {+ schema: schemas("get_dictation_settings"),+ handler: handle_get_dictation_settings,+ },+ RegisteredController {+ schema: schemas("update_dictation_settings"),+ handler: handle_update_dictation_settings,+ },+ RegisteredController {+ schema: schemas("get_voice_server_settings"),+ handler: handle_get_voice_server_settings,+ },+ RegisteredController {+ schema: schemas("update_voice_server_settings"),+ handler: handle_update_voice_server_settings,+ },+ RegisteredController {+ schema: schemas("update_composio_trigger_settings"),+ handler: handle_update_composio_trigger_settings,+ },+ RegisteredController {+ schema: schemas("get_composio_trigger_settings"),+ handler: handle_get_composio_trigger_settings,+ },+ RegisteredController {+ schema: schemas("get_autonomy_settings"),+ handler: handle_get_autonomy_settings,+ },+ RegisteredController {+ schema: schemas("update_autonomy_settings"),+ handler: handle_update_autonomy_settings,+ },+ RegisteredController {+ schema: schemas("get_privacy_mode"),+ handler: handle_get_privacy_mode,+ },+ RegisteredController {+ schema: schemas("set_privacy_mode"),+ handler: handle_set_privacy_mode,+ },+ RegisteredController {+ schema: schemas("get_agent_settings"),+ handler: handle_get_agent_settings,+ },+ RegisteredController {+ schema: schemas("update_agent_settings"),+ handler: handle_update_agent_settings,+ },+ RegisteredController {+ schema: schemas("update_search_settings"),+ handler: handle_update_search_settings,+ },+ RegisteredController {+ schema: schemas("get_search_settings"),+ handler: handle_get_search_settings,+ },+ RegisteredController {+ schema: schemas("get_activity_level_settings"),+ handler: handle_get_activity_level_settings,+ },+ RegisteredController {+ schema: schemas("update_activity_level_settings"),+ handler: handle_update_activity_level_settings,+ },+ RegisteredController {+ schema: schemas("get_memory_sync_settings"),+ handler: handle_get_memory_sync_settings,+ },+ RegisteredController {+ schema: schemas("update_memory_sync_settings"),+ handler: handle_update_memory_sync_settings,+ },+ RegisteredController {+ schema: schemas("get_sandbox_settings"),+ handler: handle_get_sandbox_settings,+ },+ RegisteredController {+ schema: schemas("update_sandbox_settings"),+ handler: handle_update_sandbox_settings,+ },+ ]+}diff --git a/crates/openhuman-core/src/config/schemas/controllers/voice.rs b/crates/openhuman-core/src/config/schemas/controllers/voice.rsnew file mode 100644index 0000000000..28f2696f45--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/voice.rs@@ -0,0 +1,67 @@+//! Handlers for voice dictation and voice-server settings.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;++use super::super::helpers::{deserialize_params, to_json, DictationSettingsUpdate, VoiceServerSettingsUpdate};++pub(super) fn handle_get_dictation_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::get_dictation_settings().await?) })+}++pub(super) fn handle_update_dictation_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<DictationSettingsUpdate>(params)?;+ let patch = config_rpc::DictationSettingsPatch {+ enabled: update.enabled,+ hotkey: update.hotkey,+ activation_mode: update.activation_mode,+ llm_refinement: update.llm_refinement,+ streaming: update.streaming,+ streaming_interval_ms: update.streaming_interval_ms,+ };+ to_json(config_rpc::load_and_apply_dictation_settings(patch).await?)+ })+}++pub(super) fn handle_get_voice_server_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::get_voice_server_settings().await?) })+}++pub(super) fn handle_update_voice_server_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<VoiceServerSettingsUpdate>(params)?;+ let patch = config_rpc::VoiceServerSettingsPatch {+ auto_start: update.auto_start,+ hotkey: update.hotkey,+ activation_mode: update.activation_mode,+ skip_cleanup: update.skip_cleanup,+ min_duration_secs: update.min_duration_secs,+ silence_threshold: update.silence_threshold,+ custom_dictionary: update.custom_dictionary,+ always_on_enabled: update.always_on_enabled,+ wake_word: update.wake_word,+ stt_engine: update.stt_engine,+ };+ let result = config_rpc::load_and_apply_voice_server_settings(patch).await?;+ // Apply the always-on toggle live (start/idle the capture loop) so the+ // Settings switch takes effect without a restart. Don't fail the RPC if+ // the reload hiccups, but DO surface it — otherwise the saved setting+ // silently wouldn't apply until the next launch.+ match config_rpc::load_config_with_timeout().await {+ Ok(config) => {+ log::info!("[config][rpc] voice settings saved; applying live always-on state");+ crate::voice::always_on::start_if_enabled(&config).await;+ }+ Err(error) => {+ log::warn!(+ "[config][rpc] voice settings saved, but live always-on apply was skipped \+ (config reload failed): {error}"+ );+ }+ }+ to_json(result)+ })+}diff --git a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs b/crates/openhuman-core/src/config/schemas/controllers/workspace.rsnew file mode 100644index 0000000000..bc0cfd1c8d--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs@@ -0,0 +1,165 @@+//! Handlers for workspace state: onboarding flags, analytics, dashboard, data and agent paths, and local-data reset.++use serde_json::{Map, Value};++use crate::config::rpc as config_rpc;+use crate::core::all::ControllerFuture;++use super::super::helpers::{deserialize_params, to_json, AgentPathsUpdate, AnalyticsSettingsUpdate, OnboardingCompletedSetParams, WorkspaceOnboardingFlagParams, WorkspaceOnboardingFlagSetParams, DEFAULT_ONBOARDING_FLAG_NAME};++pub(super) fn handle_workspace_onboarding_flag_exists(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let payload = deserialize_params::<WorkspaceOnboardingFlagParams>(params)?;+ to_json(+ config_rpc::workspace_onboarding_flag_resolve(+ payload.flag_name,+ DEFAULT_ONBOARDING_FLAG_NAME,+ )+ .await?,+ )+ })+}++pub(super) fn handle_workspace_onboarding_flag_set(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let payload = deserialize_params::<WorkspaceOnboardingFlagSetParams>(params)?;+ to_json(+ config_rpc::workspace_onboarding_flag_set(+ payload.flag_name,+ DEFAULT_ONBOARDING_FLAG_NAME,+ payload.value,+ )+ .await?,+ )+ })+}++pub(super) fn handle_update_analytics_settings(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let update = deserialize_params::<AnalyticsSettingsUpdate>(params)?;+ let patch = config_rpc::AnalyticsSettingsPatch {+ enabled: update.enabled,+ };+ to_json(config_rpc::load_and_apply_analytics_settings(patch).await?)+ })+}++pub(super) fn handle_get_analytics_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ use crate::rpc::RpcOutcome;+ let config = config_rpc::load_config_with_timeout().await?;+ let result = serde_json::json!({+ "enabled": config.observability.analytics_enabled,+ });+ to_json(RpcOutcome::new(+ result,+ vec!["analytics settings read".to_string()],+ ))+ })+}++pub(super) fn handle_get_dashboard_settings(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::get_dashboard_settings().await?) })+}++pub(super) fn handle_agent_server_status(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::agent_server_status()) })+}++pub(super) fn handle_reset_local_data(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::reset_local_data().await?) })+}++pub(super) fn handle_get_data_paths(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] get_data_paths enter");+ match resolve_data_paths(params).await {+ Ok(outcome) => {+ log::debug!("[config][rpc] get_data_paths ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] get_data_paths fail: {err}");+ Err(err)+ }+ }+ })+}++/// Resolve the data paths for `get_data_paths`, honoring an optional `user_id`+/// param. The Clear App Data flow passes the signed-in id (#4950) because it+/// removes the active-user marker *before* the reset resolves paths — without+/// the explicit id the core would fall back to the pre-login `users/local` dir+/// and leave the real user's data behind. Absent/blank → marker-based+/// resolution (the default used by the agent tool and diagnostics).+async fn resolve_data_paths(+ params: Map<String, Value>,+) -> Result<crate::rpc::RpcOutcome<Value>, String> {+ let user_id = params+ .get("user_id")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|id| !id.is_empty())+ .map(|id| id.to_string());+ log::debug!(+ "[config][rpc] get_data_paths: explicit_user_id={}",+ user_id.is_some()+ );+ match user_id.as_deref() {+ Some(id) => config_rpc::get_data_paths_for_user(id).await,+ None => config_rpc::get_data_paths().await,+ }+}++pub(super) fn handle_get_agent_paths(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async {+ log::debug!("[config][rpc] get_agent_paths enter");+ match config_rpc::get_agent_paths().await {+ Ok(outcome) => {+ log::debug!("[config][rpc] get_agent_paths ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] get_agent_paths fail: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_update_agent_paths(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ log::debug!("[config][rpc] update_agent_paths enter");+ let update = match deserialize_params::<AgentPathsUpdate>(params) {+ Ok(u) => u,+ Err(err) => {+ log::warn!("[config][rpc] update_agent_paths invalid params: {err}");+ return Err(err);+ }+ };+ let patch = config_rpc::AgentPathsPatch {+ action_dir: update.action_dir,+ };+ match config_rpc::load_and_apply_agent_paths_settings(patch).await {+ Ok(outcome) => {+ log::debug!("[config][rpc] update_agent_paths ok");+ to_json(outcome)+ }+ Err(err) => {+ log::warn!("[config][rpc] update_agent_paths failed: {err}");+ Err(err)+ }+ }+ })+}++pub(super) fn handle_get_onboarding_completed(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async { to_json(config_rpc::get_onboarding_completed().await?) })+}++pub(super) fn handle_set_onboarding_completed(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let payload = deserialize_params::<OnboardingCompletedSetParams>(params)?;+ to_json(config_rpc::set_onboarding_completed(payload.value).await?)+ })+}diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/agent.rs b/crates/openhuman-core/src/config/schemas/schema_defs/agent.rsnew file mode 100644index 0000000000..a1e809148e--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/schema_defs/agent.rs@@ -0,0 +1,198 @@+//! Schemas for agent behaviour settings: autonomy, privacy, browser, sandbox, activity level, and memory sync.++use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use super::super::helpers::{json_output, optional_bool, optional_json, optional_string};++pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+"get_autonomy_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_autonomy_settings",+ description: "Get the agent access-mode settings (autonomy level, workspace confinement, trusted roots, command allow-list, forbidden paths).",+ inputs: vec![],+ outputs: vec![json_output("autonomy", "Current [autonomy] config block.")],+ }),+"update_autonomy_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_autonomy_settings",+ description: "Update the agent access mode: autonomy level, workspace confinement, trusted-roots allow-list, command allow-list, forbidden paths, and OS-install permission. Applies live to active sessions.",+ inputs: vec![+ optional_string("level", "Autonomy level: readonly | supervised | full."),+ optional_bool("workspace_only", "Confine file/path access to the workspace directory."),+ FieldSchema {+ name: "allowed_commands",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ comment: "Replace the shell command allow-list (array of base command names).",+ required: false,+ },+ FieldSchema {+ name: "forbidden_paths",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ comment: "Replace the forbidden-paths denylist (array of path prefixes).",+ required: false,+ },+ FieldSchema {+ name: "trusted_roots",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Replace the trusted-roots allow-list: array of {path, access: read|readwrite}. Grants access outside the workspace; credential dirs (~/.ssh, ~/.gnupg, ~/.aws) stay blocked regardless.",+ required: false,+ },+ optional_bool("allow_tool_install", "Allow the agent to install OS packages via install_tool (intended for Full mode)."),+ FieldSchema {+ name: "max_actions_per_hour",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Rate limit for side-effecting actions per hour.",+ required: false,+ },+ FieldSchema {+ name: "auto_approve",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ comment: "Replace the \"Always allow\" allowlist (array of tool names the agent runs without an approval prompt). Empty array clears it.",+ required: false,+ },+ optional_bool("require_task_plan_approval", "Require approval before an agent executes a task-board plan."),+ optional_bool("auto_approve_all", "When true, auto-approve all tool calls without prompting. SubconsciousTainted and Unknown origins still denied. Hard security blocks unaffected."),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"get_privacy_mode" => Some( ControllerSchema {+ namespace: "config",+ function: "get_privacy_mode",+ description: "Get the active Privacy Mode (data-egress posture): local_only | standard | sensitive. Distinct from the autonomy access mode.",+ inputs: vec![],+ outputs: vec![json_output("mode", "Current privacy mode: local_only | standard | sensitive.")],+ }),+"set_privacy_mode" => Some( ControllerSchema {+ namespace: "config",+ function: "set_privacy_mode",+ description: "Set the Privacy Mode (data-egress posture). local_only blocks external model calls at the inference chokepoint. Applies live to active sessions without a restart.",+ inputs: vec![+ optional_string("mode", "Privacy mode: local_only | standard | sensitive."),+ ],+ outputs: vec![json_output("mode", "Updated privacy mode.")],+ }),+"get_agent_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_agent_settings",+ description: "Read agent execution settings: the action/tool wall-clock timeout, the runtime-effective value, and whether the OPENHUMAN_TOOL_TIMEOUT_SECS env var overrides it.",+ inputs: vec![],+ outputs: vec![json_output(+ "settings",+ "Agent settings: agent_timeout_secs, effective_timeout_secs, env_override, min_timeout_secs, max_timeout_secs.",+ )],+ }),+"update_agent_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_agent_settings",+ description: "Update agent execution settings. Currently the action/tool wall-clock timeout (seconds). Applies to the next tool call without a restart; the OPENHUMAN_TOOL_TIMEOUT_SECS env var still overrides it when set.",+ inputs: vec![FieldSchema {+ name: "agent_timeout_secs",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Wall-clock timeout for a single tool/action execution, in seconds (1–3600). Extend this when large local models are interrupted before finishing.",+ required: false,+ }],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"update_browser_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_browser_settings",+ description: "Update browser automation settings.",+ inputs: vec![+ optional_bool("enabled", "Enable browser integration."),+ optional_string(+ "backend",+ "Browser backend: agent_browser, playwright, rust_native, computer_use, or auto.",+ ),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"set_browser_allow_all" => Some( ControllerSchema {+ namespace: "config",+ function: "set_browser_allow_all",+ description: "Disable browser allow-all mode, or enable it only when operator opt-in is present.",+ inputs: vec![FieldSchema {+ name: "enabled",+ ty: TypeSchema::Bool,+ comment: "Whether to enable browser allow-all mode. Runtime enable is refused unless OPENHUMAN_BROWSER_ALLOW_ALL_RPC_ENABLE=1.",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "flags",+ ty: TypeSchema::Ref("RuntimeFlagsOut"),+ comment: "Updated runtime flag state.",+ required: true,+ }],+ }),+"get_activity_level_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_activity_level_settings",+ description: "Get the agent activity level (0–4) and its derived settings: sync cadence, heartbeat/subconscious toggles, token budget, estimated monthly cost.",+ inputs: vec![],+ outputs: vec![json_output("settings", "Activity level settings with cost estimates.")],+ }),+"update_activity_level_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_activity_level_settings",+ description: "Set the agent activity level. Immediately updates the scheduler gate mode and persists the change.",+ inputs: vec![optional_string("level", "Activity level: off | minimal | moderate | active | always_on (or 0–4).")],+ outputs: vec![json_output("settings", "Updated activity level settings with cost estimates.")],+ }),+"get_memory_sync_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_memory_sync_settings",+ description: "Get the global memory-sync cadence applied to all opted-in sources: stored value, resolved selected cadence, manual/default flags, the 24h default, and the preset options (4h/12h/24h).",+ inputs: vec![],+ outputs: vec![json_output("settings", "Memory sync schedule settings.")],+ }),+"update_memory_sync_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_memory_sync_settings",+ description: "Set the global memory-sync cadence. Omit/null resets to the default; 0 means Manual only (auto-sync disabled); a positive value is seconds between syncs. Takes effect on the next scheduler tick.",+ inputs: vec![FieldSchema {+ name: "sync_interval_secs",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Seconds between auto-syncs. null = default (24h); 0 = Manual only; n>0 = sync every n seconds.",+ required: false,+ }],+ outputs: vec![json_output("settings", "Updated memory sync schedule settings.")],+ }),+"get_sandbox_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_sandbox_settings",+ description: "Get sandbox execution backend settings: selected backend, Docker image/limits, env passthrough, Docker availability, and detected OS backend.",+ inputs: vec![],+ outputs: vec![json_output("settings", "Sandbox settings with status.")],+ }),+"update_sandbox_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_sandbox_settings",+ description: "Update sandbox execution backend settings: backend selection, Docker image, memory/CPU limits, and env passthrough. Applies to new agent sessions.",+ inputs: vec![+ optional_string("backend", "Sandbox backend: auto | landlock | firejail | bubblewrap | docker | none."),+ optional_bool("enabled", "Enable or disable sandbox execution."),+ optional_string("docker_image", "Docker image for sandboxed execution (e.g. alpine:3.20)."),+ FieldSchema {+ name: "docker_memory_limit_mb",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Docker container memory limit in MB.",+ required: false,+ },+ FieldSchema {+ name: "docker_cpu_limit",+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),+ comment: "Docker container CPU limit (e.g. 1.0 = one core).",+ required: false,+ },+ FieldSchema {+ name: "env_passthrough",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))),+ comment: "Environment variables to pass through into the sandbox.",+ required: false,+ },+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+ _ => None,+ }+}diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rsnew file mode 100644index 0000000000..b7cedbdaa9--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs@@ -0,0 +1,218 @@+//! Schemas for config snapshot reads and model, memory, runtime, and local-AI inference settings.++use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use super::super::helpers::{json_output, optional_bool, optional_json, optional_string};++pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+"get_config" => Some( ControllerSchema {+ namespace: "config",+ function: "get",+ description: "Read persisted config snapshot and resolved paths.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "snapshot",+ ty: TypeSchema::Json,+ comment: "Config snapshot with workspace and config paths.",+ required: true,+ }],+ }),+"get_client_config" => Some( ControllerSchema {+ namespace: "config",+ function: "get_client_config",+ description: "Read safe client-facing config fields (api_url, feature flags). No secrets.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "api_url",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Configured OpenHuman product backend URL, if any.",+ required: false,+ },+ FieldSchema {+ name: "inference_url",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Custom OpenAI-compatible LLM endpoint, if any. When set together with an api_key, inference goes direct to this URL.",+ required: false,+ },+ FieldSchema {+ name: "default_model",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Default model identifier.",+ required: false,+ },+ FieldSchema {+ name: "app_version",+ ty: TypeSchema::String,+ comment: "OpenHuman core version.",+ required: true,+ },+ FieldSchema {+ name: "api_key_set",+ ty: TypeSchema::Bool,+ comment: "True when a custom backend api_key is stored locally. The key itself is never returned over RPC.",+ required: true,+ },+ FieldSchema {+ name: "model_routes",+ ty: TypeSchema::Json,+ comment: "Persisted task-hint -> model id pairs the core router will obey. Empty when the OpenHuman built-in router is active.",+ required: true,+ },+ ],+ }),+"update_model_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_model_settings",+ description: "Update model and backend connection settings, including a custom OpenAI-compatible backend (api_url + api_key).",+ inputs: vec![+ optional_string("api_url", "OpenHuman product backend URL (auth/billing/voice). Almost always left blank; the inference URL is a separate `inference_url` field."),+ optional_string("inference_url", "Custom OpenAI-compatible LLM endpoint. When set together with `api_key`, inference goes direct to this URL instead of the OpenHuman backend. Pass an empty string to clear."),+ optional_string("api_key", "Optional API key for the configured inference endpoint. Pass an empty string to clear a previously stored key."),+ optional_string("default_model", "Default model id."),+ FieldSchema {+ name: "default_temperature",+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),+ comment: "Default model temperature.",+ required: false,+ },+ FieldSchema {+ name: "model_routes",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Optional list of {hint, model} pairs mapping task hints (reasoning, agentic, coding, summarization) to provider-specific model ids. Replaces config.model_routes wholesale; send [] to clear (e.g. when switching back to the OpenHuman built-in router).",+ required: false,+ },+ FieldSchema {+ name: "cloud_providers",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style}. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.",+ required: false,+ },+ optional_string("primary_cloud", "id of the cloud_providers entry used when a workload routes to 'cloud'. Empty string clears."),+ optional_string("chat_provider", "Provider string for direct conversational chat workloads."),+ optional_string("reasoning_provider", "Provider string for the main reasoning workload (e.g. 'cloud', 'ollama:llama3.1:8b', 'openai:gpt-4o')."),+ optional_string("agentic_provider", "Provider string for sub-agent / tool-loop workloads."),+ optional_string("coding_provider", "Provider string for code-generation workloads."),+ optional_string("vision_provider", "Provider string for the vision / multimodal workload (managed default: vision-v1)."),+ optional_string("memory_provider", "Provider string for memory-tree extract + summarise."),+ optional_string("embeddings_provider", "Provider string for embedding generation."),+ optional_string("heartbeat_provider", "Provider string for the heartbeat background-reasoning loop."),+ optional_string("learning_provider", "Provider string for learning / reflection passes."),+ optional_string("subconscious_provider", "Provider string for subconscious evaluation."),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"update_memory_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_memory_settings",+ description: "Update memory backend and embedding settings.",+ inputs: vec![+ optional_string("backend", "Memory backend identifier."),+ FieldSchema {+ name: "auto_save",+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),+ comment: "Enable auto-save.",+ required: false,+ },+ optional_string("embedding_provider", "Embedding provider identifier."),+ optional_string("embedding_model", "Embedding model identifier."),+ FieldSchema {+ name: "embedding_dimensions",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Embedding dimensions.",+ required: false,+ },+ optional_string(+ "memory_window",+ "Stepped long-term memory window preset: minimal | balanced | extended | maximum.",+ ),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"update_runtime_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_runtime_settings",+ description: "Update runtime execution strategy settings.",+ inputs: vec![+ optional_string("kind", "Runtime kind."),+ optional_bool("reasoning_enabled", "Enable reasoning mode."),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"update_local_ai_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_local_ai_settings",+ description:+ "Update the local AI runtime master switch and per-feature usage flags.",+ inputs: vec![+ optional_bool(+ "runtime_enabled",+ "Master switch — when false, no subsystem uses the selected local AI runtime.",+ ),+ optional_bool(+ "opt_in_confirmed",+ "MVP opt-in marker. Bootstrap hard-overrides to disabled when this is false, \+ regardless of `runtime_enabled`. Set in tandem with `runtime_enabled` from the \+ unified AI panel.",+ ),+ optional_string(+ "provider",+ "Local provider identifier. Supported values: ollama, lm_studio, omlx.",+ ),+ optional_json(+ "base_url",+ "Provider base URL string, or null to clear. For LM Studio this defaults to http://localhost:1234/v1.",+ ),+ optional_string(+ "api_key",+ "Bearer credential for keyed local runtimes such as OMLX. Pass an empty string to clear.",+ ),+ optional_string("model_id", "Default local chat model identifier."),+ optional_string("chat_model_id", "Local chat model identifier."),+ optional_bool(+ "usage_embeddings",+ "Use the local model for embedding generation (when runtime_enabled).",+ ),+ optional_bool(+ "usage_heartbeat",+ "Use the local model inside the heartbeat loop (when runtime_enabled).",+ ),+ optional_bool(+ "usage_learning_reflection",+ "Use the local model for learning/reflection passes (when runtime_enabled).",+ ),+ optional_bool(+ "usage_subconscious",+ "Use the local model for subconscious evaluation (when runtime_enabled).",+ ),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"resolve_api_url" => Some( ControllerSchema {+ namespace: "config",+ function: "resolve_api_url",+ description: "Resolve effective API base URL using config/env/default from core.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "api_url",+ ty: TypeSchema::String,+ comment: "Resolved backend API URL.",+ required: true,+ }],+ }),+"get_runtime_flags" => Some( ControllerSchema {+ namespace: "config",+ function: "get_runtime_flags",+ description: "Read environment-driven runtime flags.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "flags",+ ty: TypeSchema::Ref("RuntimeFlagsOut"),+ comment: "Runtime flag state.",+ required: true,+ }],+ }),+ _ => None,+ }+}diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs b/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rsnew file mode 100644index 0000000000..4191f93058--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs@@ -0,0 +1,122 @@+//! Schemas for third-party integration settings: web search and Composio triggers.++use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use super::super::helpers::{json_output, optional_bool, optional_json, optional_string};++pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+"update_search_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_search_settings",+ description: "Update search engine selection and BYO API credentials.",+ inputs: vec![+ optional_string(+ "engine",+ "Active engine: disabled | managed | parallel | brave | querit | exa | tavily.",+ ),+ FieldSchema {+ name: "max_results",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Maximum results per query (1-20).",+ required: false,+ },+ FieldSchema {+ name: "timeout_secs",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Per-request timeout in seconds (1-120).",+ required: false,+ },+ optional_string(+ "parallel_api_key",+ "Parallel API key (empty string clears the stored key).",+ ),+ optional_string(+ "brave_api_key",+ "Brave Search API key (empty string clears the stored key).",+ ),+ optional_string(+ "querit_api_key",+ "Querit API key (empty string clears the stored key).",+ ),+ optional_string(+ "exa_api_key",+ "Exa API key (empty string clears the stored key).",+ ),+ optional_string(+ "tavily_api_key",+ "Tavily API key (empty string clears the stored key).",+ ),+ FieldSchema {+ name: "allowed_domains",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Websites the assistant may open/read (web_fetch/curl). Exact hosts match their subdomains; \"*\" allows all public sites; empty blocks all web access.",+ required: false,+ },+ FieldSchema {+ name: "allow_all",+ ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),+ comment: "\"Allow all sites\" toggle. true sets the allowlist to [\"*\"]; false drops the wildcard, keeping explicit hosts.",+ required: false,+ },+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"get_search_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_search_settings",+ description:+ "Read search engine settings. API keys are surfaced as presence booleans only.",+ inputs: vec![],+ outputs: vec![json_output(+ "settings",+ "Engine, effective engine, limits, and per-provider configuration flags.",+ )],+ }),+ "update_composio_trigger_settings" => Some(ControllerSchema {+ namespace: "config",+ function: "update_composio_trigger_settings",+ description: "Update Composio trigger-triage settings. When triage is disabled the \+ local LLM is NOT invoked per trigger — events are still archived to \+ trigger history.",+ inputs: vec![+ optional_bool(+ "triage_disabled",+ "When true, skip the LLM triage turn for all Composio triggers globally.",+ ),+ FieldSchema {+ name: "triage_disabled_toolkits",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Toolkit slugs that skip LLM triage (e.g. [\"gmail\", \"slack\"]).",+ required: false,+ },+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+ "get_composio_trigger_settings" => Some(ControllerSchema {+ namespace: "config",+ function: "get_composio_trigger_settings",+ description: "Read current Composio trigger-triage settings.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "triage_disabled",+ ty: TypeSchema::Bool,+ comment: "Whether the global triage-disabled flag is set.",+ required: true,+ },+ FieldSchema {+ name: "triage_disabled_toolkits",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Toolkit slugs that skip LLM triage.",+ required: true,+ },+ ],+ }),+ _ => None,+ }+}diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/voice.rs b/crates/openhuman-core/src/config/schemas/schema_defs/voice.rsnew file mode 100644index 0000000000..869a666661--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/schema_defs/voice.rs@@ -0,0 +1,95 @@+//! Schemas for voice dictation and voice-server settings.++use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use super::super::helpers::{json_output, optional_bool, optional_json, optional_string};++pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+"get_dictation_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_dictation_settings",+ description: "Read current voice dictation settings.",+ inputs: vec![],+ outputs: vec![json_output("settings", "Dictation settings payload.")],+ }),+ "update_dictation_settings" => Some(ControllerSchema {+ namespace: "config",+ function: "update_dictation_settings",+ description: "Update voice dictation settings.",+ inputs: vec![+ optional_bool("enabled", "Enable voice dictation."),+ optional_string("hotkey", "Global hotkey string (e.g. Fn)."),+ optional_string("activation_mode", "Activation mode: toggle or push."),+ optional_bool(+ "llm_refinement",+ "Enable LLM post-processing of transcription.",+ ),+ optional_bool("streaming", "Enable WebSocket streaming transcription."),+ FieldSchema {+ name: "streaming_interval_ms",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Interval between streaming inference passes (ms).",+ required: false,+ },+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+ "get_voice_server_settings" => Some(ControllerSchema {+ namespace: "config",+ function: "get_voice_server_settings",+ description: "Read current voice server settings.",+ inputs: vec![],+ outputs: vec![json_output("settings", "Voice server settings payload.")],+ }),+ "update_voice_server_settings" => Some(ControllerSchema {+ namespace: "config",+ function: "update_voice_server_settings",+ description: "Update voice server settings.",+ inputs: vec![+ optional_bool(+ "auto_start",+ "Start the voice server automatically with the core.",+ ),+ optional_string("hotkey", "Voice server hotkey string (e.g. Fn)."),+ optional_string("activation_mode", "Activation mode: tap or push."),+ optional_bool(+ "skip_cleanup",+ "Skip LLM cleanup and keep dictation verbatim.",+ ),+ FieldSchema {+ name: "min_duration_secs",+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),+ comment: "Minimum recording duration in seconds.",+ required: false,+ },+ FieldSchema {+ name: "silence_threshold",+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),+ comment: "RMS energy threshold for silence detection.",+ required: false,+ },+ FieldSchema {+ name: "custom_dictionary",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Custom vocabulary words to bias the STT engine toward.",+ required: false,+ },+ optional_bool(+ "always_on_enabled",+ "Continuous always-on listening (no hotkey). Opt-in.",+ ),+ optional_string(+ "wake_word",+ "Always-on wake word; utterances must contain it (default 'Hey Tiny').",+ ),+ optional_string(+ "stt_engine",+ "Hosted speech-to-text engine: backend, elevenlabs, or openai.",+ ),+ ],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+ _ => None,+ }+}diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs b/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rsnew file mode 100644index 0000000000..7a73fbb7b7--- /dev/null+++ b/crates/openhuman-core/src/config/schemas/schema_defs/workspace.rs@@ -0,0 +1,172 @@+//! Schemas for workspace state: onboarding flags, analytics, dashboard, data and agent paths, and local-data reset.++use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++use super::super::helpers::{json_output, optional_bool, optional_json, optional_string};++pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+"workspace_onboarding_flag_exists" => Some( ControllerSchema {+ namespace: "config",+ function: "workspace_onboarding_flag_exists",+ description: "Check if onboarding flag file exists in workspace.",+ inputs: vec![FieldSchema {+ name: "flag_name",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Optional onboarding flag name override.",+ required: false,+ }],+ outputs: vec![FieldSchema {+ name: "exists",+ ty: TypeSchema::Bool,+ comment: "True when the flag file is present.",+ required: true,+ }],+ }),+"workspace_onboarding_flag_set" => Some( ControllerSchema {+ namespace: "config",+ function: "workspace_onboarding_flag_set",+ description: "Create or remove the onboarding flag file in workspace.",+ inputs: vec![+ FieldSchema {+ name: "flag_name",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Optional onboarding flag name override.",+ required: false,+ },+ FieldSchema {+ name: "value",+ ty: TypeSchema::Bool,+ comment: "True to create, false to remove.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "exists",+ ty: TypeSchema::Bool,+ comment: "True when the flag file is present after the operation.",+ required: true,+ }],+ }),+"update_analytics_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "update_analytics_settings",+ description: "Enable or disable anonymized analytics and error reporting.",+ inputs: vec![optional_bool(+ "enabled",+ "Enable anonymized analytics and crash reports.",+ )],+ outputs: vec![json_output("snapshot", "Updated config snapshot.")],+ }),+"get_analytics_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_analytics_settings",+ description: "Read current analytics settings.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "enabled",+ ty: TypeSchema::Bool,+ comment: "Whether anonymized analytics is enabled.",+ required: true,+ }],+ }),+"get_dashboard_settings" => Some( ControllerSchema {+ namespace: "config",+ function: "get_dashboard_settings",+ description: "Read dashboard settings, including the local architecture diagram viewer.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "dashboard",+ ty: TypeSchema::Json,+ comment: "Current [dashboard] config block.",+ required: true,+ }],+ }),+"agent_server_status" => Some( ControllerSchema {+ namespace: "config",+ function: "agent_server_status",+ description: "Return agent server runtime URL and status.",+ inputs: vec![],+ outputs: vec![json_output("status", "Agent server status payload.")],+ }),+"reset_local_data" => Some( ControllerSchema {+ namespace: "config",+ function: "reset_local_data",+ description:+ "Delete local OpenHuman data for the active config/workspace so the next restart boots clean.",+ inputs: vec![],+ outputs: vec![json_output("result", "Reset result with removed paths.")],+ }),+"get_data_paths" => Some( ControllerSchema {+ namespace: "config",+ function: "get_data_paths",+ description:+ "Resolve the OpenHuman data directories (current workspace, default ~/.openhuman, active workspace marker) that reset_local_data would remove. Read-only — performs no filesystem changes.",+ inputs: vec![optional_string(+ "user_id",+ "Resolve paths for this specific user id (users/<id>) instead of the active-user marker. Clear App Data passes this because it signs the user out — removing the marker — before deleting the data.",+ )],+ outputs: vec![json_output(+ "paths",+ "Resolved data paths: current_openhuman_dir, default_openhuman_dir, active_workspace_marker_path.",+ )],+ }),+"get_agent_paths" => Some( ControllerSchema {+ namespace: "config",+ function: "get_agent_paths",+ description:+ "Resolve the agent's filesystem roots (action_dir, workspace_dir, projects_dir) so the UI can render live values instead of hard-coded strings. Read-only. Also returns `action_dir_env_override: bool` so the UI knows when OPENHUMAN_ACTION_DIR is forcing the value (Settings → action_dir editing disabled in that case).",+ inputs: vec![],+ outputs: vec![json_output(+ "paths",+ "Resolved agent paths: action_dir (acting-tool CWD), workspace_dir (internal state, agent-blocked), projects_dir (default projects home), action_dir_source (env | override | default).",+ )],+ }),+"update_agent_paths" => Some( ControllerSchema {+ namespace: "config",+ function: "update_agent_paths",+ description:+ "Update the agent's editable filesystem roots. Currently only action_dir (the acting-tool sandbox). The path must be absolute; a missing directory is auto-created; it cannot equal the internal workspace_dir. An empty string clears the override and reverts to the default. Applies to new sessions immediately (live policy hot-swap), no restart. OPENHUMAN_ACTION_DIR still overrides at runtime when set.",+ inputs: vec![FieldSchema {+ name: "action_dir",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "New absolute action sandbox path. Empty string clears the override (revert to default). Omit to leave unchanged.",+ required: false,+ }],+ outputs: vec![json_output(+ "paths",+ "Updated agent paths (same shape as get_agent_paths): action_dir, workspace_dir, projects_dir, action_dir_source.",+ )],+ }),+"get_onboarding_completed" => Some( ControllerSchema {+ namespace: "config",+ function: "get_onboarding_completed",+ description: "Read whether the user has completed the onboarding flow.",+ inputs: vec![],+ outputs: vec![FieldSchema {+ name: "completed",+ ty: TypeSchema::Bool,+ comment: "True when onboarding has been completed.",+ required: true,+ }],+ }),+ "set_onboarding_completed" => Some(ControllerSchema {+ namespace: "config",+ function: "set_onboarding_completed",+ description: "Mark the onboarding flow as completed or reset it.",+ inputs: vec![FieldSchema {+ name: "value",+ ty: TypeSchema::Bool,+ comment: "True to mark completed, false to reset.",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "completed",+ ty: TypeSchema::Bool,+ comment: "Updated onboarding completed state.",+ required: true,+ }],+ }),+ _ => None,+ }+}