The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge upstream/main into feat/7032-isolated-agents
oxoxDev68167133e2d1
diff --cc crates/openhuman-core/src/agent/session_host/builder/factory.rsindex ed0ba917b6,04ab0d5abf..5e9446f662--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@@ -437,8 -428,10 +428,10 @@@ impl OpenHumanSessionHostOption<std::collections::HashSet<String>>,) = match (target_def,- crate::agent::harness::definition::AgentDefinitionRegistry::global(),+ crate::agent::harness::definition::AgentDefinitionRegistry::current(),) {+ // Host-only: no delegation; the host's names join an empty belt.+ _ if host_only => (Vec::new(), Some(super::host_only::empty_belt())),(Some(def), Some(reg)) => {let synthed = if should_synthesize_delegation_tools(def) {tools::orchestrator_tools::collect_orchestrator_tools(@@@ -711,8 -706,8 +706,8 @@@// itself MUST be `None` to avoid recursive self-summarization).let payload_summarizer: Option<std::sync::Arc<dyn crate::agent::tinyagents::payload_summarizer::PayloadSummarizer>,- > = if super::summarizes_tool_output(agent_id, config) {+ > = if !host_only && super::summarizes_tool_output(agent_id, config) {- match crate::agent::harness::definition::AgentDefinitionRegistry::global() {+ match crate::agent::harness::definition::AgentDefinitionRegistry::current() {Some(reg) => match reg.get("summarizer") {Some(summarizer_def) => {log::info!(diff --cc crates/openhuman-core/src/core/runtime/agent_scope.rsindex 683f399b22,0000000000..4f1e1a934fmode 100644,000000..100644--- a/crates/openhuman-core/src/core/runtime/agent_scope.rs+++ b/crates/openhuman-core/src/core/runtime/agent_scope.rs@@@ -1,186 -1,0 +1,175 @@@+//! Per-agent state owned by a [`CoreContext`].+//!+//! An embedded agent runs every turn under its own derived context+//! ([`CoreContext::derive_with`]). Core state that must not be shared between+//! agents hangs off that context instead of a process static:+//!+//! - [`AgentScopedState`]: a lazily populated, type-keyed slot map. Each+//! derived agent context owns one; the booted default context owns its own,+//! so the app and CLI keep a single instance as before.+//! - [`AgentContextRegistry`]: the live agent contexts by agent id, so work+//! that starts outside a turn (cron) can run under the agent that owns it.+//! - [`agent_scope_dir`]: where an agent's workspace-scoped stores live.++use std::any::{Any, TypeId};+use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock, Weak};++use super::CoreContext;++/// Type-keyed state slots owned by one context.+///+/// A slot is created on first use with `T::default()` and lives as long as+/// the context that owns it. Two contexts never share a slot.+#[derive(Default)]+pub struct AgentScopedState {+ slots: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,+}++impl AgentScopedState {+ /// The slot of type `T`, created on first use.+ pub fn slot<T: Default + Send + Sync + 'static>(&self) -> Arc<T> {+ let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);+ let entry = slots+ .entry(TypeId::of::<T>())+ .or_insert_with(|| Arc::new(T::default()) as Arc<dyn Any + Send + Sync>);+ Arc::clone(entry)+ .downcast::<T>()+ .unwrap_or_else(|_| unreachable!("a slot is keyed by its own TypeId"))+ }++ /// Number of slots created so far.+ pub fn len(&self) -> usize {+ self.slots+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .len()+ }++ /// Whether no slot has been created yet.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// Drops every slot.+ pub fn clear(&self) {+ self.slots+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .clear();+ }+}++impl std::fmt::Debug for AgentScopedState {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("AgentScopedState")+ .field("slots", &self.len())+ .finish()+ }+}++/// Slots used when no context exists at all.+static UNSCOPED: LazyLock<AgentScopedState> = LazyLock::new(AgentScopedState::default);++/// The ambient context's slot of type `T`, or the unscoped one when no+/// context exists.+pub fn current_slot<T: Default + Send + Sync + 'static>() -> Arc<T> {+ match CoreContext::current() {+ Some(ctx) => ctx.agent_state().slot::<T>(),+ None => UNSCOPED.slot::<T>(),+ }+}++static AGENT_CONTEXTS: LazyLock<RwLock<HashMap<String, Weak<CoreContext>>>> =+ LazyLock::new(|| RwLock::new(HashMap::new()));++/// The process's live agent contexts, by agent id.+///+/// Holds weak references: registering a context does not keep it alive, and a+/// dropped agent's entry resolves to `None` even before it is deregistered.+pub struct AgentContextRegistry;++impl AgentContextRegistry {+ /// Records `ctx` as the context of `agent_id`, replacing any dead entry.+ pub fn register(agent_id: &str, ctx: &Arc<CoreContext>) {+ let mut map = AGENT_CONTEXTS+ .write()+ .unwrap_or_else(PoisonError::into_inner);+ map.retain(|_, weak| weak.strong_count() > 0);+ map.insert(agent_id.to_string(), Arc::downgrade(ctx));+ log::debug!(+ "[core-context] agent context registered agent={agent_id} live={}",+ map.len()+ );+ }++ /// Removes `agent_id`'s entry when it still points at `ctx`.+ pub fn deregister(agent_id: &str, ctx: &Arc<CoreContext>) -> bool {+ let mut map = AGENT_CONTEXTS+ .write()+ .unwrap_or_else(PoisonError::into_inner);+ let owned = map+ .get(agent_id)+ .is_some_and(|weak| std::ptr::eq(weak.as_ptr(), Arc::as_ptr(ctx)));+ if owned {+ map.remove(agent_id);+ log::debug!("[core-context] agent context deregistered agent={agent_id}");+ }+ owned+ }++ /// The live context of `agent_id`, if that agent is still alive.+ pub fn get(agent_id: &str) -> Option<Arc<CoreContext>> {+ AGENT_CONTEXTS+ .read()+ .unwrap_or_else(PoisonError::into_inner)+ .get(agent_id)+ .and_then(Weak::upgrade)+ }++ /// Every live agent context, sorted by agent id.+ pub fn live() -> Vec<(String, Arc<CoreContext>)> {+ let mut live: Vec<(String, Arc<CoreContext>)> = AGENT_CONTEXTS+ .read()+ .unwrap_or_else(PoisonError::into_inner)+ .iter()+ .filter_map(|(id, weak)| weak.upgrade().map(|ctx| (id.clone(), ctx)))+ .collect();+ live.sort_by(|a, b| a.0.cmp(&b.0));+ live+ }+}++/// The directory an agent's workspace-scoped stores live under:+/// `<workspace>/agents/<id>` under a context derived for an agent, else the+/// workspace itself.+pub fn agent_scope_dir(config: &crate::config::Config) -> PathBuf {+ match CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned)) {+ Some(agent_id) => config.workspace_dir.join("agents").join(agent_id),+ None => config.workspace_dir.clone(),+ }+}+- /// `tokio::spawn` carrying the ambient [`CoreContext`] and turn origin onto- /// the new task. A bare `tokio::spawn` runs its future under the process- /// default context, so an agent's work would read the runtime's policy.- pub fn spawn_scoped<F>(fut: F) -> tokio::task::JoinHandle<F::Output>- where- F: std::future::Future + Send + 'static,- F::Output: Send + 'static,- {- crate::agent::turn_origin::spawn(fut)- }-+/// The agent id of the ambient context, when it was derived for one.+pub fn current_agent_id() -> Option<String> {+ CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned))+}++/// A context derived from `parent` for `agent_id`, for tests that need two+/// agents side by side.+#[cfg(test)]+pub(crate) fn test_agent_context(parent: &Arc<CoreContext>, agent_id: &str) -> Arc<CoreContext> {+ parent.derive_with(+ super::ContextOverlay::new(+ crate::config::Config::default(),+ super::DomainSet::kernel(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .session_agent(agent_id),+ )+}++#[cfg(test)]+#[path = "agent_scope_tests.rs"]+mod tests;diff --cc crates/openhuman-core/src/core/runtime/agent_scope_tests.rsindex 018abe6672,0000000000..97359b4016mode 100644,000000..100644--- a/crates/openhuman-core/src/core/runtime/agent_scope_tests.rs+++ b/crates/openhuman-core/src/core/runtime/agent_scope_tests.rs@@@ -1,183 -1,0 +1,183 @@@+use super::*;- use crate::core::runtime::{ContextOverlay, DomainSet};++use crate::core::runtime::{spawn_scoped, ContextOverlay, DomainSet};+use crate::security::{AutonomyLevel, SecurityPolicy};+use crate::tools::toolpacks::ToolGroups;++#[derive(Default)]+struct Counter(Mutex<u32>);++fn root(dir: &str) -> Arc<CoreContext> {+ CoreContext::for_test(DomainSet::full(), Some(PathBuf::from(dir)))+}++fn overlay(workspace: &str) -> ContextOverlay {+ let mut config = crate::config::Config::default();+ config.workspace_dir = PathBuf::from(workspace);+ ContextOverlay::new(config, DomainSet::kernel(), ToolGroups::none())+}++fn agent(parent: &Arc<CoreContext>, id: &str) -> Arc<CoreContext> {+ parent.derive_with(overlay("/tmp/agent-scope-ws").session_agent(id))+}++fn bump(ctx: &CoreContext) -> u32 {+ let counter = ctx.agent_state().slot::<Counter>();+ let mut value = counter.0.lock().unwrap();+ *value += 1;+ *value+}++#[test]+fn every_agent_context_owns_its_slots() {+ let parent = root("/tmp/agent-scope-root");+ let alpha = agent(&parent, "alpha");+ let beta = agent(&parent, "beta");++ assert_eq!(bump(&alpha), 1);+ assert_eq!(bump(&alpha), 2);+ assert_eq!(bump(&beta), 1, "beta must not see alpha's slot");+ assert_eq!(bump(&parent), 1, "the root context keeps its own slot");+ assert_eq!(alpha.agent_state().len(), 1);+}++#[test]+fn contexts_derived_without_an_agent_share_the_parent_slots() {+ let parent = root("/tmp/agent-scope-shared");+ let alpha = agent(&parent, "alpha");+ let turn = alpha.derive_with(overlay("/tmp/agent-scope-ws"));++ assert_eq!(bump(&alpha), 1);+ assert_eq!(bump(&turn), 2, "a turn context keeps its agent's slots");+ assert_eq!(turn.session_agent(), Some("alpha"));+}++#[test]+fn clear_drops_every_slot() {+ let state = AgentScopedState::default();+ assert!(state.is_empty());+ *state.slot::<Counter>().0.lock().unwrap() = 7;+ state.clear();+ assert!(state.is_empty());+ assert_eq!(*state.slot::<Counter>().0.lock().unwrap(), 0);+}++#[test]+fn derive_with_carries_policy_catalogue_and_approval_flag() {+ let parent = root("/tmp/agent-scope-policy");+ let policy = Arc::new(SecurityPolicy {+ autonomy: AutonomyLevel::ReadOnly,+ ..SecurityPolicy::default()+ });+ let definitions = Arc::new(crate::agent::harness::AgentDefinitionRegistry::default());+ let mut spec = overlay("/tmp/agent-scope-ws")+ .session_agent("alpha")+ .agent_policy(Arc::clone(&policy))+ .definitions(Arc::clone(&definitions));+ spec.approvals_disabled = true;+ let alpha = parent.derive_with(spec);+ let turn = alpha.derive_with(overlay("/tmp/agent-scope-ws"));++ for ctx in [&alpha, &turn] {+ assert!(Arc::ptr_eq(&ctx.agent_policy().unwrap(), &policy));+ assert!(Arc::ptr_eq(&ctx.definitions().unwrap(), &definitions));+ assert!(ctx.approvals_disabled());+ }+ assert!(parent.agent_policy().is_none());+ assert!(parent.definitions().is_none());+ assert!(!parent.approvals_disabled());+}++#[test]+fn registry_resolves_live_agents_only() {+ let parent = root("/tmp/agent-scope-registry");+ let alpha = agent(&parent, "registry-alpha");+ let beta = agent(&parent, "registry-beta");+ AgentContextRegistry::register("registry-alpha", &alpha);+ AgentContextRegistry::register("registry-beta", &beta);++ assert!(Arc::ptr_eq(+ &AgentContextRegistry::get("registry-alpha").unwrap(),+ &alpha+ ));+ let live: Vec<String> = AgentContextRegistry::live()+ .into_iter()+ .map(|(id, _)| id)+ .filter(|id| id.starts_with("registry-"))+ .collect();+ assert_eq!(live, ["registry-alpha", "registry-beta"]);++ drop(beta);+ assert!(AgentContextRegistry::get("registry-beta").is_none());++ let impostor = agent(&parent, "registry-alpha");+ assert!(!AgentContextRegistry::deregister(+ "registry-alpha",+ &impostor+ ));+ assert!(AgentContextRegistry::get("registry-alpha").is_some());+ assert!(AgentContextRegistry::deregister("registry-alpha", &alpha));+ assert!(AgentContextRegistry::get("registry-alpha").is_none());+}++#[tokio::test]+async fn scope_dir_and_agent_id_follow_the_ambient_context() {+ let mut config = crate::config::Config::default();+ config.workspace_dir = PathBuf::from("/tmp/agent-scope-dir");+ let parent = root("/tmp/agent-scope-dir");+ let alpha = agent(&parent, "alpha");++ let (dir, id) = CoreContext::scope(alpha, async {+ (agent_scope_dir(&config), current_agent_id())+ })+ .await;+ assert_eq!(dir, PathBuf::from("/tmp/agent-scope-dir/agents/alpha"));+ assert_eq!(id.as_deref(), Some("alpha"));++ let (dir, id) = CoreContext::scope(parent, async {+ (agent_scope_dir(&config), current_agent_id())+ })+ .await;+ assert_eq!(dir, PathBuf::from("/tmp/agent-scope-dir"));+ assert!(id.is_none());+}++#[tokio::test]+async fn spawn_scoped_keeps_the_agent_context_and_tokio_spawn_does_not() {+ let parent = root("/tmp/agent-scope-spawn");+ let policy = Arc::new(SecurityPolicy {+ autonomy: AutonomyLevel::ReadOnly,+ ..SecurityPolicy::default()+ });+ let alpha = parent.derive_with(+ overlay("/tmp/agent-scope-ws")+ .session_agent("alpha")+ .agent_policy(policy),+ );++ let (scoped, bare) = CoreContext::scope(alpha, async {+ let scoped = spawn_scoped(async {+ (+ current_agent_id(),+ CoreContext::current_agent_policy().map(|p| p.autonomy),+ )+ })+ .await+ .unwrap();+ let bare = tokio::spawn(async { CoreContext::scoped().is_some() })+ .await+ .unwrap();+ (scoped, bare)+ })+ .await;++ assert_eq!(scoped.0.as_deref(), Some("alpha"));+ assert_eq!(scoped.1, Some(AutonomyLevel::ReadOnly));+ assert!(!bare, "a bare tokio::spawn loses the task-local context");+}++#[test]+fn current_slot_without_a_context_uses_the_unscoped_state() {+ let first = current_slot::<Counter>();+ let second = current_slot::<Counter>();+ assert!(Arc::ptr_eq(&first, &second));+}diff --cc crates/openhuman-core/src/core/runtime/context_agent.rsindex 3b9b996af6,0000000000..c166eaace9mode 100644,000000..100644--- a/crates/openhuman-core/src/core/runtime/context_agent.rs+++ b/crates/openhuman-core/src/core/runtime/context_agent.rs@@@ -1,75 -1,0 +1,69 @@@+//! What a context derived for one agent owns: its policy, approval switch,+//! sub-agent catalogue and state slots.++use super::*;++#[derive(Clone, Default)]+pub(super) struct AgentParts {+ /// `None` for booted contexts, which read the process live policy.+ policy: Option<Arc<crate::security::SecurityPolicy>>,+ approvals_disabled: bool,+ /// `None` resolves through the process registry.+ definitions: Option<Arc<crate::agent::harness::definition::AgentDefinitionRegistry>>,+ /// Shared by every turn context derived from the same agent context.+ state: Arc<super::super::agent_scope::AgentScopedState>,+}++impl AgentParts {+ /// The parts of a context derived from one owning `self` with `overlay`.+ /// An overlay that names an agent gets state slots of its own.+ pub(super) fn derive(&self, overlay: &mut ContextOverlay) -> Self {+ Self {+ policy: overlay.agent_policy.take().or_else(|| self.policy.clone()),+ approvals_disabled: overlay.approvals_disabled || self.approvals_disabled,+ definitions: overlay+ .definitions+ .take()+ .or_else(|| self.definitions.clone()),+ state: if overlay.session_agent.is_some() {+ Default::default()+ } else {+ Arc::clone(&self.state)+ },+ }+ }+}++impl CoreContext {+ /// The security policy of the agent this context was derived for.+ pub fn agent_policy(&self) -> Option<Arc<crate::security::SecurityPolicy>> {+ self.agent.policy.clone()+ }++ /// [`agent_policy`](Self::agent_policy) of the ambient context.+ pub fn current_agent_policy() -> Option<Arc<crate::security::SecurityPolicy>> {+ Self::current().and_then(|ctx| ctx.agent.policy.clone())+ }++ /// Whether the interactive approval gate is off for this context's agent.+ pub fn approvals_disabled(&self) -> bool {+ self.agent.approvals_disabled+ }++ /// [`approvals_disabled`](Self::approvals_disabled) of the ambient context.+ pub fn current_approvals_disabled() -> bool {+ Self::current().is_some_and(|ctx| ctx.agent.approvals_disabled)+ }++ /// The sub-agent catalogue of the agent this context was derived for.+ pub fn definitions(+ &self,+ ) -> Option<Arc<crate::agent::harness::definition::AgentDefinitionRegistry>> {+ self.agent.definitions.clone()+ }++ /// The state slots this context owns.+ pub fn agent_state(&self) -> &super::super::agent_scope::AgentScopedState {+ &self.agent.state+ }-- /// The task-local context, without falling back to the process default.- /// `None` outside any [`scope`](Self::scope).- pub fn scoped() -> Option<Arc<CoreContext>> {- CURRENT_CONTEXT.try_with(Arc::clone).ok()- }+}diff --cc crates/openhuman-core/src/core/runtime/mod.rsindex fa82338137,b9d55dfc7a..992f7df98a--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@@ -43,15 -43,19 +43,21 @@@ pub const AGENT_WORKER_STACK_BYTES: usi/// `.thread_stack_size(AGENT_WORKER_STACK_BYTES)` on every such runtime.pub const MAX_BLOCKING_THREADS: usize = 64;+pub mod agent_scope;+ pub mod boot_guard;mod bootstrap;pub mod builder;pub mod context;+ pub mod domain_set;+ pub mod mode;+ pub mod saas;pub mod services;+ pub mod spawn;pub(crate) mod subscribers;- pub use agent_scope::{- agent_scope_dir, current_slot, spawn_scoped, AgentContextRegistry, AgentScopedState,- };++pub use agent_scope::{agent_scope_dir, current_slot, AgentContextRegistry, AgentScopedState};pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};pub use context::{ContextOverlay, CoreContext};+ pub use mode::{current_mode, is_saas, Mode};+ pub use saas::SaasConfig;+ pub use spawn::{spawn_blocking_scoped, spawn_scoped};diff --cc crates/openhuman-core/src/memory/tools.rsindex 2bcd837163,6e8dddc280..f742d798ad--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@@ -17,8 -17,9 +17,9 @@@//! everything under its root, never another root's (another tenant's or//! team's). A `reach` in the model's filter is overwritten.+ use crate::tools::schema_cache::static_schema;use std::collections::HashMap;-use std::sync::{Arc, LazyLock, Mutex};+use std::sync::{Arc, Mutex};use async_trait::async_trait;use serde_json::{json, Value};@@@ -388,6 -354,6 +359,10 @@@ impl Tool for MemoryTool#[path = "tools_tests.rs"]mod tests;+#[cfg(test)]+#[path = "tools_agent_tests.rs"]+mod agent_tests;+++ #[cfg(test)]+ #[path = "tools_schema_tests.rs"]+ mod schema_tests;diff --cc crates/openhuman-core/src/security/approval/gate.rsindex 7274bf991c,d6abbb42b4..5ce2fc4b04--- a/crates/openhuman-core/src/security/approval/gate.rs+++ b/crates/openhuman-core/src/security/approval/gate.rs@@@ -264,7 -245,10 +264,10 @@@ pub struct ApprovalGatestruct WaiterGuard<'a> {gate: &'a ApprovalGate,request_id: String,- thread_id: Option<String>,+ thread_key: Option<String>,+ /// Storage scope of the parking call, kept for `Drop`: the acting agent's+ /// task-local is gone by then.+ docs: Result<Option<super::store_documents::Docs>, String>,armed: bool,}@@@ -292,11 -276,16 +295,16 @@@ impl Drop for WaiterGuard<'_>// an unconditional `remove` would delete the *new* request's routing, so// the next typed yes/no would fall through as a fresh chat turn instead// of resolving the live gate (#4774).- if let Some(thread_id) = &self.thread_id {+ if let Some(thread_key) = &self.thread_key {self.gate- .clear_thread_route_if_owned(thread_id, &self.request_id);+ .clear_thread_route_if_owned(thread_key, &self.request_id);}- let decided = store::decide(&self.gate.config, &self.request_id, ApprovalDecision::Deny);+ let decided = store::decide_captured(+ &self.gate.config,+ &self.docs,+ &self.request_id,+ ApprovalDecision::Deny,+ );if let Ok(Some(row)) = decided {let route = self.gate.take_request_route(&self.request_id);BUS.publish(DomainEvent::ApprovalDecided {diff --cc crates/openhuman-core/src/security/approval/gate_intercept.rsindex b7f35dfb40,6c9b55b9a7..ab36f64669--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@@ -586,7 -590,8 +613,8 @@@ impl ApprovalGatelet mut waiter_guard = WaiterGuard {gate: self,request_id: request_id.clone(),- thread_id: chat_thread_id.clone(),+ thread_key: thread_key.clone(),+ docs: store::capture_docs(),armed: true,};diff --cc crates/openhuman-core/src/security/approval/store.rsindex feb2c17575,e952d5f6bb..81e467a169--- a/crates/openhuman-core/src/security/approval/store.rs+++ b/crates/openhuman-core/src/security/approval/store.rs@@@ -195,19 -192,10 +202,14 @@@ fn migrate_session_id_scrub(conn: &ConnOk(())}- /// Open (and migrate) the approval DB, then call `f` with a live- /// connection. Mirrors `notifications/store.rs::with_connection`.+fn db_path(config: &Config) -> std::path::PathBuf {+ config.workspace_dir.join("approval").join("approval.db")+}+- /// Whether the approval store has been created for `config`'s workspace.- pub fn exists(config: &Config) -> bool {- db_path(config).is_file()- }-+ /// Open (and migrate) the approval DB, then call `f` with a live+ /// connection. Mirrors `notifications/store.rs::with_connection`.fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {- let db_path = config.workspace_dir.join("approval").join("approval.db");+ let db_path = db_path(config);tracing::trace!(path = %db_path.display(),@@@ -613,10 -625,8 +640,9 @@@ fn publish_expired(expired: &[PendingApclient_id: None,tool_call_id: row.tool_call_id.clone(),resolution: Some("expired".to_string()),+ agent_id: row.agent_id.clone(),});}- Ok(about_to_expire)}fn row_to_audit_entry(row: &rusqlite::Row<'_>) -> rusqlite::Result<ApprovalAuditEntry> {@@@ -712,6 -720,6 +738,10 @@@ fn parse_rfc3339(input: &str) -> DateTi.unwrap_or_else(|_| Utc::now())}++#[path = "store_agent.rs"]++mod agent_rows;++pub use agent_rows::{exists, list_pending_for_agent, pending_agent};++#[cfg(test)]#[path = "store_tests.rs"]mod tests;diff --cc crates/openhuman-core/src/security/approval/store_agent.rsindex 0000000000,0000000000..89a9923ff6new file mode 100644--- /dev/null+++ b/crates/openhuman-core/src/security/approval/store_agent.rs@@@ -1,0 -1,0 +1,55 @@@++//! Approval rows by the embedded agent that parked them, and whether the++//! store exists to hold any.++++use anyhow::{Context, Result};++use rusqlite::params;++++use super::{Config, PendingApproval};++++/// Whether the approval store has been created for `config`'s workspace.++/// A configured document store always exists.++pub fn exists(config: &Config) -> bool {++ matches!(super::super::store_documents::current(), Ok(Some(_)))++ || super::db_path(config).is_file()++}++++/// [`list_pending`](super::list_pending) narrowed to the rows of `agent` (see++/// [`PendingApproval::belongs_to`]).++pub fn list_pending_for_agent(++ config: &Config,++ agent: Option<&str>,++) -> Result<Vec<PendingApproval>> {++ Ok(super::list_pending(config)?++ .into_iter()++ .filter(|row| row.belongs_to(agent))++ .collect())++}++++/// The agent that parked the still-undecided `request_id`: `Ok(None)` when no++/// such row exists, `Ok(Some(None))` for a row the process parked itself.++pub fn pending_agent(config: &Config, request_id: &str) -> Result<Option<Option<String>>> {++ if let Some(docs) = super::super::store_documents::current()? {++ return docs.pending_agent(request_id);++ }++ super::with_connection(config, |conn| {++ let mut stmt = conn++ .prepare(++ "SELECT agent_id FROM pending_approvals++ WHERE request_id = ?1 AND decided_at IS NULL",++ )++ .context("[approval::store] prepare pending_agent")?;++ let mut rows = stmt++ .query(params![request_id])++ .context("[approval::store] query pending_agent")?;++ match rows++ .next()++ .context("[approval::store] pending_agent next")?++ {++ Some(row) => Ok(Some(++ row.get::<_, Option<String>>(0)++ .context("[approval::store] pending_agent decode")?,++ )),++ None => Ok(None),++ }++ })++}diff --cc crates/openhuman-core/src/security/approval/store_documents.rsindex 0000000000,a5a2e2b7fa..0f423d9f0cmode 000000,100644..100644--- a/crates/openhuman-core/src/security/approval/store_documents.rs+++ b/crates/openhuman-core/src/security/approval/store_documents.rs@@@ -1,0 -1,489 +1,503 @@@+ //! The approval store on the `tinystoragedrivers` document port.+ //!+ //! Used instead of `approval/approval.db` when the host configured a storage+ //! backend ([`crate::storage`]); the public functions in `store.rs` pick it+ //! per call. Records live under the current call's storage scope (the acting+ //! agent, `local` on a single-user host), so in a multi-tenant process one+ //! user's approvals are invisible to another's.+ //!+ //! # Layout+ //!+ //! | Collection | Document id | Holds |+ //! | --- | --- | --- |+ //! | `approvals` | `request_id` | one approval request and its audit trail |+ //! | `approval_flow_trust` | `(flow_id, tool_name)` | one "approve always for this flow" grant |+ //!+ //! The SQL guards become preconditions: a request is inserted only if absent,+ //! and deciding, expiring and recording execution are compare-and-swap on the+ //! document's version, each applied only while the row is still in the state+ //! the SQL `WHERE` clause required (`decided_at IS NULL`, and so on). Two+ //! processes sharing one database therefore decide a request at most once.+ //! `args_redacted` and `source_context` are stored as JSON strings, so a+ //! MongoDB-backed port never meets an arbitrary key.++ use std::sync::Arc;++ use anyhow::{anyhow, Context, Result};+ use chrono::{DateTime, Utc};+ use serde_json::{json, Value};++ use crate::storage::{+ block_on, current_scoped, DocumentStore, DocumentStoreExt, ScopedStorage, StorageError,+ };+ use tinystoragedrivers::{+ CollectionSpec, ErrorKind, Filter, IndexSpec, Precondition, Query, Sort, Versioned,+ };++ use super::types::{+ ApprovalAuditEntry, ApprovalDecision, ApprovalSourceContext, ExecutionOutcome, PendingApproval,+ };++ const APPROVALS: &str = "approvals";+ const FLOW_TRUST: &str = "approval_flow_trust";++ /// Compare-and-swap attempts before a contended update gives up.+ const CAS_ATTEMPTS: usize = 32;++ /// The approval store over one scoped document handle.+ #[derive(Clone)]+ pub(super) struct Docs {+ docs: Arc<dyn DocumentStore>,+ }++ /// The document store to use for this call, when the host configured one.+ ///+ /// # Errors+ ///+ /// When the storage scope cannot be resolved — in SaaS mode with no acting+ /// agent — so the call fails rather than reading a shared bucket.+ pub(super) fn current() -> Result<Option<Docs>> {+ Ok(current_scoped()+ .context("[approval::store] resolve the storage scope")?+ .map(|scoped| Docs::new(&scoped)))+ }++ fn storage(error: StorageError) -> anyhow::Error {+ anyhow!("[approval::store] storage: {error}")+ }++ /// Fixed-width (nanosecond, `Z`) so the strings sort in time order.+ fn rfc3339(at: DateTime<Utc>) -> String {+ at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true)+ }++ /// The comparable expiry key: nanoseconds since the epoch, falling back to+ /// milliseconds for instants beyond the i64-nanosecond range (year 2262).+ fn expiry_key(at: DateTime<Utc>) -> i64 {+ at.timestamp_nanos_opt()+ .unwrap_or_else(|| at.timestamp_millis().saturating_mul(1_000_000))+ }++ fn parse_time(raw: Option<&str>) -> Option<DateTime<Utc>> {+ raw.and_then(|value| DateTime::parse_from_rfc3339(value).ok())+ .map(|at| at.with_timezone(&Utc))+ }++ fn text<'a>(doc: &'a Value, field: &str) -> Option<&'a str> {+ doc.get(field).and_then(Value::as_str)+ }++ /// A stored request as a [`PendingApproval`].+ fn to_pending(stored: &Versioned<Value>) -> PendingApproval {+ let doc = &stored.doc;+ PendingApproval {+ request_id: stored.id.clone(),+ tool_name: text(doc, "tool_name").unwrap_or_default().to_string(),+ action_summary: text(doc, "action_summary").unwrap_or_default().to_string(),+ args_redacted: text(doc, "args_redacted")+ .and_then(|raw| serde_json::from_str(raw).ok())+ .unwrap_or(Value::Null),+ created_at: parse_time(text(doc, "created_at")).unwrap_or_else(Utc::now),+ expires_at: parse_time(text(doc, "expires_at")),+ source_context: text(doc, "source_context").and_then(|raw| {+ serde_json::from_str::<ApprovalSourceContext>(raw)+ .map_err(|error| {+ tracing::warn!(+ %error,+ "[approval::store] failed to decode source_context JSON — treating as absent"+ );+ })+ .ok()+ }),+ tool_call_id: text(doc, "tool_call_id").map(str::to_string),++ agent_id: text(doc, "agent_id").map(str::to_string),+ }+ }++ /// A decided request as an [`ApprovalAuditEntry`]; `None` if it is not+ /// decided or its decision is unknown.+ fn to_audit(stored: &Versioned<Value>) -> Option<ApprovalAuditEntry> {+ let pending = to_pending(stored);+ let decided_at = parse_time(text(&stored.doc, "decided_at"))?;+ let decision = ApprovalDecision::from_str(text(&stored.doc, "decision")?)?;+ Some(ApprovalAuditEntry {+ request_id: pending.request_id,+ tool_name: pending.tool_name,+ action_summary: pending.action_summary,+ args_redacted: pending.args_redacted,+ created_at: pending.created_at,+ expires_at: pending.expires_at,+ decided_at,+ decision,+ })+ }++ /// `error` sanitized for the durable audit row, then capped at 512 chars —+ /// sanitize first, so truncation can never split a secret past the redactor.+ fn audit_error(error: Option<&str>) -> Option<String> {+ error.map(|raw| {+ let sanitized = crate::security::scrub::sanitize_text(raw).value;+ if sanitized.chars().count() > 512 {+ let head: String = sanitized.chars().take(511).collect();+ format!("{head}…")+ } else {+ sanitized+ }+ })+ }++ impl Docs {+ pub(super) fn new(scoped: &ScopedStorage) -> Self {+ Self {+ docs: Arc::clone(scoped.documents()),+ }+ }++ /// Runs `op` against the store from synchronous code.+ fn run<T, F, Fut>(&self, op: F) -> Result<T>+ where+ F: FnOnce(Arc<dyn DocumentStore>) -> Fut,+ Fut: std::future::Future<Output = Result<T, StorageError>> + Send + 'static,+ T: Send + 'static,+ {+ let docs = Arc::clone(&self.docs);+ let future = op(Arc::clone(&docs));+ block_on(async move {+ declare(&docs).await?;+ future.await+ })+ .map_err(storage)+ }++ pub(super) fn insert_pending(&self, pending: &PendingApproval, session_id: &str) -> Result<()> {+ let doc = json!({+ "tool_name": pending.tool_name,+ "action_summary": pending.action_summary,+ "args_redacted": serde_json::to_string(&pending.args_redacted)+ .context("[approval::store] serialize args_redacted")?,+ "session_id": session_id,+ "created_at": rfc3339(pending.created_at),+ "expires_at": pending.expires_at.map(rfc3339),+ "expires_ts": pending.expires_at.map(expiry_key),+ "source_context": pending+ .source_context+ .as_ref()+ .map(serde_json::to_string)+ .transpose()+ .context("[approval::store] serialize source_context")?,+ "tool_call_id": pending.tool_call_id,++ "agent_id": pending.agent_id,+ "pending": true,+ });+ let id = pending.request_id.clone();+ self.run(|docs| async move {+ docs.put(APPROVALS, &id, doc, Precondition::Absent)+ .await+ .map(|_| ())+ })+ }++ /// Inserts a request that is decided from birth (a flow+ /// pre-authorization): it never appears pending, only in the audit+ /// trail.+ pub(super) fn insert_decided(+ &self,+ tool_name: &str,+ action_summary: &str,+ session_id: &str,+ source_context: &ApprovalSourceContext,+ decision: ApprovalDecision,+ ) -> Result<()> {+ let now = rfc3339(Utc::now());+ let doc = json!({+ "tool_name": tool_name,+ "action_summary": action_summary,+ "args_redacted": "{}",+ "session_id": session_id,+ "created_at": now,+ "source_context": serde_json::to_string(source_context)+ .context("[approval::store] serialize preauthorization source_context")?,+ "pending": false,+ "decided_at": now,+ "decision": decision.as_str(),+ });+ let id = uuid::Uuid::new_v4().to_string();+ self.run(|docs| async move {+ docs.put(APPROVALS, &id, doc, Precondition::Absent)+ .await+ .map(|_| ())+ })+ }++ /// Moves every undecided request past its expiry to a terminal `deny`+ /// and returns the ones this call moved, so the caller can announce+ /// them.+ pub(super) fn expire_stale(&self, now: DateTime<Utc>) -> Result<Vec<PendingApproval>> {+ let deny = ApprovalDecision::Deny.as_str();+ let decided_at = rfc3339(now);+ let now_ts = expiry_key(now);+ self.run(|docs| async move {+ let query =+ Query::filter(Filter::eq("pending", true).and(Filter::lte("expires_ts", now_ts)));+ let mut expired = Vec::new();+ for stale in docs.query_all(APPROVALS, &query).await? {+ let moved = update(&docs, &stale.id, |doc| {+ if doc.get("pending") != Some(&json!(true)) {+ return None;+ }+ let mut next = doc.clone();+ next["pending"] = json!(false);+ next["decided_at"] = json!(decided_at);+ next["decision"] = json!(deny);+ Some(next)+ })+ .await?;+ if let Some(moved) = moved {+ expired.push(to_pending(&moved));+ }+ }+ Ok(expired)+ })+ }++ pub(super) fn list_pending(&self) -> Result<Vec<PendingApproval>> {+ self.run(|docs| async move {+ let query = Query::filter(Filter::eq("pending", true)).sort(Sort::asc("created_at"));+ Ok(docs+ .query_all(APPROVALS, &query)+ .await?+ .iter()+ .map(to_pending)+ .collect())+ })+ }+++ /// The agent that parked the still-undecided `request_id`: `None` when no++ /// such request is pending, `Some(None)` for one the process parked.++ pub(super) fn pending_agent(&self, request_id: &str) -> Result<Option<Option<String>>> {++ let id = request_id.to_string();++ self.run(|docs| async move {++ Ok(docs.get(APPROVALS, &id).await?.and_then(|stored| {++ (stored.doc.get("pending") == Some(&json!(true)))++ .then(|| text(&stored.doc, "agent_id").map(str::to_string))++ }))++ })++ }+++ pub(super) fn get_decision(&self, request_id: &str) -> Result<Option<ApprovalDecision>> {+ let id = request_id.to_string();+ self.run(|docs| async move {+ Ok(docs.get(APPROVALS, &id).await?.and_then(|stored| {+ text(&stored.doc, "decided_at")?;+ ApprovalDecision::from_str(text(&stored.doc, "decision")?)+ }))+ })+ }++ pub(super) fn decide(+ &self,+ request_id: &str,+ decision: ApprovalDecision,+ ) -> Result<Option<PendingApproval>> {+ self.decide_at(request_id, decision, Utc::now())+ }++ /// [`decide`](Self::decide) stamped `at`, so ordering can be pinned.+ pub(super) fn decide_at(+ &self,+ request_id: &str,+ decision: ApprovalDecision,+ at: DateTime<Utc>,+ ) -> Result<Option<PendingApproval>> {+ let id = request_id.to_string();+ let decided_at = rfc3339(at);+ self.run(|docs| async move {+ let decided = update(&docs, &id, |doc| {+ if doc.get("pending") != Some(&json!(true)) {+ return None;+ }+ let mut next = doc.clone();+ next["pending"] = json!(false);+ next["decided_at"] = json!(decided_at);+ next["decision"] = json!(decision.as_str());+ Some(next)+ })+ .await?;+ Ok(decided.as_ref().map(to_pending))+ })+ }++ pub(super) fn record_execution(+ &self,+ request_id: &str,+ outcome: ExecutionOutcome,+ error: Option<&str>,+ ) -> Result<bool> {+ let id = request_id.to_string();+ let executed_at = rfc3339(Utc::now());+ let error = audit_error(error);+ self.run(|docs| async move {+ let recorded = update(&docs, &id, |doc| {+ // Decided first, and the first outcome wins.+ if text(doc, "decided_at").is_none() || text(doc, "executed_at").is_some() {+ return None;+ }+ let mut next = doc.clone();+ next["executed_at"] = json!(executed_at);+ next["execution_outcome"] = json!(outcome.as_str());+ next["execution_error"] = json!(error);+ Some(next)+ })+ .await?;+ Ok(recorded.is_some())+ })+ }++ pub(super) fn list_recent_decisions(&self, limit: usize) -> Result<Vec<ApprovalAuditEntry>> {+ self.run(|docs| async move {+ let query =+ Query::filter(Filter::eq("pending", false).and(Filter::exists("decision", true)))+ .sort(Sort::desc("decided_at"))+ .limit(limit);+ let page = docs.query(APPROVALS, &query).await?;+ Ok(page.items.iter().filter_map(to_audit).collect())+ })+ }++ pub(super) fn purge_session(&self, session_id: &str) -> Result<usize> {+ let session = session_id.to_string();+ self.run(|docs| async move {+ let removed = docs+ .delete_where(+ APPROVALS,+ &Filter::eq("session_id", session).and(Filter::eq("pending", true)),+ )+ .await?;+ Ok(usize::try_from(removed).unwrap_or(usize::MAX))+ })+ }++ pub(super) fn insert_flow_trust(&self, flow_id: &str, tool_name: &str) -> Result<()> {+ let id = trust_id(flow_id, tool_name);+ let doc = json!({+ "flow_id": flow_id,+ "tool_name": tool_name,+ "created_at": rfc3339(Utc::now()),+ });+ self.run(|docs| async move {+ // `INSERT OR IGNORE`: re-granting is a no-op.+ match docs.put(FLOW_TRUST, &id, doc, Precondition::Absent).await {+ Ok(_) => Ok(()),+ Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),+ Err(error) => Err(error),+ }+ })+ }++ pub(super) fn list_flow_trust(&self, flow_id: &str) -> Result<Vec<String>> {+ let flow = flow_id.to_string();+ self.run(|docs| async move {+ let query = Query::filter(Filter::eq("flow_id", flow)).sort(Sort::asc("tool_name"));+ Ok(docs+ .query_all(FLOW_TRUST, &query)+ .await?+ .iter()+ .filter_map(|grant| text(&grant.doc, "tool_name").map(str::to_string))+ .collect())+ })+ }++ pub(super) fn delete_flow_trust(+ &self,+ flow_id: &str,+ tool_names: Option<&[String]>,+ ) -> Result<usize> {+ let flow = flow_id.to_string();+ let names = tool_names.map(<[String]>::to_vec);+ self.run(|docs| async move {+ let removed = match names {+ None => {+ docs.delete_where(FLOW_TRUST, &Filter::eq("flow_id", flow))+ .await?+ }+ Some(names) => {+ let mut removed = 0;+ for name in names {+ if docs+ .delete(FLOW_TRUST, &trust_id(&flow, &name), Precondition::None)+ .await?+ {+ removed += 1;+ }+ }+ removed+ }+ };+ Ok(usize::try_from(removed).unwrap_or(usize::MAX))+ })+ }++ pub(super) fn is_flow_tool_trusted(&self, flow_id: &str, tool_name: &str) -> Result<bool> {+ let id = trust_id(flow_id, tool_name);+ self.run(|docs| async move { Ok(docs.get(FLOW_TRUST, &id).await?.is_some()) })+ }+ }++ /// The id of a `(flow_id, tool_name)` grant: length-prefixed, so no two+ /// pairs collide.+ fn trust_id(flow_id: &str, tool_name: &str) -> String {+ format!("{}:{flow_id}/{tool_name}", flow_id.len())+ }++ async fn declare(docs: &Arc<dyn DocumentStore>) -> Result<(), StorageError> {+ docs.ensure_collection(+ &CollectionSpec::new(APPROVALS)+ .index(IndexSpec::new("by_pending", ["pending", "created_at"]))+ .index(IndexSpec::new("by_decided", ["pending", "decided_at"]))+ .index(IndexSpec::new("by_session", ["session_id", "pending"])),+ )+ .await?;+ docs.ensure_collection(+ &CollectionSpec::new(FLOW_TRUST).index(IndexSpec::new("by_flow", ["flow_id", "tool_name"])),+ )+ .await+ }++ /// Applies `change` to the request `id` under compare-and-swap and returns+ /// the stored result, or `None` when the request is missing or `change`+ /// declines (the request is no longer in the state the change requires).+ async fn update(+ docs: &Arc<dyn DocumentStore>,+ id: &str,+ change: impl Fn(&Value) -> Option<Value>,+ ) -> Result<Option<Versioned<Value>>, StorageError> {+ for _ in 0..CAS_ATTEMPTS {+ let Some(stored) = docs.get(APPROVALS, id).await? else {+ return Ok(None);+ };+ let Some(next) = change(&stored.doc) else {+ return Ok(None);+ };+ match docs+ .put(APPROVALS, id, next.clone(), stored.unchanged())+ .await+ {+ Ok(version) => {+ return Ok(Some(Versioned {+ id: id.to_string(),+ version,+ doc: next,+ }));+ }+ Err(error) if error.kind() == ErrorKind::Conflict => {}+ Err(error) => return Err(error),+ }+ }+ Err(StorageError::conflict(format!(+ "approval {id} kept changing under {CAS_ATTEMPTS} attempts"+ )))+ }++ #[cfg(test)]+ #[path = "store_documents_tests.rs"]+ mod tests;diff --cc crates/openhuman-core/src/security/approval/store_documents_tests.rsindex 0000000000,d1732b8493..e8b3758249mode 000000,100644..100644--- a/crates/openhuman-core/src/security/approval/store_documents_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_documents_tests.rs@@@ -1,0 -1,374 +1,399 @@@+ use super::*;+ use chrono::{Duration, Timelike};+ use tinystoragedrivers::{MemoryStorage, Scope, StorageBackend};++ fn docs_in(storage: &MemoryStorage, scope: &str) -> Docs {+ Docs::new(&storage.for_scope(&Scope::new(scope).unwrap()).unwrap())+ }++ fn docs() -> Docs {+ docs_in(&MemoryStorage::new(), "local")+ }++ fn pending(id: &str, created_secs_ago: i64, expires_in: Option<i64>) -> PendingApproval {+ let now = Utc::now();+ PendingApproval {+ request_id: id.to_string(),+ tool_name: "shell".to_string(),+ action_summary: format!("run {id}"),+ args_redacted: json!({ "file.name": "x", "cmd": "ls" }),+ created_at: now - Duration::seconds(created_secs_ago),+ expires_at: expires_in.map(|secs| now + Duration::seconds(secs)),+ source_context: Some(ApprovalSourceContext::Flow {+ flow_id: "flow-1".to_string(),+ run_id: "run-1".to_string(),+ node_id: None,+ }),+ tool_call_id: Some(format!("call-{id}")),++ agent_id: None,+ }+ }++ #[test]+ fn pending_requests_round_trip_oldest_first() {+ let store = docs();+ store.insert_pending(&pending("b", 10, None), "s1").unwrap();+ store.insert_pending(&pending("a", 20, None), "s1").unwrap();+ let listed = store.list_pending().unwrap();+ let ids: Vec<&str> = listed.iter().map(|p| p.request_id.as_str()).collect();+ assert_eq!(ids, ["a", "b"]);+ assert_eq!(listed[0].args_redacted["file.name"], json!("x"));+ assert_eq!(listed[0].tool_call_id.as_deref(), Some("call-a"));+ assert!(matches!(+ listed[0].source_context,+ Some(ApprovalSourceContext::Flow { .. })+ ));+ assert!(+ store.insert_pending(&pending("a", 0, None), "s1").is_err(),+ "a request id is inserted once"+ );+ }++ #[test]+ fn a_request_is_decided_exactly_once() {+ let store = docs();+ store.insert_pending(&pending("r", 0, None), "s").unwrap();+ assert_eq!(store.get_decision("r").unwrap(), None);+ let decided = store.decide("r", ApprovalDecision::ApproveOnce).unwrap();+ assert_eq!(decided.map(|p| p.request_id), Some("r".to_string()));+ assert!(store.decide("r", ApprovalDecision::Deny).unwrap().is_none());+ assert_eq!(+ store.get_decision("r").unwrap(),+ Some(ApprovalDecision::ApproveOnce)+ );+ assert!(store+ .decide("missing", ApprovalDecision::Deny)+ .unwrap()+ .is_none());+ assert!(store.list_pending().unwrap().is_empty());+ }++ #[test]+ fn concurrent_deciders_never_both_win() {+ let storage = MemoryStorage::new();+ let store = docs_in(&storage, "local");+ store+ .insert_pending(&pending("race", 0, None), "s")+ .unwrap();+ let winners: usize = (0..8)+ .map(|_| {+ let store = store.clone();+ std::thread::spawn(move || {+ store+ .decide("race", ApprovalDecision::ApproveOnce)+ .unwrap()+ .is_some()+ })+ })+ .collect::<Vec<_>>()+ .into_iter()+ .map(|handle| usize::from(handle.join().unwrap()))+ .sum();+ assert_eq!(winners, 1);+ }++ #[test]+ fn stale_requests_expire_to_deny_once() {+ let store = docs();+ store+ .insert_pending(&pending("old", 0, Some(-5)), "s")+ .unwrap();+ store+ .insert_pending(&pending("fresh", 0, Some(600)), "s")+ .unwrap();+ store+ .insert_pending(&pending("forever", 0, None), "s")+ .unwrap();+ let expired = store.expire_stale(Utc::now()).unwrap();+ assert_eq!(+ expired+ .iter()+ .map(|p| p.request_id.as_str())+ .collect::<Vec<_>>(),+ ["old"]+ );+ assert!(+ store.expire_stale(Utc::now()).unwrap().is_empty(),+ "only once"+ );+ assert_eq!(+ store.get_decision("old").unwrap(),+ Some(ApprovalDecision::Deny)+ );+ let left: Vec<String> = store+ .list_pending()+ .unwrap()+ .into_iter()+ .map(|p| p.request_id)+ .collect();+ assert_eq!(left.len(), 2);+ assert!(!left.contains(&"old".to_string()));+ }++ #[test]+ fn execution_is_recorded_after_a_decision_and_only_once() {+ let store = docs();+ store.insert_pending(&pending("r", 0, None), "s").unwrap();+ assert!(+ !store+ .record_execution("r", ExecutionOutcome::Success, None)+ .unwrap(),+ "not before a decision"+ );+ store.decide("r", ApprovalDecision::ApproveOnce).unwrap();+ let long = format!("token=sk-abcdefghijklmnopqrstuvwxyz {}", "e".repeat(800));+ assert!(store+ .record_execution("r", ExecutionOutcome::Failure, Some(&long))+ .unwrap());+ assert!(+ !store+ .record_execution("r", ExecutionOutcome::Success, None)+ .unwrap(),+ "the first outcome wins"+ );+ assert!(!store+ .record_execution("missing", ExecutionOutcome::Success, None)+ .unwrap());+ let stored = store+ .run(|docs| async move { docs.get(APPROVALS, "r").await })+ .unwrap()+ .unwrap();+ assert_eq!(stored.doc["execution_outcome"], json!("failure"));+ let error = stored.doc["execution_error"].as_str().unwrap();+ assert!(error.chars().count() <= 512, "capped");+ assert!(+ !error.contains("sk-abcdefghijklmnopqrstuvwxyz"),+ "the secret is redacted before storage: {error}"+ );+ }++ #[test]+ fn recent_decisions_are_newest_first_and_capped() {+ let store = docs();+ let base = Utc::now();+ for (n, id) in ["a", "b", "c"].into_iter().enumerate() {+ store.insert_pending(&pending(id, 0, None), "s").unwrap();+ // Distinct sub-second stamps (the fixed-width format must order them).+ let at = base + Duration::milliseconds(n as i64 * 100);+ store+ .decide_at(id, ApprovalDecision::ApproveOnce, at)+ .unwrap();+ }+ store+ .insert_pending(&pending("open", 0, None), "s")+ .unwrap();+ let recent = store.list_recent_decisions(2).unwrap();+ assert_eq!(+ recent+ .iter()+ .map(|e| e.request_id.as_str())+ .collect::<Vec<_>>(),+ ["c", "b"]+ );+ assert_eq!(recent[0].decision, ApprovalDecision::ApproveOnce);+ }++ #[test]+ fn purging_a_session_drops_only_its_undecided_requests() {+ let store = docs();+ store+ .insert_pending(&pending("mine", 0, None), "s1")+ .unwrap();+ store+ .insert_pending(&pending("decided", 0, None), "s1")+ .unwrap();+ store.decide("decided", ApprovalDecision::Deny).unwrap();+ store+ .insert_pending(&pending("theirs", 0, None), "s2")+ .unwrap();+ assert_eq!(store.purge_session("s1").unwrap(), 1);+ assert!(store.get_decision("decided").unwrap().is_some());+ let left: Vec<String> = store+ .list_pending()+ .unwrap()+ .into_iter()+ .map(|p| p.request_id)+ .collect();+ assert_eq!(left, ["theirs"]);+ }++ #[test]+ fn a_preauthorization_is_audit_only() {+ let store = docs();+ store+ .insert_decided(+ "http",+ "pre-authorized",+ "s",+ &ApprovalSourceContext::Flow {+ flow_id: "flow-1".to_string(),+ run_id: String::new(),+ node_id: None,+ },+ ApprovalDecision::ApproveAlwaysForFlow,+ )+ .unwrap();+ assert!(store.list_pending().unwrap().is_empty());+ let audit = store.list_recent_decisions(10).unwrap();+ assert_eq!(audit.len(), 1);+ assert_eq!(audit[0].decision, ApprovalDecision::ApproveAlwaysForFlow);+ }++ #[test]+ fn flow_trust_grants_list_and_revoke() {+ let store = docs();+ store.insert_flow_trust("flow-1", "shell").unwrap();+ store.insert_flow_trust("flow-1", "shell").unwrap();+ store.insert_flow_trust("flow-1", "http").unwrap();+ store.insert_flow_trust("flow-2", "shell").unwrap();+ assert_eq!(store.list_flow_trust("flow-1").unwrap(), ["http", "shell"]);+ assert!(store.is_flow_tool_trusted("flow-1", "shell").unwrap());+ assert!(!store.is_flow_tool_trusted("flow-1", "mail").unwrap());+ assert_eq!(+ store+ .delete_flow_trust("flow-1", Some(&["shell".to_string(), "nope".to_string()]))+ .unwrap(),+ 1+ );+ assert_eq!(store.delete_flow_trust("flow-1", None).unwrap(), 1);+ assert!(store.list_flow_trust("flow-1").unwrap().is_empty());+ assert!(store.is_flow_tool_trusted("flow-2", "shell").unwrap());+ assert_ne!(trust_id("a/b", "c"), trust_id("a", "b/c"));+ }++ #[test]+ fn scopes_keep_users_apart() {+ let storage = MemoryStorage::new();+ let alice = docs_in(&storage, "alice");+ let bob = docs_in(&storage, "bob");+ alice.insert_pending(&pending("r", 0, None), "s").unwrap();+ alice.insert_flow_trust("flow-1", "shell").unwrap();+ assert!(bob.list_pending().unwrap().is_empty());+ assert!(bob+ .decide("r", ApprovalDecision::ApproveOnce)+ .unwrap()+ .is_none());+ assert!(!bob.is_flow_tool_trusted("flow-1", "shell").unwrap());+ assert_eq!(alice.list_pending().unwrap().len(), 1);+ }++ #[test]+ fn an_unreadable_source_context_reads_as_absent() {+ let store = docs();+ store.insert_pending(&pending("r", 0, None), "s").unwrap();+ store+ .run(|docs| async move {+ let mut stored = docs.get(APPROVALS, "r").await?.unwrap();+ stored.doc["source_context"] = json!("not json");+ docs.put(APPROVALS, "r", stored.doc, Precondition::None)+ .await+ .map(|_| ())+ })+ .unwrap();+ assert!(store.list_pending().unwrap()[0].source_context.is_none());+ }++ #[test]+ fn a_missing_error_stays_missing() {+ assert!(audit_error(None).is_none());+ assert_eq!(audit_error(Some("plain")).as_deref(), Some("plain"));+ }++ #[test]+ fn sub_second_timestamps_order_and_expire_on_time() {+ let store = docs();+ let base = Utc::now();+ // Whole-second and sub-second values in the same second must sort by time.+ let whole = base.with_nanosecond(0).unwrap();+ for (id, at) in [("x", whole + Duration::milliseconds(500)), ("w", whole)] {+ let mut p = pending(id, 0, None);+ p.created_at = at;+ store.insert_pending(&p, "s").unwrap();+ }+ let ids: Vec<String> = store+ .list_pending()+ .unwrap()+ .into_iter()+ .map(|p| p.request_id)+ .collect();+ assert_eq!(ids, ["w", "x"]);++ // An approval due 900 ms into a second is not expired at 100 ms.+ let due = whole + Duration::milliseconds(900);+ let mut p = pending("late", 0, None);+ p.expires_at = Some(due);+ store.insert_pending(&p, "s").unwrap();+ assert!(store+ .expire_stale(whole + Duration::milliseconds(100))+ .unwrap()+ .is_empty());+ assert_eq!(store.expire_stale(due).unwrap().len(), 1);+ }++ #[test]+ fn a_captured_store_decides_without_the_task_scope() {+ let store = docs();+ store.insert_pending(&pending("r", 0, None), "s").unwrap();+ let config = crate::config::Config::default();+ let decided = crate::security::approval::store::decide_captured(+ &config,+ &Ok(Some(store.clone())),+ "r",+ ApprovalDecision::Deny,+ )+ .unwrap();+ assert_eq!(decided.map(|p| p.request_id), Some("r".to_string()));+ }++ #[test]+ fn an_unresolved_scope_fails_the_captured_decide_instead_of_using_sqlite() {+ let config = crate::config::Config::default();+ let captured = Err("no acting agent".to_string());+ let error = crate::security::approval::store::decide_captured(+ &config,+ &captured,+ "r",+ ApprovalDecision::Deny,+ )+ .unwrap_err();+ assert!(error.to_string().contains("unresolved"), "{error}");+ }++ #[test]+ fn expiry_is_compared_below_a_millisecond() {+ let store = docs();+ let whole = Utc::now().with_nanosecond(0).unwrap();+ let due = whole + Duration::nanoseconds(900_000);+ let mut p = pending("tight", 0, None);+ p.expires_at = Some(due);+ store.insert_pending(&p, "s").unwrap();+ assert!(store+ .expire_stale(whole + Duration::nanoseconds(100_000))+ .unwrap()+ .is_empty());+ assert_eq!(store.expire_stale(due).unwrap().len(), 1);+ }++++#[test]++fn the_parking_agent_round_trips_and_names_the_pending_owner() {++ let store = docs();++ let mut owned = pending("owned", 10, None);++ owned.agent_id = Some("alpha".to_string());++ store.insert_pending(&owned, "s1").unwrap();++ store++ .insert_pending(&pending("process", 5, None), "s1")++ .unwrap();++++ let listed = store.list_pending().unwrap();++ assert_eq!(listed[0].agent_id.as_deref(), Some("alpha"));++ assert_eq!(listed[1].agent_id, None);++ assert_eq!(++ store.pending_agent("owned").unwrap(),++ Some(Some("alpha".to_string()))++ );++ assert_eq!(store.pending_agent("process").unwrap(), Some(None));++ assert_eq!(store.pending_agent("missing").unwrap(), None);++++ store.decide("owned", ApprovalDecision::Deny).unwrap();++ assert_eq!(store.pending_agent("owned").unwrap(), None);++}diff --cc crates/openhuman-core/src/skills/ops_install/fetch.rsindex 01652b29da,0de2363420..347e590cab--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs@@@ -180,121 -271,10 +271,8 @@@ pub(crate) fn install_validated_documen.map(|s| s.name).collect();- let client = reqwest::Client::builder()- .timeout(std::time::Duration::from_secs(timeout_secs))- .build()- .map_err(|e| format!("fetch failed: build http client: {e}"))?;-- tracing::info!(- fetch_url = %redacted_fetch_url,- "[skills] install_workflow_from_url: fetching SKILL.md"- );-- let response = match client.get(&fetch_url).send().await {- Ok(resp) => resp,- Err(e) => {- let (failure, msg) = if e.is_timeout() {- ("timeout", format!("fetch timed out after {timeout_secs}s"))- } else {- ("transport", format!("fetch failed: {e}"))- };- crate::core::observability::report_error(- msg.as_str(),- "skills",- "install_fetch",- &[("url", redacted_fetch_url.as_str()), ("failure", failure)],- );- return Err(msg);- }- };-- let status = response.status();- if !status.is_success() {- // A 4xx (esp. 404/410) means the requested SKILL.md is gone or the URL- // is wrong — expected user/catalog input state, surfaced to the UI as- // "skill not found". Don't page Sentry for it (TAURI-RUST-CGE: ~1,446- // events / 72 users on `[email protected]`, almost all 404). Keep- // reporting 5xx — a genuine remote failure is still Sentry-actionable.- // The `Err(msg)` return is unchanged in both cases so the UI always- // surfaces the failure.- let status_str = status.as_u16().to_string();- // Read `Retry-After` off the response BEFORE anything consumes the- // body: `response.bytes()` below takes `response` by value, and a- // header read afterwards is not available at all. (The same ordering- // trap silently drops the header on the model-call path — see #6413.)- let retry_after = retry_after_secs(response.headers());- // A throttled host is a different user action from an unreachable one:- // "try again shortly" versus "this host is not answering". Both were- // previously the same opaque `returned status N` string, so the UI- // could not tell the user which had happened (#6409).- let msg = if status == reqwest::StatusCode::TOO_MANY_REQUESTS- || (status.is_server_error() && retry_after.is_some())- {- match retry_after {- Some(secs) => {- format!("{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry after {secs}s")- }- None => format!("{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry shortly"),- }- } else {- format!(- "fetch failed: {fetch_url} returned status {}",- status.as_u16()- )- };- let report_msg = format!(- "fetch failed: {redacted_fetch_url} returned status {}",- status.as_u16()- );- if should_report_install_fetch_status(status) {- crate::core::observability::report_error(- report_msg.as_str(),- "skills",- "install_fetch",- &[- ("url", redacted_fetch_url.as_str()),- ("status", status_str.as_str()),- ("failure", "non_2xx"),- ],- );- } else {- tracing::debug!(- fetch_url = %redacted_fetch_url,- status = status.as_u16(),- "[skills] install_workflow_from_url: skipped Sentry report for user/catalog fetch status"- );- }- return Err(msg);- }-- if let Some(len) = response.content_length() {- check_document_size(len).map_err(|e| e.to_string())?;- }-- let bytes = match response.bytes().await {- Ok(b) => b,- Err(e) => {- if e.is_timeout() {- return Err(format!("fetch timed out after {timeout_secs}s"));- }- return Err(format!("fetch failed: reading body: {e}"));- }- };-- // Size, UTF-8, frontmatter, required fields and slug derivation are- // owned by tinyskills; the second size check guards against a lying- // Content-Length header.- let document = validate_fetched_document(&bytes).map_err(|e| e.to_string())?;- let slug = document.slug;- let content = document.content;- let parse_warnings = document.warnings;-- // Install to user scope (`~/.openhuman/skills/<slug>`), which `discover_workflows`- // scans unconditionally. Project scope (`<ws>/.openhuman/skills/`) is gated on- // a `<ws>/.openhuman/trust` marker and would render the install invisible to the- // skills list until the user opts the workspace into trust.- let skills_root = home- .ok_or_else(|| "write failed: unable to resolve home directory".to_string())?- .join(".openhuman")- .join("skills");+ let skills_root = crate::skills::write_root::user_skill_install_root(workspace_dir, home)+ .ok_or_else(|| "write failed: unable to resolve home directory".to_string())?;let target_file =match write_installed_document(&skills_root, &slug, &content).map_err(|e| e.to_string())? {diff --cc crates/openhuman-core/src/web_chat/README.mdindex b9f7889d34,ced93a3c70..deb6aba4da--- a/crates/openhuman-core/src/web_chat/README.md+++ b/crates/openhuman-core/src/web_chat/README.md@@@ -1,202 -1,331 +1,331 @@@# Web chat- The web/desktop channel's turn runner. Owns the `channel.web_*` RPC namespace,- the Socket.IO `chat:start`/`chat:cancel` handlers' business logic, and the- whole request lifecycle from a raw message to a delivered, durably stored- reply. `channels/` owns the external messaging providers (Telegram, WhatsApp,- and so on); their inbound messages are dispatched through this module's- `start_chat` too (`channels/bus/subscriber.rs`), so this is the single turn- runner behind both surfaces.-- ## Request lifecycle-- 1. `openhuman-rpc/src/server/socketio.rs` receives a `chat:start` socket event and calls- [`start_chat`] (`ops/start_chat.rs`) with the raw message, thread/client ids,- and any model/profile/locale/queue-mode overrides.- 2. `start_chat` preprocesses `[FILE:...]`/`[IMAGE:...]` attachment markers- before prompt-injection scanning or persistence (a multi-MB base64 blob- must never reach those stages), runs `enforce_prompt_input`, and checks- for a parked chat-native approval reply before treating the message as a- new turn. It then applies the queue mode (`QueueMode::Interrupt` default,- `Steer`, `Followup`, `Collect`, `Parallel`) against the thread's- `InFlightEntry`/`ParallelEntry` (`types.rs`).- 3. It spawns a tokio task that runs `run_task::run_chat_task` through- `run_turn_under_cancel_and_deadline` (`ops/turn_guards.rs`): a cooperative- `CancellationToken`, the wall-clock backstop (`web_turn_deadline`), the- `AgentTurnOrigin::WebChat` scope, and the- `APPROVAL_CHAT_CONTEXT` task-local scope all wrap the same future.- 4. `run_chat_task` checks the session `Agent` out of the per-thread cache- (`session.rs::checkout_session_agent`), reusing the `thread_sessions()` entry- when its `SessionCacheFingerprint` (including the resolved effective model,- even without a picker override) still matches and otherwise building one- and cold-boot resuming it from the thread's `session_raw` transcript (or- the conversation log). A `Parallel` fork always builds a fresh agent and- never touches the cache. It then spawns [`spawn_progress_bridge`]- (`progress_bridge.rs`), awaits `agent.run_single`, and checks the agent- back in (`checkin_session_agent`) unless the turn poisoned it. The bridge- forwards `AgentProgress` into `WebChannelEvent` socket events, mirrors turn- state into `crate::threads::turn_state::TurnStateStore`, and emits an- `inference_heartbeat` beat every `INFERENCE_HEARTBEAT_SECS` (20s) so a long- silent prefill doesn't trip the frontend's ~120s silence timeout (#4270).- 5. On `Ok`, the spawned task calls `presentation::deliver_response`, which- first calls `reply_persistence::persist_delivered_reply` to write the reply- to the thread's conversation store under the deterministic- `run_reply_message_id(request_id)` (so the answer survives a client- reconnect or reload, #6034) and then emits exactly one `chat_done` carrying- the model's unmodified text. The segmentation helpers in `presentation.rs`- are legacy and unused on this path.- 6. On `Err`, `run_chat_task`'s error branch first consults the per-thread- budget signal (`budget_correlation.rs`, `classify_budget_correlation` maps- to a `BudgetCorrelation`) so an empty 200 on the same provider binding as a- recent budget-exhausted failure is reclassified as out-of-credits (#3386);- the spawned task then normalizes the error string through- `web_errors::classify_inference_error` into the user-facing `chat_error`- (budget-exhausted, non-retryable rate limit, fallback-chain-exhausted, turn- timeout, and so on) and decides via `sentry_suppression_reason` whether it- pages. The event carries `message` (finished English copy, unchanged for- older UIs, the CLI, the TUI and embedders) plus `copy_key`- (`chat_error.<class>`, one per row of `inference/failure_copy/table.rs`) and- `copy_params` (`retry_after_secs`, `provider`, `detail`); the app renders- the key in the user's locale (`app/src/lib/chatErrorCopy.ts`) and falls back- to `message` for an unknown or missing key. Loop-guard halt summaries are- not `chat_error` events (they become the turn's reply text), so they carry- no key.-- Host-authored turns, meaning background-delivery notices- (`agent::orchestration::background_delivery`) and goal continuations- (`agent::goals::continuation`), enter through `run_system_turn_on_thread`- (`ops/system_turn.rs`) instead of `start_chat`. They skip ingress, `in_flight()`- and the progress bridge but go through the same session checkout, so the- model sees the conversation and the turn lands in the thread's transcript. A- turn run on a throwaway host bound to the thread wrote a competing root- transcript that the next cold-boot resume preferred, dropping every earlier- turn. Such a turn checks out with `CheckoutPolicy::AdoptCached` (reuse the- thread's agent under whatever settings the user's last turn chose, rather than+ The turn runner for the in-app chat (desktop and web). It takes a raw user+ message, runs it through the agent harness on the thread's own session, and+ ends with a reply that is stored durably and announced to the client exactly+ once. It owns the `channel.web_*` RPC namespace and the business logic behind+ the Socket.IO `chat:start` and `chat:cancel` handlers.++ External messaging providers (Telegram, Discord and so on) live in+ `channels/`, but their inbound messages are dispatched through this module's+ `start_chat` as well (`channels/bus/subscriber.rs`). So this is the single+ turn runner behind both surfaces, and its `WebChannelEvent` broadcast bus is+ what Socket.IO, the JSON-RPC `/events` SSE stream, the TUI and the channel+ subscriber all listen to.++ ## How it works++ ### The request path++ ```text+ Socket.IO chat:start channel.web_chat RPC channels/ subscriber+ (openhuman-rpc socketio.rs) (schemas.rs) threads edit/regenerate+ \ | /+ v v v+ +-----------------------------------------------------++ | start_chat (ops/start_chat.rs) |+ | attachments -> prompt guard -> approval reply? |+ | -> beforeSubmitPrompt hook -> queue mode |+ +-----------------------------------------------------++ | Interrupt (default) | Steer/Followup/Collect -> RunQueue+ | Parallel -> spawn_parallel_turn (ops/parallel_turn.rs)+ v+ tokio::spawn( run_turn_under_cancel_and_deadline( )+ cancel token + wall-clock backstop+ + WebChat origin + APPROVAL_CHAT_CONTEXT+ run_chat_task (run_task.rs) )+ |+ | checkout_session_agent (session.rs)+ | spawn_progress_bridge (progress_bridge.rs) ---> WebChannelEvent+ | agent.run_single_with_origin (deltas, tools,+ | checkin_session_agent heartbeat, ...)+ v+ Ok(reply) --> presentation::deliver_response+ persist_reply (reply_persistence.rs) -> conversation store+ announce_reply -> one chat_done+ spawn_follow_up_suggestions -> chat_suggestions (later)+ Err(e) --> web_errors::classify_inference_error -> one chat_error+ ```++ 1. A `chat:start` socket event arrives in `openhuman-rpc/src/server/socketio.rs`+ (or a `channel.web_chat` RPC call, or an inbound provider message) and+ calls `start_chat` with the raw message, the thread and client ids, and any+ model, temperature, locale or queue-mode overrides.++ 2. `start_chat` stages `[FILE:...]` and `[IMAGE:...]` markers through+ `agent::attachments::stage` first. A multi-megabyte base64 blob must never+ reach prompt-injection scanning or persistence. It then runs+ `security::prompt_injection::enforce_prompt_input`; a block comes back as+ `StartChatError::Guardrail` with a verdict, score and reasons so the+ frontend can classify on `chat_error.error_type == "guardrail"` instead of+ matching copy. Next it checks whether the thread has a parked chat-native+ approval and the message parses as an approval reply+ (`security::approval::parse_approval_reply`); if so the reply goes to the+ approval gate and no new turn starts. Only after that does a configured+ `beforeSubmitPrompt` hook see the message, so a bare "yes" answering an+ approval can never be blocked by a hook.++ 3. The queue mode decides what happens to a turn already in flight on the+ thread. `QueueMode` ([`types.rs`](./types.rs)) has five values. `Interrupt` (the default)+ cancels the current turn and starts this one. `Steer`, `Followup` and+ `Collect` map to TinyAgents run-queue lanes (`QueueMode::queue_lane`) and+ are pushed onto the running turn's `RunQueue` instead of starting a turn;+ with nothing in flight they start a normal turn.+ `Parallel` starts an isolated fork alongside whatever is running- ([`ops/parallel_turn.rs`](./ops/parallel_turn.rs)), tracked in its own `PARALLEL_IN_FLIGHT` table++ ([`ops/parallel_turn.rs`](./ops/parallel_turn.rs)), tracked in its own `parallel_in_flight()` table+ keyed by request id so it never touches interrupt or queue semantics.+-4. For a primary turn, `start_chat` records an `InFlightEntry` in `IN_FLIGHT`++4. For a primary turn, `start_chat` records an `InFlightEntry` in `in_flight()`+ and spawns a task (under `CoreContext::propagate`) that drives+ `run_task::run_chat_task` through `run_turn_under_cancel_and_deadline`+ ([`ops/turn_guards.rs`](./ops/turn_guards.rs)). That wrapper puts four things around the same+ future: a cooperative `CancellationToken`, the wall-clock backstop, the+ `AgentTurnOrigin::WebChat` scope, and the `APPROVAL_CHAT_CONTEXT`+ task-local.++ 5. `run_chat_task` checks the session agent out of the per-thread cache+ (`session::checkout_session_agent`). The entry is removed from- `THREAD_SESSIONS` for the duration of the turn so two turns can never++ `thread_sessions()` for the duration of the turn so two turns can never+ drive one agent. It is reused when its `SessionCacheFingerprint` still+ matches; otherwise a new agent is built. A new agent needs no history+ seeding: `set_thread_id` binds the session's durable identity+ (`SessionRef`) and the turn resumes the thread's one transcript by it. The+ task then spawns the progress bridge, awaits+ `agent.run_single_with_origin`, and checks the agent back in with+ `checkin_session_agent` unless the turn poisoned it. A fork never takes or+ returns the cached agent.++ 6. While the turn runs, `spawn_progress_bridge` turns each `AgentProgress`+ event into `WebChannelEvent`s (`text_delta`, `thinking_delta`,+ `tool_call`, `tool_result`, `chat_interim`, `turn_cost`, sub-agent events+ and so on), mirrors turn state into `threads::turn_state::TurnStateStore`,+ and emits an `inference_heartbeat` every `INFERENCE_HEARTBEAT_SECS` (20 s)+ so a long silent prefill does not trip the frontend's roughly 120 s+ silence timeout (#4270). Sub-agent arms live in+ [`progress_bridge_subagent_events.rs`](./progress_bridge_subagent_events.rs); time to first visible output is+ stamped by [`turn_timing.rs`](./turn_timing.rs); at the end of a turn+ [`journal_shadow.rs`](./journal_shadow.rs) compares the live trace spans with the spans+ reprojected from the durable journal and logs what differs.++ 7. On success the spawned task calls `presentation::deliver_response`. It+ first writes the reply to the thread's conversation store+ (`persist_reply`, which uses `reply_persistence::persist_delivered_reply`)+ under the deterministic id `run_reply_message_id(request_id)`, so the+ answer survives a client reconnect or reload (#6034) and the client's own+ append collapses onto the same row. Then `announce_reply` emits exactly one+ `chat_done` carrying the model's unmodified text. For the main single-user+ turn it also spawns `suggestions::spawn_follow_up_suggestions`, a cheap+ `summarization`-role call that may emit `chat_suggestions` after+ `chat_done`. It never delays the reply and is gated on+ `web_chat.suggestions_enabled`.++ 8. On failure, `run_chat_task` first consults the per-thread budget signal+ ([`ops/budget_correlation.rs`](./ops/budget_correlation.rs)). An empty 200 on the same provider binding as+ a recent budget-exhausted failure is reclassified as out-of-credits (#3386),+ because the managed route closes the stream cleanly when credits run out.+ The spawned task then runs the error string through+ `web_errors::classify_inference_error` and emits one `chat_error`, and+ `sentry_suppression_reason` decides whether it pages.++ ### The chat_error payload++ A `chat_error` carries `message` (finished English copy, kept for older UIs,+ the CLI, the TUI and embedders), `copy_key` (`chat_error.<class>`, one per row+ of `inference/failure_copy/table.rs`) and `copy_params` (`retry_after_secs`,+ `provider`, `detail`). The app renders the key in the user's locale+ (`app/src/lib/chatErrorCopy.ts`) and falls back to `message` for an unknown or+ missing key. The classifier covers budget exhaustion, non-retryable rate+ limits, an exhausted fallback chain, turn timeouts, backend error codes and+ generic provider failures. Loop-guard halt summaries are not `chat_error`+ events (they become the turn's reply text), so they carry no key.++ ### Host-authored turns++ Background-delivery notices (`agent::orchestration::background_delivery`) and+ goal continuations enter through `run_system_turn_on_thread`-([`ops/system_turn.rs`](./ops/system_turn.rs)) instead of `start_chat`. They skip ingress, `IN_FLIGHT`++([`ops/system_turn.rs`](./ops/system_turn.rs)) instead of `start_chat`. They skip ingress, `in_flight()`+ and the progress bridge, run with `SYSTEM_CLIENT_ID` ("system"), and return+ the reply text for the caller to deliver. They still go through the same+ session checkout, so the model sees the conversation and the turn lands in the+ thread's transcript. A turn run on a throwaway session host would write a+ competing root transcript that the next resume preferred, dropping every+ earlier turn.++ Such a turn checks out with `CheckoutPolicy::AdoptCached` (reuse the thread's+ agent under whatever settings the user's last turn chose, instead ofrebuilding on a fingerprint miss) and checks in with- `checkin_session_agent_if_vacant`: a user turn that started meanwhile and- re-cached its own agent wins.-- ## Public surface-- - Event bus (`event_bus.rs`): `subscribe_web_channel_events`,- `publish_web_channel_event`, `approval_request_event`,- `register_approval_surface_subscriber`, `register_artifact_surface_subscriber`,- `register_egress_surface_subscriber`. These bridge `DomainEvent`s onto the- in-process `WebChannelEvent` broadcast bus consumed by both Socket.IO and- the JSON-RPC `/events` SSE stream.- - Operations (`ops.rs`, a thin shell over the `ops/` submodule: `start_chat.rs`,- `channel_ops.rs`, `parallel_turn.rs`, `turn_guards.rs`, `state.rs`,- `budget_correlation.rs`, `system_turn.rs`, `test_hooks.rs`): `start_chat`,- `run_system_turn_on_thread` (+ `SYSTEM_CLIENT_ID`,- `SESSION_CHECKOUT_FAILURE`), `cancel_chat`,- `cancel_chat_scoped`, `cancel_should_target`, `channel_web_chat`,- `channel_web_cancel`, `channel_web_queue_status`, `channel_web_queue_clear`,- `invalidate_thread_sessions`, plus `in_flight_entries_for_test` (exported- unconditionally; `test_support/introspect.rs` uses it). The turn's- in-flight/session state lives here (`thread_sessions()`, `in_flight()`,- `parallel_in_flight()` and the budget signals). Each table is a slot of- the ambient agent context, so two embedded agents on one thread id never- share an entry; outside an agent context it is the process default.- - `ChatRequestMetadata` (`types.rs`): per-request metadata passed by every- caller of `start_chat`/`spawn_progress_bridge`.- - Schemas (`schemas.rs`): `all_web_channel_controller_schemas`,- `all_web_channel_registered_controllers`, `schemas`. This is the RPC contract- for the `channel` namespace.- - Debug/test-only hooks: `set_test_forced_run_chat_task_error`,- `RUN_CHAT_TASK_TEST_LOCK`, `set_test_run_chat_task_block`,- `TestRunChatTaskBlock`, `parallel_in_flight_entries_for_test`- (`#[cfg(any(test, debug_assertions))]`) and- `fresh_approval_surface_subscription` (`#[cfg(debug_assertions)]`), so none- of them link into a release binary.+ `checkin_session_agent_if_vacant`, so a user turn that started meanwhile and+ re-cached its own agent wins. A checkout failure returns an error prefixed with+ `SESSION_CHECKOUT_FAILURE`, which callers use to tell "no turn ran" from "the+ turn failed".- ## Files+ ### Session cache fingerprint- | File | Purpose |- | --- | --- |- | `mod.rs` | Module wiring and re-exports; no business logic |- | `ops.rs` (thin shell over `ops/`: `start_chat.rs`, `channel_ops.rs`, `parallel_turn.rs`, `turn_guards.rs`, `state.rs`, `budget_correlation.rs`, `test_hooks.rs`) | `start_chat`/`cancel_*`/`channel_web_*` operations, session cache, in-flight tracking, budget-signal correlation, `run_turn_under_cancel_and_deadline` |- | `run_task.rs` | `run_chat_task`: resolves/builds the session agent, spawns the progress bridge, runs the turn, applies the budget correlation to its error |- | `session.rs` | Builds/fingerprints the cached session `Agent`, resolves target agent id, locale directive, provider role, and turn-local provider/model routing for a model selection |- | `progress_bridge.rs` | Forwards `AgentProgress` into `WebChannelEvent`s and `TurnStateMirror`, emits the `inference_heartbeat` liveness beat |- | `presentation.rs` | `deliver_response` (one unsegmented `chat_done`, persisted first) and `deliver_response_single_bubble` (core-initiated turns); local-model emoji-reaction decision; legacy segmentation helpers |- | `reply_persistence.rs` | Durable write of the reply about to be announced, under a deterministic id shared with the client's own append |- | `event_bus.rs` | The `WebChannelEvent` broadcast channel plus approval/artifact/egress `DomainEvent` surface subscribers |- | `web_errors.rs` (thin shell over `web_errors/`: `backend_error_code.rs`, `budget.rs`, `classify.rs`, `provider_detail.rs`, `retry.rs`, `timeout.rs`; the class -> copy table is `inference/failure_copy/`) | Classifies raw provider error strings into user-facing copy; budget-exhausted / rate-limit / fallback-exhausted / timeout detection |- | `schemas.rs` | `ControllerSchema`/`RegisteredController` definitions for the `channel.web_*` RPC functions |- | `types.rs` | `SessionEntry`, `SessionCacheFingerprint`, `InFlightEntry`, `ParallelEntry`, `WebChatTaskResult`, `ChatRequestMetadata`, `WebChatParams` |-- ## RPC-- Namespace `channel`, registered via- `all_web_channel_registered_controllers()` in `core/all.rs`:-- | Function | Handler |+ `SessionCacheFingerprint` ([`types.rs`](./types.rs)) decides when a cached agent can be+ reused. It holds the model override, the resolved effective model (so a+ changed managed default rebuilds even without a picker override), temperature,+ target agent id, provider binding, an autonomy signature and a model-registry+ signature (toggling a model's vision flag keeps the model id but must+ rebuild). A miss logs the fields that differ. Adding a dimension that should+ force a rebuild means adding a field there and filling it in+ `build_session_fingerprint` ([`session.rs`](./session.rs)).++ `session::effective_session_config` applies a concrete picker provider and+ model to the per-turn config clone. Managed `openrouter/...` defaults restore+ the managed route after restart without saving changes or touching sibling+ role routes; hints and unqualified legacy model ids keep their configured+ provider route. `provider_role_for_model_override` picks the provider role+ that feeds the fingerprint's binding.++ ### Cancellation and the backstop++ `cancel_chat` and `cancel_chat_scoped` ([`ops/channel_ops.rs`](./ops/channel_ops.rs)) cancel by+ thread, or by request id when one is given. A stale cancel for a superseded+ request is ignored (`cancel_should_target`) so the newer turn survives. Without+ a request id, a cancel also stops the thread's parallel forks and detached+ background sub-agents. `state::cancel_in_flight_gracefully` cancels the token+ first and only hard-aborts the task if it has not unwound after a short grace+ period.++ The wall-clock backstop defaults to 900 s (`DEFAULT_WEB_TURN_TIMEOUT_SECS`)+ and is set with `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` (`0` disables it). It is an+ outer safety net. The primary guard is the harness policy's+ `max_wall_clock_ms` (600 s by default), which interrupts a hung model or tool+ call and returns a proper timeout. The backstop only fires when a turn wedges+ outside the harness run, for example in session assembly, so the client still+ gets a terminal event instead of an endless heartbeat stream (#4746).++ ### The event bus++ [`event_bus.rs`](./event_bus.rs) holds an in-process `tokio::sync::broadcast` channel of+ `WebChannelEvent` (the type is defined in [`channel_event.rs`](./channel_event.rs)). Any domain can+ publish to it with `publish_web_channel_event`; consumers call+ `subscribe_web_channel_events`. It also registers process-lifetime,+ `OnceLock`-guarded subscribers on `core::bus::BUS` that turn `DomainEvent`s+ into socket events:++ | Registration | DomainEvents | Socket events |+ | --- | --- | --- |+ | `register_approval_surface_subscriber` | `ApprovalRequested`, `ApprovalDecided`, `PlanReviewRequested`, `PlanReviewDecided` | `approval_request`, `approval_decided`, `plan_review_request`, `plan_review_decided` |+ | `register_artifact_surface_subscriber` | `ArtifactPending`, `ArtifactReady`, `ArtifactFailed` | `artifact_pending`, `artifact_ready`, `artifact_failed` |+ | `register_agent_surface_subscriber` | thread goal, todo and run-mode changes; run-queue queued, delivered, dispatched and interrupted | `thread_goal_updated`, `thread_goal_cleared`, `thread_todos_changed`, `run_mode_changed`, `queue_item_queued`, `queue_item_delivered` |+ | `register_memory_activity_surface_subscriber` | `MemoryStored`, `MemoryRecalled` | `memory_activity` |+ | `register_egress_surface_subscriber` ([`egress_surface.rs`](./egress_surface.rs)) | `ExternalTransferPending`, only when the transfer carries chat routing | `external_transfer_pending` |++ They are registered from `core/runtime/bootstrap.rs` and+ `channels/runtime/startup/start_channels.rs`; the TUI registers the approval+ and artifact bridges itself (`openhuman-tui/src/runner.rs`).++ ## Layout++ | Path | What it does || --- | --- |- | `web_chat` | `channel_web_chat` |- | `web_cancel` | `channel_web_cancel` |- | `web_queue_status` | `channel_web_queue_status` |- | `web_queue_clear` | `channel_web_queue_clear` |-- ## Events-- - Broadcasts `WebChannelEvent` (defined in `openhuman-rpc/src/server/socketio.rs`) over an- in-process `tokio::sync::broadcast` channel. `openhuman-rpc/src/server/socketio.rs` forwards it- to the connected Socket.IO client; `core/jsonrpc/http/events.rs` subscribes to that stream and- serves the JSON-RPC `/events` SSE endpoint; `channels/bus/subscriber.rs`- subscribes to collect the reply for an inbound provider message.- - Subscribes to `DomainEvent` on `crate::core::bus::BUS` via three- process-lifetime, `OnceLock`-guarded subscribers registered at startup from- `core/runtime/bootstrap.rs` and `channels/runtime/startup/start_channels.rs`:- `register_approval_surface_subscriber`- (maps `ApprovalRequested`/`PlanReviewRequested` to `approval_request` /- `plan_review_request`), `register_artifact_surface_subscriber`- (maps `ArtifactPending`/`ArtifactReady`/`ArtifactFailed` to `artifact_*`), and- `register_egress_surface_subscriber` (maps `ExternalTransferPending` to- `external_transfer_pending`, only when the transfer carries chat routing).-- ## Calls into-- - `crate::agent::harness`: `Agent::from_config_for_agent`,- `run_queue::{RunQueue, QueueMode}`, and the tool-calling loop itself.- - `crate::threads::turn_state::{TurnStateStore, TurnStateMirror}`: the- progress bridge mirrors turn state here for cross-surface visibility.- - `crate::inference::provider::provider_for_role`: resolves the provider- binding for `provider_role_for_model_override`, which feeds the session- fingerprint. `effective_session_config` applies a concrete picker provider- and model to the per-turn clone; managed `openrouter/...` defaults restore- the managed route after restart without saving changes or altering sibling- role routes. Hints and unqualified legacy model IDs retain their configured- provider route.- - `crate::security::approval::APPROVAL_CHAT_CONTEXT`: scoped by- `run_turn_under_cancel_and_deadline` around the `run_chat_task` future.- `crate::web3::wallet::execution::current_owner()` relies on this task-local- staying scoped through the inline `.await` chain in `run_chat_task`;- detaching the tool loop onto a fresh `tokio::spawn` without re-scoping it- would silently disable the quote-owner gate (see `web3/wallet/README.md`).- - `crate::memory::conversations`: `reply_persistence` appends the durable- reply row; `crate::memory::agent::memory_loader::MemoryCitation` carries- citations through to that row's metadata.-- ## Called by-- - `openhuman-rpc/src/server/socketio.rs`: the `chat:start` and `chat:cancel` handlers call- `start_chat` / `cancel_chat_scoped`, and forward `WebChannelEvent`s to the- client.- - `core/jsonrpc/http/events.rs`: subscribes to the `/events` SSE stream and forwards web-channel events; `core/runtime/bootstrap.rs` registers the `DomainEvent` surface subscribers.- - `core/all.rs`: registers `all_web_channel_registered_controllers()` under- `DomainGroup::Channels`, deliberately not behind the `channels` feature- (the in-app chat is core product surface, #5002).- - `channels/bus/subscriber.rs`: inbound external-provider messages run through- `start_chat` with a per-sender `client_id`;- `channels/providers/telegram/remote_control.rs` calls- `invalidate_thread_sessions`.- - `flows/ops/streaming.rs` and- `agent/orchestration/background_delivery.rs`: core-initiated turns reuse- `spawn_progress_bridge` and `presentation::deliver_response*` so they render- on the same socket surface.- - `publish_web_channel_event` is also called from `cron`, `voice`,- and `channels/proactive.rs` for surface-level- notifications.+ | [`mod.rs`](./mod.rs) | Module wiring and re-exports. No business logic. |+ | [`ops.rs`](./ops.rs) | Thin shell over [`ops/`](./ops/); re-exports the request surface and state. |+ | [`ops/start_chat.rs`](./ops/start_chat.rs) | `start_chat` and `StartChatError`: ingress, guardrail, approval-reply routing, queue dispatch, and the spawned turn body that delivers or classifies. |+ | [`ops/channel_ops.rs`](./ops/channel_ops.rs) | `cancel_chat`, `cancel_chat_scoped`, and the `channel_web_*` RPC handlers. |+ | [`ops/parallel_turn.rs`](./ops/parallel_turn.rs) | Spawns and cancels `QueueMode::Parallel` forks. |+ | [`ops/system_turn.rs`](./ops/system_turn.rs) | `run_system_turn_on_thread` for host-authored turns. |-| [`ops/state.rs`](./ops/state.rs) | `THREAD_SESSIONS`, `IN_FLIGHT`, `PARALLEL_IN_FLIGHT`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`. |++| [`ops/state.rs`](./ops/state.rs) | `thread_sessions()`, `in_flight()`, `parallel_in_flight()`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`. Each table is a slot of the ambient agent context, so two embedded agents never share an entry; outside an agent context it is the process default. |+ | [`ops/turn_guards.rs`](./ops/turn_guards.rs) | `run_turn_under_cancel_and_deadline`, the wall-clock backstop, Sentry suppression and timeout tagging. |-| [`ops/budget_correlation.rs`](./ops/budget_correlation.rs) | `THREAD_BUDGET_SIGNALS` and `classify_budget_correlation` for the empty-200-after-budget case. |++| [`ops/budget_correlation.rs`](./ops/budget_correlation.rs) | `thread_budget_signals()` and `classify_budget_correlation` for the empty-200-after-budget case. |+ | [`ops/test_hooks.rs`](./ops/test_hooks.rs) | Debug/test hooks that force or block `run_chat_task`. |+ | [`run_task.rs`](./run_task.rs) | `run_chat_task`: checkout, progress bridge, run, budget correlation on error, checkin. |+ | [`session.rs`](./session.rs) | Session checkout and checkin, fingerprinting, `CheckoutPolicy`, target agent id, locale reply directive, per-turn provider and model routing. |+ | [`progress_bridge.rs`](./progress_bridge.rs) | `spawn_progress_bridge`: `AgentProgress` to `WebChannelEvent`, turn-state mirror, heartbeat. |+ | [`progress_bridge_subagent_events.rs`](./progress_bridge_subagent_events.rs) | The bridge's `AgentProgress::Subagent*` handlers. |+ | [`turn_timing.rs`](./turn_timing.rs) | Time to first visible output, and rate limiting for live `turn_cost` events. |+ | [`journal_shadow.rs`](./journal_shadow.rs) | Compares live trace spans with spans reprojected from the journal and logs divergences. |+ | [`presentation.rs`](./presentation.rs) | `deliver_response` (persist, then one `chat_done`), `deliver_response_single_bubble` for core-initiated turns, and legacy `chat_segment` helpers. |+ | [`reply_persistence.rs`](./reply_persistence.rs) | `persist_delivered_reply`: durable reply row under the deterministic reply id. |+ | [`suggestions.rs`](./suggestions.rs) | Post-turn follow-up suggestions (`chat_suggestions`). |+ | [`channel_event.rs`](./channel_event.rs) | `WebChannelEvent` and its payload types (`TurnUsagePayload`, `GuardrailPayload`, `QueueItemPayload`, `ChatSuggestion`, ...). |+ | [`event_bus.rs`](./event_bus.rs) | The broadcast channel and the `DomainEvent` surface subscribers. |+ | [`egress_surface.rs`](./egress_surface.rs) | The `external_transfer_pending` bridge. |+ | [`web_errors.rs`](./web_errors.rs) | Thin shell over [`web_errors/`](./web_errors/): `classify.rs` (the classification ladder and `ClassifiedError`), `backend_error_code.rs`, `budget.rs`, `retry.rs`, `timeout.rs`. The class to copy table is in `inference/failure_copy/`. |+ | [`schemas.rs`](./schemas.rs) | Controller schemas and thin handlers for the `channel` namespace. |+ | `types.rs` | `QueueMode`, `SessionEntry`, `SessionCacheFingerprint`, `InFlightEntry`, `ParallelEntry`, `WebChatTaskResult`, `ChatRequestMetadata`, RPC param structs. |++ ## Key types and entry points++ - `start_chat` ([`ops/start_chat.rs`](./ops/start_chat.rs)) is the entry point for every user turn.+ It returns the new request id, or a `StartChatError`.+ - `run_system_turn_on_thread` (`ops/system_turn.rs`) runs a host-authored turn+ on a thread's own session and returns the reply text.+ - `cancel_chat` / `cancel_chat_scoped` (`ops/channel_ops.rs`) stop a turn by+ thread or request id.+ - `invalidate_thread_sessions` ([`ops/state.rs`](./ops/state.rs)) drops a thread's cached agent.+ Thread edit and regenerate (`threads/ops/edit.rs`) and channel remote+ control (`channels/host/remote_control.rs`) call it.+ - `ChatRequestMetadata` (`types.rs`) is per-request metadata (`speak_reply`,+ `source`, `session_id`, `agent_id` for trace attribution) passed by every+ caller of `start_chat` and `spawn_progress_bridge`.+ - `WebChannelEvent` (`channel_event.rs`) is the event payload sent to clients.+ New fields are additive so older clients keep working.+ - `publish_web_channel_event` / `subscribe_web_channel_events`+ (`event_bus.rs`) are the bus.+ - `spawn_progress_bridge` and `presentation::deliver_response*` are reused by+ core-initiated turns (`flows/ops/streaming.rs`,+ `agent/orchestration/background_delivery.rs`) so they render on the same+ socket surface.+ - `persist_delivered_reply` and `pick_target_agent_id` are also used by the+ cron scheduler's origin delivery (`cron/scheduler/origin_delivery.rs`).+ - `classify_inference_error` ([`web_errors/classify.rs`](./web_errors/classify.rs)) maps a flattened+ error string to a `ClassifiedError`.++ ## RPC surface++ Namespace `channel`, registered through+ `all_web_channel_registered_controllers()` in `core/all.rs` under+ `DomainGroup::Channels`. It is deliberately not behind the `channels` feature,+ because the in-app chat is core product surface (#5002).++ | Method | Handler | Purpose |+ | --- | --- | --- |+ | `channel.web_chat` | `channel_web_chat` | Send a message through the agent loop. Takes `client_id`, `thread_id`, `message`, plus optional `model_override`, `temperature`, `locale`, `speak_reply`, `source`, `session_id`, `queue_mode`, `run_mode`, `reasoning_effort`. |+ | `channel.web_cancel` | `channel_web_cancel` | Cancel the thread's turn, or one `request_id`. |+ | `channel.web_queue_status` | `channel_web_queue_status` | Run-queue status for a thread. |+ | `channel.web_queue_clear` | `channel_web_queue_clear` | Clear a thread's run queue. |+ | `channel.web_queue_remove` | `channel_web_queue_remove` | Remove one queued item by `item_id`. |++ ## Boundaries++ - The agent loop, run queue, sessions and transcripts belong to TinyAgents+ (`vendor/tinyagents`); this module calls `run_single_with_origin` and uses+ `run_queue::{RunQueue, QueueLane}`. Segmentation helpers come from+ `tinychannels_bus::delivery` (`vendor/tinychannels`).+ - The Socket.IO transport and the `/events` SSE endpoint live in+ `openhuman-rpc` (`src/server/socketio.rs`, `src/server/http/events.rs`).+ This module only produces events.+ - External provider adapters (Telegram, Slack, ...) live in `channels/`.+ - Prompt-injection policy is `security::prompt_injection`; the approval gate+ and `APPROVAL_CHAT_CONTEXT` are `security::approval`.+ - Failure copy per error class is `inference/failure_copy/`; provider+ resolution is `inference::provider`.+ - Turn-state storage is `threads::turn_state`; the conversation store that the+ reply row lands in is `memory::conversations`.++ ## Gotchas++ - `APPROVAL_CHAT_CONTEXT` is a task-local scoped around the `run_chat_task`+ future. The wallet quote-owner gate+ (`web3::wallet::execution::current_owner()`) relies on it staying in scope+ through the inline `.await` chain. Moving the tool loop onto a fresh+ `tokio::spawn` without re-scoping it would silently disable that gate.+ - Approval-reply routing runs before the `beforeSubmitPrompt` hook on+ purpose. Reordering them lets a hook strand a turn waiting on an approval.+ - Attachment staging must stay ahead of prompt scanning and persistence.+ - A reply persistence error is non-fatal: the reply is announced anyway, since+ the client's own append is still a working fallback.-- Host-authored turns are not in `IN_FLIGHT`, so they neither interrupt nor++- Host-authored turns are not in `in_flight()`, so they neither interrupt nor+ get interrupted by user messages. Callers gate on idleness themselves.+ - Debug/test hooks (`set_test_forced_run_chat_task_error`,+ `RUN_CHAT_TASK_TEST_LOCK`, `set_test_run_chat_task_block`,+ `TestRunChatTaskBlock`, `parallel_in_flight_entries_for_test`,+ `fresh_approval_surface_subscription`) are compiled only under+ `cfg(any(test, debug_assertions))` or `cfg(debug_assertions)`.+ `in_flight_entries_for_test` is exported unconditionally because+ `test_support/introspect.rs` uses it.## Testsdiff --cc crates/openhuman-core/src/web_chat/ops.rsindex 14858ca1e9,1157ab33df..572e6e48d9--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@@ -28,11 -28,13 +28,13 @@@ pub use system_turn::{run_system_turn_o#[cfg(test)]pub use state::drain_queued_turns_for_test;+#[cfg(test)]+pub(crate) use state::in_flight;#[cfg(any(test, debug_assertions))]pub use state::parallel_in_flight_entries_for_test;+ #[cfg(test)]+ pub(crate) use state::scoped_key;-#[cfg(test)]-pub(crate) use state::IN_FLIGHT;-pub(super) use state::THREAD_SESSIONS;+pub(super) use state::thread_sessions;pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};pub(crate) use state::{event_session_id_for, key_for};diff --cc crates/openhuman-core/src/web_chat/ops/parallel_turn.rsindex 7e8f2aa65c,c6eab6c57c..3d126632d0--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs@@@ -14,7 -14,7 +14,7 @@@ use super::super::event_bus::publish_weuse super::super::run_task::run_chat_task;use super::super::types::{ChatRequestMetadata, ParallelEntry};use super::super::web_errors::classify_inference_error;- use super::state::parallel_in_flight;-use super::state::{key_for, unscope, PARALLEL_IN_FLIGHT};++use super::state::{key_for, parallel_in_flight, unscope};use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@@ -22,7 -22,7 +22,7 @@@/// Spawn an independent, forked (`QueueMode::Parallel`) turn. It snapshots the/// thread's history-at-start (inside `run_chat_task` with `fork = true`), runs/// concurrently with any other turn on the thread, and on completion delivers--/// its response (append-only) and removes itself from `PARALLEL_IN_FLIGHT`.++/// its response (append-only) and removes itself from [`parallel_in_flight`]./// Emits the same per-`request_id` stream events as a primary turn, so the UI/// can render it as an interleaved branch.#[allow(clippy::too_many_arguments)]@@@ -193,17 -197,14 +197,17 @@@ pub(crate) async fn spawn_parallel_turn}}- PARALLEL_IN_FLIGHT.lock().await.remove(&map_key_task);+ parallel_in_flight()+ .lock_owned()+ .await- .remove(&request_id_task);++ .remove(&map_key_task);},));- PARALLEL_IN_FLIGHT.lock().await.insert(+ parallel_in_flight().lock_owned().await.insert(- request_id,+ map_key,ParallelEntry {- thread_id: thread_id.to_string(),+ thread_id: key_for(thread_id),handle,cancel_token,},@@@ -215,10 -216,11 +219,11 @@@/// tears down any concurrent forked turns, not just the primary turn.pub(crate) async fn cancel_parallel_turns_for_thread(thread_id: &str) -> Vec<String> {let mut cancelled = Vec::new();+ let scoped_thread = key_for(thread_id);- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;+ let mut parallel = parallel_in_flight().lock_owned().await;let request_ids: Vec<String> = parallel.iter()- .filter(|(_, entry)| entry.thread_id == thread_id)+ .filter(|(_, entry)| entry.thread_id == scoped_thread).map(|(request_id, _)| request_id.clone()).collect();for request_id in request_ids {@@@ -247,10 -249,12 +252,12 @@@ pub(crate) async fn cancel_parallel_turthread_id: &str,request_id: &str,) -> Vec<String> {+ let map_key = key_for(request_id);+ let scoped_thread = key_for(thread_id);- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;+ let mut parallel = parallel_in_flight().lock_owned().await;let matches = parallel- .get(request_id)- .map(|entry| entry.thread_id == thread_id)+ .get(&map_key)+ .map(|entry| entry.thread_id == scoped_thread).unwrap_or(false);if !matches {return Vec::new();diff --cc crates/openhuman-core/src/web_chat/ops/state.rsindex 28b1674f9c,445e96e1b0..5013f782e8--- a/crates/openhuman-core/src/web_chat/ops/state.rs+++ b/crates/openhuman-core/src/web_chat/ops/state.rs@@@ -11,30 -11,73 +11,82 @@@ use tokio::sync::Mutexuse super::super::types::{InFlightEntry, ParallelEntry, SessionEntry};-pub(crate) static THREAD_SESSIONS: Lazy<Mutex<HashMap<String, SessionEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+type ThreadSessions = Mutex<HashMap<String, SessionEntry>>;+type InFlight = Mutex<HashMap<String, InFlightEntry>>;+type ParallelInFlight = Mutex<HashMap<String, ParallelEntry>>;-pub(crate) static IN_FLIGHT: Lazy<Mutex<HashMap<String, InFlightEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// The current agent context's per-thread session cache.+pub(crate) fn thread_sessions() -> Arc<ThreadSessions> {+ crate::core::runtime::current_slot::<ThreadSessions>()+}++/// The current agent context's primary in-flight turns, keyed by thread.+pub(crate) fn in_flight() -> Arc<InFlight> {+ crate::core::runtime::current_slot::<InFlight>()+}/// Parallel (forked) turns, keyed by `request_id`. A separate lane from-/// `IN_FLIGHT` (which holds one primary, interrupt-able turn per thread) so any-/// number of concurrent `QueueMode::Parallel` turns can run on the same thread-/// without touching interrupt/steer/queue semantics. See `QueueMode::Parallel`.-pub(crate) static PARALLEL_IN_FLIGHT: Lazy<Mutex<HashMap<String, ParallelEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// [`in_flight`] (which holds one primary, interrupt-able turn per thread) so+/// any number of concurrent `QueueMode::Parallel` turns can run on the same+/// thread without touching interrupt/steer/queue semantics.+pub(crate) fn parallel_in_flight() -> Arc<ParallelInFlight> {+ crate::core::runtime::current_slot::<ParallelInFlight>()+}+ /// The map key for `thread_id` in the calling scope.+ ///+ /// Thread ids are chosen by callers and are only unique per agent, so a turn+ /// running for an embedded agent ([`CoreContext::session_agent`]) is keyed+ /// `<agent>::<thread>`. Two agents that pick the same thread id then get two+ /// cache entries and two in-flight slots instead of sharing one live session.+ /// Outside an agent scope the key stays the bare thread id.+ ///+ /// [`CoreContext::session_agent`]: crate::core::runtime::CoreContext::session_agentpub(crate) fn key_for(thread_id: &str) -> String {- thread_id.to_string()+ let agent = crate::core::runtime::CoreContext::current()+ .and_then(|context| context.session_agent().map(str::to_owned));+ scoped_key(agent.as_deref(), thread_id)+ }++ /// `key` with the calling scope's agent prefix removed: the id the caller+ /// chose, for handing back to it.+ pub(crate) fn unscope(key: &str) -> String {+ let agent = crate::core::runtime::CoreContext::current()+ .and_then(|context| context.session_agent().map(str::to_owned));+ match agent {+ Some(agent) => key+ .strip_prefix(&scoped_key(Some(&agent), ""))+ .unwrap_or(key)+ .to_string(),+ None => key.to_string(),+ }+ }++ /// Injective encoding of `(session_agent, thread_id)`. Both parts are caller+ /// controlled, so a plain `agent::thread` join would let `("a", "b::c")` and+ /// `("a::b", "c")` (or an unscoped `"a::b"`) share one slot. A scoped key is+ /// `\x1f<agent byte length>:<agent><thread>`; an unscoped key is the bare+ /// thread id, except that an id starting with `\x1f` gets a second `\x1f`+ /// prepended so it can never look like a scoped key.+ pub(crate) fn scoped_key(session_agent: Option<&str>, thread_id: &str) -> String {+ match session_agent {+ Some(agent) => format!("\u{1f}{}:{agent}{thread_id}", agent.len()),+ None if thread_id.starts_with('\u{1f}') => format!("\u{1f}{thread_id}"),+ None => thread_id.to_string(),+ }+ }++ /// The thread id a [`scoped_key`] was built from, ignoring its agent scope.+ fn thread_id_of_key(key: &str) -> Option<&str> {+ let Some(rest) = key.strip_prefix('\u{1f}') else {+ return Some(key);+ };+ if rest.starts_with('\u{1f}') {+ return Some(rest);+ }+ let (len, tail) = rest.split_once(':')?;+ let len: usize = len.parse().ok()?;+ tail.get(len..)}pub(crate) fn event_session_id_for(client_id: &str, thread_id: &str) -> String {@@@ -71,12 -114,27 +123,26 @@@ pub(crate) fn cancel_in_flight_graceful}pub async fn invalidate_thread_sessions(thread_id: &str) {- // Under an embedded agent only that agent's slot goes: another agent that- // picked the same thread id keeps its live session. Outside an agent scope- // (a host-level edit or delete of the thread) every scope's slot goes.++ // Under an embedded agent only that agent's entry goes. Outside an agent++ // scope every entry for the thread in the current table goes.+ let active_agent = crate::core::runtime::CoreContext::current()+ .and_then(|context| context.session_agent().map(str::to_owned));- let mut sessions = THREAD_SESSIONS.lock().await;+ let mut sessions = thread_sessions().lock_owned().await;- let keys_to_remove: Vec<String> = sessions- .keys()- .filter(|k| k.as_str() == thread_id || k.ends_with(&format!("::{thread_id}")))- .cloned()- .collect();+ let keys_to_remove: Vec<String> = match active_agent {+ Some(_) => {+ let key = key_for(thread_id);+ sessions+ .contains_key(&key)+ .then_some(key)+ .into_iter()+ .collect()+ }+ None => sessions+ .keys()+ .filter(|k| thread_id_of_key(k) == Some(thread_id))+ .cloned()+ .collect(),+ };for key in &keys_to_remove {sessions.remove(key);}diff --cc crates/openhuman-core/src/web_chat/session.rsindex 7e6ada82bb,16ca30789d..7c594907e2--- a/crates/openhuman-core/src/web_chat/session.rs+++ b/crates/openhuman-core/src/web_chat/session.rs@@@ -543,6 -552,6 +552,10 @@@ pub(crate) async fn checkin_session_age#[path = "session_checkout_tests.rs"]mod session_checkout_tests;++#[cfg(test)]++#[path = "session_checkout_agents_tests.rs"]++mod session_checkout_agents_tests;++#[cfg(test)]#[path = "session_routing_tests.rs"]mod session_routing_tests;diff --cc crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rsindex 0000000000,0000000000..60f6e6c1cbnew file mode 100644--- /dev/null+++ b/crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rs@@@ -1,0 -1,0 +1,76 @@@++//! Per-agent session cache slots for embedded agents that share thread ids.++++use std::sync::Arc;++++use super::session_checkout_tests::{host_seeded_with, test_config, unique_thread};++use crate::config::Config;++use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};++use crate::web_chat::ops::{key_for, thread_sessions};++++/// Thread ids are chosen by callers, so two embedded agents can pick the same++/// one. Each must get its own cache slot, or the second agent's turn would++/// check out the first agent's live session and its history.++#[tokio::test]++async fn two_agents_with_the_same_thread_id_get_their_own_cache_slots() {++ let thread_id = unique_thread("agents");++ assert_eq!(key_for(&thread_id), thread_id, "no agent scope: bare id");++++ let parent = CoreContext::for_test(DomainSet::full(), None);++ let agent_ctx = |agent: &str| {++ parent.derive_with(++ ContextOverlay::new(Config::default(), DomainSet::full(), Default::default())++ .session_agent(agent),++ )++ };++ let asha = agent_ctx("asha");++ let ravi = agent_ctx("ravi");++ let key_a = CoreContext::scope(asha.clone(), async { key_for(&thread_id) }).await;++ let key_b = CoreContext::scope(ravi.clone(), async { key_for(&thread_id) }).await;++ assert_ne!(key_a, key_b);++ assert_ne!(key_a, thread_id);++ // Delimiter-looking input cannot forge another scope's key.++ use crate::web_chat::ops::scoped_key;++ assert_ne!(scoped_key(Some("a"), "b::c"), scoped_key(Some("a::b"), "c"));++ assert_ne!(scoped_key(None, "a::b"), scoped_key(Some("a"), "b"));++ assert_ne!(scoped_key(None, "\u{1f}1:ab"), scoped_key(Some("a"), "b"));++ assert_ne!(scoped_key(Some("a"), "bc"), scoped_key(Some("ab"), "c"));++++ let tmp = tempfile::tempdir().unwrap();++ let config = test_config(&tmp);++ let fingerprint =++ super::build_session_fingerprint(&config, None, None, "orchestrator".into(), "chat");++ for (ctx, key) in [(&asha, &key_a), (&ravi, &key_b)] {++ let entry = crate::web_chat::types::SessionEntry {++ agent: host_seeded_with(&config, "x"),++ fingerprint: fingerprint.clone(),++ };++ CoreContext::scope(Arc::clone(ctx), async {++ thread_sessions()++ .lock_owned()++ .await++ .insert(key.clone(), entry);++ })++ .await;++ }++ let cached = |ctx: &Arc<CoreContext>, key: &String| {++ let (ctx, key) = (Arc::clone(ctx), key.clone());++ async move {++ CoreContext::scope(ctx, async move {++ thread_sessions().lock_owned().await.contains_key(&key)++ })++ .await++ }++ };++ // Under one agent's scope only that agent's slot goes.++ CoreContext::scope(asha.clone(), async {++ crate::web_chat::ops::invalidate_thread_sessions(&thread_id).await;++ })++ .await;++ assert!(!cached(&asha, &key_a).await, "asha's slot is evicted");++ assert!(cached(&ravi, &key_b).await, "ravi's slot survives");++ CoreContext::scope(ravi.clone(), async {++ crate::web_chat::ops::invalidate_thread_sessions(&thread_id).await;++ })++ .await;++ assert!(!cached(&ravi, &key_b).await, "ravi's slot is evicted");++}diff --cc crates/openhuman-core/src/web_chat/session_checkout_tests.rsindex 9dd100e170,0e9bb9adc0..b897a0081f--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs@@@ -21,7 -21,7 +21,7 @@@ use crate::web_chat::types::SessionCachuse tinyagents_session::transcript::TranscriptMessage;use tinytools_agent::dialect::TranscriptEntry;--fn test_config(tmp: &tempfile::TempDir) -> Config {++pub(super) fn test_config(tmp: &tempfile::TempDir) -> Config {let config = Config {workspace_dir: tmp.path().join("workspace"),action_dir: tmp.path().join("workspace"),@@@ -32,7 -32,7 +32,7 @@@config}--fn unique_thread(tag: &str) -> String {++pub(super) fn unique_thread(tag: &str) -> String {format!("thread-checkout-{tag}-{}", uuid::Uuid::new_v4())}@@@ -86,7 -86,7 +86,7 @@@ fn prose(history: &[TranscriptEntry]) -.collect()}--fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {++pub(super) fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {let mut host = OpenHumanSessionHost::from_config_for_agent(config, "orchestrator").unwrap();host.seed_resume_from_messages(vec![@@@ -550,6 -548,115 +551,54 @@@ fn chat_agent_id_selects_the_web_chat_a);}-/// Thread ids are chosen by callers, so two embedded agents can pick the same-/// one. Each must get its own cache slot, or the second agent's turn would-/// check out the first agent's live session and its history.-#[tokio::test]-async fn two_agents_with_the_same_thread_id_get_their_own_cache_slots() {- use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};-- let thread_id = unique_thread("agents");- assert_eq!(key_for(&thread_id), thread_id, "no agent scope: bare id");-- let parent = CoreContext::for_test(DomainSet::full(), None);- let agent_ctx = |agent: &str| {- parent.derive_with(- ContextOverlay::new(Config::default(), DomainSet::full(), Default::default())- .session_agent(agent),- )- };- let key_a = CoreContext::scope(agent_ctx("asha"), async { key_for(&thread_id) }).await;- let key_b = CoreContext::scope(agent_ctx("ravi"), async { key_for(&thread_id) }).await;- assert_ne!(key_a, key_b);- assert_ne!(key_a, thread_id);- // Delimiter-looking input cannot forge another scope's key.- use crate::web_chat::ops::scoped_key;- assert_ne!(scoped_key(Some("a"), "b::c"), scoped_key(Some("a::b"), "c"));- assert_ne!(scoped_key(None, "a::b"), scoped_key(Some("a"), "b"));- assert_ne!(scoped_key(None, "\u{1f}1:ab"), scoped_key(Some("a"), "b"));- assert_ne!(scoped_key(Some("a"), "bc"), scoped_key(Some("ab"), "c"));-- // Evicting the thread clears every agent's slot for it.- {- let tmp = tempfile::tempdir().unwrap();- let config = test_config(&tmp);- let fingerprint =- super::build_session_fingerprint(&config, None, None, "orchestrator".into(), "chat");- let mut sessions = THREAD_SESSIONS.lock().await;- for key in [&key_a, &key_b] {- sessions.insert(- key.clone(),- crate::web_chat::types::SessionEntry {- agent: host_seeded_with(&config, "x"),- fingerprint: fingerprint.clone(),- },- );- }- }- // Under one agent's scope only that agent's slot goes.- CoreContext::scope(agent_ctx("asha"), async {- crate::web_chat::ops::invalidate_thread_sessions(&thread_id).await;- })- .await;- {- let sessions = THREAD_SESSIONS.lock().await;- assert!(!sessions.contains_key(&key_a), "asha's slot is evicted");- assert!(sessions.contains_key(&key_b), "ravi's slot survives");- }- // A host-level invalidation (no agent scope) clears every agent's slot.- crate::web_chat::ops::invalidate_thread_sessions(&thread_id).await;- let sessions = THREAD_SESSIONS.lock().await;- assert!(!sessions.contains_key(&key_a) && !sessions.contains_key(&key_b));-}-+ /// A host-authored turn adopts the thread's agent whatever settings built it,+ /// but never one built against another workspace: after a different user+ /// signs in, the old user's live session must not answer for the new one.+ #[tokio::test]+ async fn a_system_turn_never_adopts_an_agent_from_another_workspace() {+ let tmp_a = tempfile::tempdir().unwrap();+ let tmp_b = tempfile::tempdir().unwrap();+ let config_a = test_config(&tmp_a);+ let config_b = test_config(&tmp_b);+ let thread_id = unique_thread("workspace");+ let built_for_a =+ super::build_session_fingerprint(&config_a, None, None, "orchestrator".into(), "chat");+ checkin_session_agent(+ &thread_id,+ host_seeded_with(&config_a, "user-a-history"),+ built_for_a,+ )+ .await;++ let CheckedOutSession { agent, fingerprint } = checkout_session_agent(+ &config_b,+ super::super::SYSTEM_CLIENT_ID,+ &thread_id,+ None,+ None,+ None,+ CheckoutPolicy::AdoptCached,+ )+ .await+ .unwrap();+ assert!(+ !prose(&agent.history()).contains(&"user-a-history".to_string()),+ "workspace B must not inherit workspace A's session"+ );+ assert_eq!(fingerprint.workspace_dir, config_b.workspace_dir);+ evict(&thread_id).await;+ }++ #[test]+ fn fingerprint_diff_names_a_workspace_change() {+ let base = sample_fingerprint();+ let mut moved = base.clone();+ moved.workspace_dir = std::path::PathBuf::from("/ws/b");+ let diff = fingerprint_diff(&base, &moved);+ assert_eq!(diff.len(), 1, "{diff:?}");+ assert!(diff[0].starts_with("workspace_dir"), "{diff:?}");+ }+/// Every checkout arms the reply language from THIS turn's locale, on a fresh/// build and on a reused cached agent alike, and a locale with no directive/// (English) clears a stale one. Before the fix the directive was computeddiff --cc crates/openhuman-embed/README.mdindex 26750a9331,38eb157e56..778a4b2393--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@@ -207,244 -182,419 +182,461 @@@ println!("{}", second.reply)# }```- `Core` is the typed facade shown at the top: a host that already built a- `CoreRuntime` wraps it with `Core::from_runtime` and reaches sub-facades- through it: `config()`, `auth()`, and `agent()` (a `CoreAgent` running the- orchestrator).+ A harness keeps a few older defaults. Its agent's `action_dir` is the+ workspace's own `action/` directory, its skills are copied into the shared+ `<workspace>/skills` root, and it only turns on the `mcp` and `skills` domain+ families when servers or a skills directory were supplied. See+ [`src/harness/README.md`](src/harness/README.md).- ### One runtime per process+ ### The typed core facade- The keyring master key, the RPC bearer, the global event bus and the- `Once`-guarded domain subscribers are process-scoped- (`openhuman_core::core::runtime::context::CoreContext::init` runs that- sequence), so a second runtime would silently share them while believing it- had a separate workspace. `RuntimeBuilder::build` returns- `RuntimeError::AlreadyRunning` instead; agents are the unit of multiplicity.- `Core::from_runtime` is not guarded (it only wraps a runtime the host- already built), but the same constraint applies to the `CoreRuntime` beneath- it.+ ```rust,no_run+ use std::sync::Arc;- Build the tokio runtime yourself. A turn is a large async state machine that- overflows tokio's default 2 MiB worker stack once a sub-agent nests inside it,- so use `AGENT_WORKER_STACK_BYTES` and `MAX_BLOCKING_THREADS` from- [`openhuman_core::core::runtime`](../openhuman-core/src/core/runtime/README.md):+ use openhuman_embed::{Core, CoreBuilder, DomainSet, HostKind, ServiceSet};++ # async fn run() -> Result<(), Box<dyn std::error::Error>> {+ let runtime = CoreBuilder::new(HostKind::Library)+ .domains(DomainSet::embedded())+ .services(ServiceSet::none())+ .build()+ .await?;+ let core = Core::from_runtime(Arc::new(runtime));+ let flags = core.config().runtime_flags().await?;+ println!("log_prompts={}", flags.log_prompts);+ # Ok(())+ # }+ ```++ `Core::agent()` needs the `inference` domain family at runtime. Note that+ `DomainSet::harness()` leaves `inference` off despite its name; use+ `DomainSet::embedded()`.++ ### Product identity++ An embedding product sets its identity once at startup, before any backend+ client is built. It becomes the `x-sdk-name` header on TinyHumans requests.```rust,no_run- use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};+ use openhuman_tinyhumans::{set_product_identity, ProductIdentity};- let runtime = tokio::runtime::Builder::new_multi_thread()- .enable_all()- .thread_stack_size(AGENT_WORKER_STACK_BYTES)- .max_blocking_threads(MAX_BLOCKING_THREADS)- .build()- .expect("tokio runtime");+ if let Some(identity) = ProductIdentity::new("opencompany") {+ set_product_identity(identity);+ }```- ### Memory per tenant+ `openhuman_tinyhumans::RuntimeBuilder::product_identity` does the same as+ part of the build.- Bind each agent with `AgentSpec::memory(MemoryBinding::new(agent_id).root("team:acme"))`- and its turns run TinyMemory's lifecycle under `team:acme/agent:<agent_id>`.- `Runtime::memory("team:acme")` is the operator's view of that tenant: its- agents, items, learnings and brain. Every call stays inside the root's subtree.- `RuntimeBuilder::memory_engine` installs a host-supplied engine in place of the- configured one. See `docs/specs/memory-v2.md`.+ ## What the runtime owns and what an agent owns- ### Conversations in a host store+ The runtime owns everything that is process-scoped in the core: the+ workspace and credential store, the event bus, the keyring, the RPC bearer,+ the background `ServiceSet`, the registered `DomainSet` and the API key.+ Agents can only narrow the domain set, so a runtime has to register `mcp` and+ `skills` if any agent will use them. The default runtime does when those+ features are compiled in.- By default an agent's transcripts, turn journal, run status, goals and todos- are files under the runtime's workspace. A host serving many users from one- process keeps them in its own database instead:+ Each agent owns its provider route and model, its access tier and turn+ origin, its `action_dir`, its MCP servers, its skills root, its+ `AgentDefinitionSpec` (system prompt, tool scope, sandbox mode, iteration cap,+ temperature), its narrowed `DomainSet` and `ToolGroups`, its memory binding+ and an optional host tool factory.- ```rust,ignore- let runtime = Runtime::builder()- .workspace(Workspace::stateless()) // nothing durable on disk- .session_store(Arc::new(MyMongoStores::new(db)))- .build()- .await?;+ The on-disk layout under a runtime-owned root:++ ```text+ <root>/+ config.toml, auth-profiles.json, core.token runtime-wide+ workspace/+ session_db/sessions.db runtime-wide run ledger- session_raw/ transcripts (thread + agent)- agents/<id>/skills/ each agent's skills root++ agents/<id>/session_raw/ each agent's transcripts++ agents/<id>/skills/, workflows/ each agent's skills roots++ agents/<id>/cron/jobs.db each agent's cron jobs+ agents/<id>/action/ default action_dir per agent```- The runtime asks the provider (`session_store::SessionStoreProvider`) for- each agent's stores by agent id, so a provider over a shared database scopes- every query by agent and one agent can never reach another's conversation. A- reopened agent resumes its thread from the store, in any process.- `InMemorySessionStores` keeps everything in memory; the conformance suites in- `session_store` are what a host's provider is held to.- `Workspace::stateless()` refuses to build without a store, and a private- scratch directory, removed with the runtime, still holds process-local- caches (cost log, prompt templates, migration markers). The desktop app, CLI- and TUI install `openhuman_rpc::session_store`, the classic on-disk layout behind- the same port. See `tests/session_store.rs`.+ The default `action_dir` sits beside the workspace, never inside it, because+ the core refuses agent writes beneath the workspace. An inherited workspace+ uses `<action_dir>/agents/<id>` instead.-### Settings that are still runtime-wide--Every agent reads these from the runtime's boot config today. Each is a-candidate follow-up in the core.--- `autonomy.auto_approve` and `auto_approve_all`, and the memory guard's- autonomy tier, come from the boot config (`security::live_policy`). Path- and command policy do use the agent's own tier.-- The approval gate is on or off for the whole process, and parked approvals- are not labelled with an agent id. For an agent that never waits on- approval, use `Access::full()`, whose `TrustedAutomation` origin the gate- honours per turn.-- The sub-agent catalogue is runtime-wide (built-ins plus- `<workspace>/agents/*.toml`). Embedded agents cannot be `delegate_*`- targets of each other. Do not reuse built-in ids such as `orchestrator` or- `summarizer` for your agents.-- Sub-agents an agent spawns, and the experience store, read the runtime's- on-disk config rather than the agent's overlay.-- Sub-agent run-ledger rows, cron jobs and the cost log stay in the- workspace even with a host session store.-- Agents on one workspace share the dynamic `mcp_registry_*` MCP registry.- Servers declared through `AgentSpec::mcp` are per agent. The host-seeded- documentation server is visible to every agent.-- `install_skill` and `create_skill` still write to `~/.openhuman`. With- `include_user_skills(false)` (the default) an agent does not discover the- operator's skills, but an install it performs lands there.-- One API key (or session) is shared by every agent.+### Per agent++Every agent on a runtime is isolated from its siblings on the same workspace:++- Policy and approvals: the autonomy tier, `auto_approve`, `auto_approve_all`+ and the approval gate switch come from the agent's `Access`+ (`auto_approve`, `auto_approve_all`, `approval_gate`). Parked approvals+ carry the agent id; `Agent::approvals()` lists and decides only that+ agent's requests, and a chat reply routes by agent and thread.+- Sub-agents: `AgentSpec::subagents` declares workers only that agent can+ delegate to. Built-in ids (`orchestrator`, `planner`, …) are reserved.+ Detached sub-agents keep the agent's provider route.+- MCP: each agent has its own MCP host and dynamic registry under+ `<workspace>/agents/<id>/`, plus the servers its spec declares.+- Transcripts: `<workspace>/agents/<id>/session_raw/`. Conversations written+ before this layout into `<workspace>/session_raw/` stay readable and are+ copied into the agent's directory when resumed; the shared file is never+ changed.+- Skills: `install_skill` and `create_skill` write user-scope bundles into+ `<workspace>/agents/<id>/skills/` and `workflows/`, which only that agent+ discovers. The operator's `~/.openhuman` is untouched.+- Cron: jobs an agent creates live in `<workspace>/agents/<id>/cron/jobs.db`+ and run under that agent's context, provider and policy.+- Memory sources are synced per live agent, under its own context.+- Turn tables, plan mode, reasoning effort, turn citations, budget signals,+ the request journal, sub-agent dedupe and the `run_workflow` guard live in+ the agent's context, so two agents can use the same thread or session id+ at the same time.++### Lifecycle++`RuntimeBuilder::max_agents` caps live agents (default+`DEFAULT_MAX_AGENTS`, 1024); `Runtime::agent` returns+`AgentError::AgentLimit` past it. `Runtime::remove_agent(id)` denies the+agent's parked approvals (resolution `agent_removed`), refuses new turns and+ends the ones in flight with `CoreError::AgentRemoved` (waiting up to ten+seconds for them to unwind), then drops its state slots and MCP host and+deregisters its context, which leaves its cron jobs dormant. The id is+reusable once it returns; `.purge()` also deletes the agent's home.+Dropping the last handle to an agent tears it down the same way with+resolution `agent_dropped`. Cancellation is cooperative: a tool already+executing, or a sub-agent the turn detached, may finish after removal.++### Still process-owned++- The event bus, keyring and credential store, and the API key (or+ session): one per runtime, shared by every agent.- - `IntegrationClient` (backend-proxied Composio/search/media tools) accepts- the runtime's TinyHumans API key or an app-session JWT through- `security::credentials::session_support::resolve_backend_credential`.- API keys use `x-api-key`; session JWTs use `Authorization: Bearer`.- With the backend transport installed and the integration feature and runtime- gates enabled, an API-key-only runtime can register integration tools.+- The approval gate engine and its store. Rows are labelled and decided per+ agent, but the store is one file per workspace.+- Sub-agent run-ledger rows. They are keyed by unique run ids; an owner+ column would need a schema change in the vendored `tinyagents-session`.+- The host-installed session store (`openhuman_rpc::session_store`) keeps+ its single-operator layout; the per-agent transcript layout applies to the+ core's file fallback and to embedded agents.+- Background-delivery busy flags and skill run cancellation, which are keyed+ by unique session and run ids.+- A per-turn `Turn::route` override reaches that turn only; detached+ sub-agents use the agent's own route.++### Out of scope++- A per-agent cost log. It is accounting rather than behaviour isolation,+ `Turn::meter` already reports per turn, and a per-agent budget is a+ separate request.+- Embedded agents delegating to one another. Peer delegation is a+ cross-agent trust decision that TinyHiveMind owns.+- An API to add a memory source to a running agent. `AgentSpec` memory+ sources are taken when the agent is created; nothing needs more yet.- Other invariants worth knowing before wiring any entry point:+ ## Authentication and the backend++ Library mode has no user login. `RuntimeBuilder::api_key` stores a+ TinyHumans API key in the runtime's credential store before the core boots.+ Managed inference then sends it as `Authorization: Bearer <key>`, backend+ REST calls send it as `x-api-key`, and the scheduler gate treats the runtime+ as signed in. There is no `/auth/me` round trip and no session to expire. An+ agent that names its own `Provider` never uses the key for inference.++ The key covers the hosted features the core reaches: managed inference,+ cloud embeddings, voice (STT and TTS), web search, media generation, the Jev+ ranker, Composio and the other `/agent-integrations/*` tools, referral and+ webhooks. Callers that can only send a bearer (the vendored STT and embedding+ clients, the connector module's proxy route, the memory engine's sync) send+ the key as `Authorization: Bearer`, which the backend accepts by its+ `tiny_live_` / `tiny_test_` prefix. What a key may reach is decided by its+ scopes on the backend (`inference`, `voice`, `search`, `media`, `storage`,+ `account`, `connections`); a missing scope answers `403`, and a key minted+ through the grant flow omits `connections` unless it was asked for. The+ session-bound `/auth/*` flows (OAuth connect, channel link tokens, login+ tokens), the realtime voice agent and the Socket.IO relay still need a+ signed-in user. See+ [`gitbooks/developing/tinyhumans-api-key.md`](../../gitbooks/developing/tinyhumans-api-key.md).++ A host that drives backend features for a signed-in user passes a `Session`+ to `RuntimeBuilder::session` (or `HarnessBuilder::session`, or later+ `Auth::store`). The core stores it through `openhuman.auth_set_credential`+ and never validates it. Obtaining and checking the JWT is the host's job,+ which `openhuman_tinyhumans::session` does for the desktop app and TUI.+ `Session::local` builds the offline `.local` token form, which authorizes+ nothing at the backend.++ The core reaches the hosted backend only through a `BackendTransport`+ (re-exported here). This crate installs none. Without one, agents, memory,+ skills, tools and RPC still work, and hosted surfaces (managed inference,+ billing, integrations tools, cloud voice, channel relay) answer with a typed+ `BACKEND_UNAVAILABLE:` error. `openhuman_tinyhumans::RuntimeBuilder` installs+ the SDK transport for you; `RuntimeBuilder::backend_transport` takes your own.++ ## Memory per tenant++ Bind an agent with+ `AgentSpec::memory(MemoryBinding::new(agent_id).root("team:acme"))` and its+ turns run TinyMemory's lifecycle under `team:acme/agent:<agent_id>`.+ `Runtime::memory("team:acme")` returns a `memory::Memory`, the operator's view+ of that tenant: its agents, items, learnings and brain documents, with every+ call confined to the root's subtree. `RuntimeBuilder::memory_engine` installs+ a host-supplied engine in place of the configured one. See+ [`docs/specs/memory-v2.md`](../../docs/specs/memory-v2.md).++ ## Conversations in a host store- - When building a `CoreRuntime` yourself, set `config_path` together with- `workspace_dir` (`CoreBuilder::workspace(dir)` does both). Credentials,- auth profiles and the keyring file resolve beside `config_path`, so a- workspace-only override reads the operator's real credentials. `Runtime`- and `Harness` set both for `Workspace::Ephemeral` and `Workspace::Dir`.- - A turn runs under the access tier _and_ the turn origin. `Access::full()`- sets both (`AutonomyLevel::Full` plus a `TrustedAutomation` origin);- `Access::readonly()` and `Access::supervised()` set no origin and leave the- approval gate on.- - Supply skills through `AgentSpec::skills_dir` / `HarnessBuilder::skills_dir`,- which copy the bundles. Skill discovery rejects symlinked bundles, so- linking them in does not work.+ By default an agent's transcripts, turn journal, run status, goals and todos+ are files under the workspace. A host serving many users from one process+ keeps them in its own database instead:- ## Feature flags+ ```rust,ignore+ let runtime = Runtime::builder()+ .workspace(Workspace::stateless()) // nothing durable on disk+ .session_store(Arc::new(MyMongoStores::new(db)))+ .build()+ .await?;+ ```- Every feature on this crate is a pass-through to the same-named feature on- `openhuman-core` (package `openhuman`): `default`, `http-server`,- `inference`, `documents`, `hosting`, `modules`, `voice`, `web3`,- `runtime-node`, `contacts`, `media`, `flows`, `skills`, `mcp`,- `crash-reporting`, `channels`,- `sandbox-bubblewrap`, `browser-native`, `whatsapp-web`,- `file-logging`, `scheduler-gate`.+ The runtime asks the provider (`session_store::SessionStoreProvider`) for each+ agent's stores by agent id, so a provider over a shared database scopes every+ query by agent. A reopened agent resumes its thread from the store, in any+ process. `InMemorySessionStores` keeps everything in memory, and the+ conformance suites re-exported from `session_store` are what a host's+ provider is held to. `Workspace::stateless()` refuses to build without a+ store (`RuntimeError::NoSessionStore`); a private scratch directory, removed+ with the runtime, still holds process-local caches. The desktop app, CLI and+ TUI install `openhuman_rpc::session_store`, the classic on-disk layout behind+ the same port.++ ## Tools on an agent++ `AgentSpec::tools` gives an agent the host's own in-process tools, each with+ its own schema on the wire. The factory runs once per session build, which+ in practice is once per turn, and receives a `TurnContext` naming the agent+ and the session. `Agent::attach_tools` adds a permanent named tool source to+ an agent that already exists, which is how one library hands a configured+ agent to another. See [`src/agent/README.md`](src/agent/README.md).++ ## Layout++ | Path | What it does |+ | --- | --- |+ | [`src/lib.rs`](src/lib.rs) | Re-exports (core runtime types, `Tool`, `ToolGroups`, the backend port, `session_store`, `agent_progress`) and `Core`, the typed facade over a caller-built `CoreRuntime`. |+ | [`src/runtime/`](src/runtime/README.md) | `Runtime`, `RuntimeBuilder`, `ApiKey`, and the `CoreGuard` that owns process-scoped state until the last handle drops. |+ | [`src/agent/`](src/agent/README.md) | `Agent`, `AgentSpec`, `AgentDefinitionSpec`, `AgentLayout`, `MemoryBinding`, the build step, and permanent tool attachments. |+ | [`src/harness/`](src/harness/README.md) | `Harness` and `HarnessBuilder`, plus the shared input types: `Access`, `Provider`, `Workspace`, `McpServer`, skill copying, `HarnessError`. |+ | [`src/turn.rs`](src/turn.rs) | `Turn`, `TurnRequest`, `TurnOutcome`, `Route`: one turn, its ambient scopes, and its dispatch to an agent or to the orchestrator. |+ | [`src/call.rs`](src/call.rs) | The private typed dispatch helper over `CoreRuntime::invoke` that every facade method uses. |+ | [`src/config.rs`](src/config.rs), [`src/auth.rs`](src/auth.rs), [`src/core_agent.rs`](src/core_agent.rs) | The `Core` sub-facades: runtime flags, credentials (`Session`, `AuthState`), and the orchestrator turn. |+ | [`src/memory.rs`](src/memory.rs) | `Memory`, the per-tenant memory facade returned by `Runtime::memory`. |+ | [`src/process.rs`](src/process.rs), [`src/process_sentry.rs`](src/process_sentry.rs) | Host lifecycle helpers: the agent-sized tokio runtime, logging init, dotenv and launch overrides, the master key, and (`crash-reporting`) the Sentry `ClientOptions` with the single `before_send` chain. |+ | [`src/artifacts.rs`](src/artifacts.rs), [`src/chat_surface.rs`](src/chat_surface.rs), [`src/identity.rs`](src/identity.rs), [`src/modules.rs`](src/modules.rs) | Curated host facades: artifact file resolution, the in-process web-chat event stream, the signed-in identity peek, bundled module releases. `config` also carries `load_or_init`, `load_config_with_timeout`, `default_root_openhuman_dir`, `read_active_user_id`. |+ | [`src/host_internals.rs`](src/host_internals.rs) | `__host` (doc-hidden): an explicit list of core modules for `openhuman-tinyhumans` and `openhuman-rpc` only. |+ | [`src/error.rs`](src/error.rs) | `CoreError`, the error every facade call returns (`Domain`, `Unavailable`, `Rpc`, route refusals). |+ | [`examples/`](examples/README.md) | Runnable programs: one turn on a harness, and two agents on one runtime. |+ | [`tests/`](tests/README.md) | End-to-end suites against `wiremock` providers. |++ ## Key types and entry points++ - `Runtime` and `RuntimeBuilder` ([`src/runtime/`](src/runtime/)): build once per process,+ then call `Runtime::agent`. `Runtime::core()` gives non-turn access+ (config, auth) without exposing a way to start a turn.+ - `AgentSpec` ([`src/agent/spec.rs`](src/agent/spec.rs)): the pure-data description of an agent.+ Ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`.+ - `Agent` ([`src/agent/mod.rs`](src/agent/mod.rs)): a cheap clone handle. `run`, `turn`,+ `attach_tools`, and path accessors (`action_dir`, `home_dir`,+ `skills_dir`, `transcripts_dir`).+ - `Turn` and `TurnOutcome` ([`src/turn.rs`](src/turn.rs)): configure, then `send`.+ - `Access` ([`src/harness/access.rs`](src/harness/access.rs)): the autonomy tier and turn origin,+ always set together. Presets are `readonly`, `supervised` (the default)+ and `full`.+ - `Provider` ([`src/harness/provider.rs`](src/harness/provider.rs)): `openai_compatible(base_url, key)`+ plus `model`, or `inherit()` for the machine's configured inference.+ - `Workspace` ([`src/harness/workspace.rs`](src/harness/workspace.rs)): `Ephemeral` (default), `Dir`,+ `Stateless`, or `Inherit`.+ - `Harness` ([`src/harness/mod.rs`](src/harness/mod.rs)): one runtime, one agent.+ - `Core` ([`src/lib.rs`](src/lib.rs)): the typed facade over a caller-built runtime.++ ## One model call, no runtime: `Completer`++ A host that needs *a completion*, not an agent — a code reviewer asking for a+ JSON verdict, a classifier, an extractor — uses `complete::Completer`. It needs+ no `Runtime`, so none of the one-per-process and worker-stack constraints above+ apply, and any number of calls can run concurrently.- Two of them also gate items on this crate's own public surface:+ ```rust,no_run+ # async fn demo() -> Result<(), openhuman_embed::CoreError> {+ use openhuman_embed::complete::{ChatMessage, CompletionRequest, Completer, ResponseFormat};+ use openhuman_embed::Route;++ let completer = Completer::new(Route::openai_compatible("https://openrouter.ai/api/v1", "sk-…"))+ .header("X-Title", "my-app");+ let response = completer+ .complete(+ CompletionRequest::new("openai/gpt-5-mini", vec![ChatMessage::user("Is 7 prime?")])+ .response_format(ResponseFormat::JsonObject)+ .max_tokens(64)+ .provider_options(serde_json::json!({"usage": {"include": true}})),+ )+ .await?;+ println!("{:?} {:?} {:?}", response.structured, response.finish_reason, response.usage);+ # Ok(())+ # }+ ```- - `mcp`: `HttpHeader`, `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and- `HarnessBuilder::mcp`.- - `skills`: `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.+ It differs from an agent turn on purpose: no prompt-injection guard (callers+ pass untrusted text *as data*), no tools (a request declaring tools is+ refused), no session or orchestrator prompt, and no model fallback — the+ requested model is sent verbatim and `answered_model` reports what the+ provider says actually ran. `finish_reason`, token usage (cached and reasoning+ included) and the gateway-reported cost come back on the response; a+ `CompletionObserver` sees every call, success or failure, for trace export.- See [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md)- for a measured minimal-footprint feature set, and- [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)- for the resulting binary sizes and per-agent memory numbers.+ `openhuman_embed::embeddings` re-exports the embedding models (OpenAI, Voyage,+ Cohere, Ollama, mock) for hosts that keep their own vector index, with the+ signature format unchanged so stored vectors stay in their partition.- ## Examples and tests+ ## Locked-down agents: `HostOnly`- ```bash- # Against any OpenAI-compatible endpoint:- OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \- OPENHUMAN_EXAMPLE_API_KEY=sk-… \- OPENHUMAN_EXAMPLE_MODEL=gpt-5 \- cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"-- # Or against the machine's own configured inference, in its real workspace:- OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."+ An agent that reads untrusted input (a PR diff) and must never act takes+ `ToolScopeSpec::HostOnly`: the tools it can see and call are the ones the host+ supplies (`AgentSpec::tools`, `Agent::attach_tools`) and nothing else.++ ```rust,no_run+ use openhuman_embed::{AgentDefinitionSpec, AgentSpec, HostTurnTools, ToolScopeSpec};+ # fn read_only_tools() -> Vec<Box<dyn openhuman_embed::Tool>> { Vec::new() }+ let spec = AgentSpec::new("reviewer")+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("You review pull requests.")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(|_| HostTurnTools::advertised(read_only_tools()));```- Optional: `OPENHUMAN_EXAMPLE_BACKEND_URL` points non-inference backend calls- somewhere specific, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill bundles.+ - No config-derived tool is built and no delegation tool is synthesised, so+ shell, file writes, network, memory, skills, MCP and sub-agents do not exist+ for the model. A deny-by-default gate refuses any other name it calls anyway.+ - Access and sandbox are forced read-only, whatever `Access` was set (even+ after `AgentSpec::config`). Declaring MCP servers or skills is an error.+ - The agent needs its own prompt. `bare_prompt(text)` makes `text` the whole+ system prompt: no identity, safety, tools, workspace or memory section.++ Host tools should themselves be read-only: `HostOnly` bounds which tools+ exist, not what they do.++ Per turn, `Turn::response_format(ResponseFormat)` (the `complete` type) and+ `Turn::max_tokens(n)` apply to every call of the tool loop on any runtime-owned+ agent. `TurnOutcome` then carries `structured` (the reply parsed as JSON),+ `finish_reason`, `answered_model`, and `usage.reasoning_tokens`.+ `Turn::untrusted_input(true)` reads the message as data, so the prompt-injection+ guard and screen are skipped. It is accepted only on a `HostOnly` agent; any+ other agent refuses the turn (`untrusted_input_requires_host_only`).++ ## Feature flags- Two agents on one runtime, either BYOK with the same variables as above, or- managed inference with `OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY`:+ Every feature is a pass-through to the same-named feature on+ `openhuman-core` (package `openhuman`): `default`, `http-server`, `inference`,+ `documents`, `hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,+ `flows`, `skills`, `mcp`, `crash-reporting`, `channels`, `whatsapp-web`,+ `file-logging` and `scheduler-gate`. A gate added to the core has to be+ forwarded here (and then by `openhuman-tinyhumans` and `openhuman-cli`);+ [`scripts/ci/check-feature-forwarding.mjs`](../../scripts/ci/check-feature-forwarding.mjs) checks the chain.++ Two features also gate this crate's own surface. `mcp` adds `HttpHeader`,+ `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`.+ `skills` adds `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.++ [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md) has a+ measured minimal feature set, and+ [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)+ has the resulting binary sizes and per-agent memory.++ ## Boundaries++ - The only in-repo dependency is `openhuman-core` with+ `default-features = false`. Every capability comes from a forwarded+ feature.+ - No JSON-RPC here. This crate does not depend on `openhuman-rpc`; `Outcome`+ and `StructuredRpcError` are core types. `openhuman-app` and+ `openhuman-tui` use `openhuman-rpc` and the core directly and do not use+ this crate.+ - No backend client. The hosted transport, product identity, login-token+ exchange and `/auth/me` live in `openhuman-tinyhumans`.+ - The agent loop, transcripts, session identity and tool-call parsing belong+ to [`vendor/tinyagents`](../../vendor/tinyagents/) (repo `tinyhumansai/tinyagents`); the `Tool` trait+ belongs to its nested `tinytools`. Use the `Tool` re-exported here: a+ separately added `tinytools` builds an incompatible type.+ - Memory contracts come from [`vendor/tinymemory`](../../vendor/tinymemory/) (`tinymemory-api`).++ ## Gotchas++ - One runtime per process. The keyring master key, the RPC bearer, the+ event bus and the `Once`-guarded domain subscribers are process-scoped+ (`CoreContext::init`). A second `RuntimeBuilder::build` returns+ `RuntimeError::AlreadyRunning`; a second harness returns+ `HarnessError::AlreadyRunning`. `Core::from_runtime` is not guarded, but+ the same rule applies to the `CoreRuntime` beneath it. The slot is+ released only when the `Runtime` and every `Agent` built on it are+ dropped.+ - Build the tokio runtime yourself. A turn is a deep async state machine,+ and a nested sub-agent overflows tokio's default 2 MiB worker stack, so+ `#[tokio::main]` is not enough. The constants live in the core crate, so+ the host needs the `openhuman` package as a dependency to name them:++ ```rust,no_run+ use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};++ let runtime = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .thread_stack_size(AGENT_WORKER_STACK_BYTES)+ .max_blocking_threads(MAX_BLOCKING_THREADS)+ .build()+ .expect("tokio runtime");+ ```++ - Access has two halves. The autonomy tier drives `SecurityPolicy`, and the+ turn origin (a task-local) drives the approval gate. `Access::full()` sets+ both; setting only the tier through `config` gives an agent whose acting+ tools refuse while the transcript looks plausible. `readonly()` and+ `supervised()` set no origin and leave the approval gate on, so an+ unattended supervised agent stalls on approvals until they expire.+ - When building a `CoreRuntime` yourself, set `config_path` together with+ `workspace_dir` (`CoreBuilder::workspace(dir)` does both). Credentials,+ auth profiles and the keyring file resolve beside `config_path`, so a+ workspace-only override reads the operator's real credentials. `Runtime`+ and `Harness` handle this for `Ephemeral`, `Stateless` and `Dir`, and the+ `AgentSpec::config` escape hatch cannot move it.+ - Supply skills through `skills_dir`, which copies bundles. Skill discovery+ rejects symlinked bundles, so linking them in silently does nothing.+ - `Provider::model` is advisory. A model no provider serves falls back to+ the default rather than failing, and a route with no model resolved is+ ignored.+ - A `Route` (or `Provider::openai_compatible`) that pairs a key with a plain+ `http://` endpoint is refused before dispatch with+ `CoreError::InsecureRoute`. A route without a key is allowed.+ - A resumed session keeps its first system prompt and tool list. Prompt+ changes and a tool factory that returns a different belt only reach new+ sessions.++ ## Tests++ The integration suites under [`tests/`](tests/README.md) each build one+ runtime per process against `wiremock` providers; unit tests sit beside+ their modules as `*_tests.rs`.```bash- OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \- OPENHUMAN_EXAMPLE_API_KEY=sk-… \- OPENHUMAN_EXAMPLE_MODEL=gpt-5 \- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."-- # Or managed inference, no BYOK endpoint needed:- OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_… \- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."+ cargo test -p openhuman-embed --features inference,mcp,skills+ cargo test -p openhuman-embed --features inference,mcp,skills --test runtime_agents```- The repository-root `examples/embed_headless.rs` (`DomainSet::harness()`,- `ServiceSet::none()`, RPC through `CoreRuntime::invoke`) and- `examples/embed_kernel.rs` (`DomainSet::kernel()`, then opt one family back- in) drive `CoreBuilder` from `openhuman_core` directly, without this crate;- they are `[[example]]` entries of the `openhuman` package, so run them with- `cargo run --example embed_headless`.-- `tests/harness_embed.rs` is the end-to-end proof that `Harness` runs a real- turn against a `wiremock` provider with nothing bound;- `tests/runtime_agents.rs` runs three agents with different providers, access- tiers, skills, MCP servers and working directories on one runtime and shows- the API key reaching a mocked managed backend as a bearer;- `tests/public_api.rs` pins the host-facing embedding contract at compile- time. Run them with `cargo test -p openhuman-embed --features inference,mcp,skills`.-- ## Relationship to other crates-- Its only in-repo dependency is `openhuman-core` (package `openhuman`) with- `default-features = false`: every capability comes from a feature forwarded- above. It does not depend on `openhuman-rpc`; `Outcome` and `StructuredRpcError`- are core types (`openhuman_core::core`). `openhuman-app` and `openhuman-tui`- depend on `openhuman-rpc` for its client (and the app on its server) and on- `openhuman-core`; neither uses `openhuman-embed`.-- ## Permanent tools on supplied agents-- Hosts can pass an existing configured `Agent` to another library, which adds- its tools through `Agent::attach_tools` without constructing a replacement.- Attachments are shared by clones, always directly advertised, and update only- their managed system catalogue when a continuing conversation gains tools.- See [agent attachment semantics and example](src/agent/README.md#attach-tools-to-an-existing-agent)- for source identity, collision errors, policy composition, and runtime identity.+ The repository-root [`examples/embed_headless.rs`](../../examples/embed_headless.rs) and [`examples/embed_kernel.rs`](../../examples/embed_kernel.rs)+ drive `CoreBuilder` directly, without this crate. They are `[[example]]`+ targets of `openhuman-cli`:+ `cargo run -p openhuman-cli --example embed_headless`.++ ## Further reading++ - [`crates/openhuman-embed/examples/README.md`](examples/README.md): the examples module README.+ - [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md): embedding the core in another product.+ - [`gitbooks/developing/tinyhumans-api-key.md`](../../gitbooks/developing/tinyhumans-api-key.md): running on a TinyHumans API key.+ - [`gitbooks/developing/architecture.md`](../../gitbooks/developing/architecture.md): architecture overview.+ - [`gitbooks/developing/architecture/agent-harness.md`](../../gitbooks/developing/architecture/agent-harness.md): the agent harness.+ - [`gitbooks/developing/loadable-modules.md`](../../gitbooks/developing/loadable-modules.md): loadable modules.+ - [`crates/README.md`](../README.md): crates overview.diff --cc crates/openhuman-embed/src/agent/build.rsindex 5edc8de3f8,71f1370c1c..9f8cd616c4--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@@ -24,11 -22,26 +25,30 @@@ pub(crate) fn instantiate(runtime: &Runid: id.clone(),reason,})?;+ let catalogue = process_catalogue();+ if catalogue.get(&id).is_some() {+ return Err(AgentError::ReservedId(id));+ }+ // A host-only agent must never act, whatever else the spec says, so its+ // exclusions are settled before any of the spec is applied.+ let host_only = parts.definition.is_host_only();+ if host_only {+ #[cfg(feature = "mcp")]+ if !parts.mcp_servers.is_empty() {+ return Err(AgentError::Invalid(+ "a HostOnly agent cannot declare MCP servers; supply its tools as host tools"+ .into(),+ ));+ }+ #[cfg(feature = "skills")]+ if parts.skills_dir.is_some() {+ return Err(AgentError::Invalid(+ "a HostOnly agent cannot install skills".into(),+ ));+ }+ }+let base = runtime.base_config();let root_dir = base.config_path@@@ -217,7 -220,7 +248,8 @@@access,layout,host_tools: parts.host_tools,+ lifecycle: super::lifecycle::Lifecycle::new(),+ host_only,})}diff --cc crates/openhuman-embed/src/agent/mod.rsindex 13606e317f,dd79db6077..94ac25e200--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@@ -117,55 -97,11 +117,58 @@@ pub(crate) struct AgentInner/// The agent's own in-process tools, rebuilt per turn. See/// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,+ pub(crate) lifecycle: lifecycle::Lifecycle,+ /// Built from [`ToolScopeSpec::HostOnly`]: every turn's session is built+ /// from the host tools alone.+ pub(crate) host_only: bool,}+impl AgentInner {+ /// Releases what the core keeps for this agent: parked approvals are+ /// denied with `resolution`, its state slots and MCP host are dropped,+ /// and its context leaves the registry. Runs once.+ pub(crate) fn teardown(&self, resolution: &str) {+ if !self.lifecycle.begin_teardown() {+ return;+ }+ self.deny_approvals(resolution);+ self.ctx.agent_state().clear();+ if openhuman_core::mcp::host::take_agent_host(&self.config.workspace_dir, &self.id)+ .is_some()+ {+ log::debug!(+ "[embed][agent] teardown id={} evicted its MCP host",+ self.id+ );+ }+ openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);+ log::debug!("[embed][agent] teardown complete id={}", self.id);+ }++ /// Denies every approval this agent has parked, with `resolution`.+ pub(crate) fn deny_approvals(&self, resolution: &str) {+ let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() else {+ return;+ };+ match gate.deny_all_for_agent(&self.id, resolution) {+ Ok(denied) => log::debug!(+ "[embed][agent] id={} denied_approvals={denied} resolution={resolution}",+ self.id+ ),+ Err(error) => log::warn!(+ "[embed][agent] id={} could not deny approvals: {error}",+ self.id+ ),+ }+ }+}++impl Drop for AgentInner {+ fn drop(&mut self) {+ self.teardown("agent_dropped");+ }+}+/// A handle to one agent on a runtime.////// Cheap to clone; every clone drives the same agent. The id is released fordiff --cc crates/openhuman-embed/src/harness/access.rsindex eef341e68f,5141b68b11..dd97707de4--- a/crates/openhuman-embed/src/harness/access.rs+++ b/crates/openhuman-embed/src/harness/access.rs@@@ -192,14 -154,16 +192,22 @@@ impl Access/// scoped-down agent.pub(crate) fn apply(&self, config: &mut openhuman_core::config::Config) {config.autonomy.level = self.level;+ // The tier only binds while the policy is on, and the core ships it+ // off (`[autonomy] enabled = false`). Without this, `readonly()` and+ // `supervised()` would leave shell and file writes wide open. `full()`+ // keeps whatever the base config says, so existing automation hosts+ // see no change.+ if self.level != AutonomyLevel::Full {+ config.autonomy.enabled = true;+ }config.autonomy.allow_tool_install = self.allow_tool_install;config.autonomy.trusted_roots = self.trusted_roots.clone();+ if let Some(tools) = &self.auto_approve {+ config.autonomy.auto_approve = tools.clone();+ }+ if let Some(enabled) = self.auto_approve_all {+ config.autonomy.auto_approve_all = enabled;+ }// `auto_approve_all` is deliberately NOT set for `full()`. The origin// is the correct instrument — it says *who is calling*, which the gate// can reason about — whereas `auto_approve_all` is a blanket bypassdiff --cc crates/openhuman-embed/src/harness/access_tests.rsindex 0dee15bf46,a8ed8cdeb4..f6071a5e7c--- a/crates/openhuman-embed/src/harness/access_tests.rs+++ b/crates/openhuman-embed/src/harness/access_tests.rs@@@ -141,32 -141,26 +141,56 @@@ fn an_explicit_origin_overrides_the_pre));}+#[test]+fn approval_lists_are_inherited_until_the_agent_sets_them() {+ let mut config = Config::default();+ config.autonomy.auto_approve = vec!["boot_tool".into()];+ config.autonomy.auto_approve_all = true;++ Access::supervised().apply(&mut config);+ assert_eq!(config.autonomy.auto_approve, ["boot_tool"]);+ assert!(config.autonomy.auto_approve_all);++ Access::supervised()+ .auto_approve(["shell", "file_write"])+ .auto_approve_all(false)+ .apply(&mut config);+ assert_eq!(config.autonomy.auto_approve, ["shell", "file_write"]);+ assert!(!config.autonomy.auto_approve_all);+}++#[test]+fn the_approval_gate_switch_is_independent_of_the_tier() {+ let access = Access::supervised().approval_gate(false);+ assert!(!access.approval_gate_enabled());+ let mut config = Config::default();+ access.apply(&mut config);+ assert_eq!(config.autonomy.level, AutonomyLevel::Supervised);+ assert!(access.turn_origin().is_none());++ assert!(Access::full().approval_gate(true).approval_gate_enabled());+}+++ /// The core ships the policy off, which makes every tier inert. A scoped-down+ /// access level must switch it on, or `readonly()` would still let the agent+ /// write files and run commands.+ #[test]+ fn restrictive_tiers_switch_the_policy_on() {+ for access in [Access::readonly(), Access::supervised()] {+ let mut config = openhuman_core::config::Config::default();+ config.autonomy.enabled = false;+ access.apply(&mut config);+ assert!(config.autonomy.enabled, "{access:?} must enable the policy");+ }+ }++ /// `full()` leaves the switch where the base config put it.+ #[test]+ fn full_access_keeps_the_configured_policy_switch() {+ for enabled in [false, true] {+ let mut config = openhuman_core::config::Config::default();+ config.autonomy.enabled = enabled;+ Access::full().apply(&mut config);+ assert_eq!(config.autonomy.enabled, enabled);+ }+ }diff --cc crates/openhuman-embed/src/lib.rsindex 6d40980fd9,f0f4b68e2e..87de273d79--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@@ -96,10 -114,26 +114,26 @@@ pub mod processmod runtime;mod turn;+ /// Core internals for `openhuman-tinyhumans` and `openhuman-rpc` only; see+ /// the module docs. Not part of the host-facing API.+ #[doc(hidden)]+ #[path = "host_internals.rs"]+ pub mod __host;++ /// Look up the schema of a registered RPC method (`openhuman.<ns>_<fn>`).+ pub use openhuman_core::core::all::schema_for_rpc_method;+ /// Whether this build carries the HTTP server surface the router mounts.+ pub use openhuman_core::core::http_server_status::HTTP_SERVER_COMPILED_IN;+ pub use openhuman_core::core::ControllerSchema;+ /// Why a listen-port pick failed (another live core holds the port, ...).+ pub use openhuman_core::platform::connectivity::rpc::PickListenPortError;+ /// Whether this build carries the voice domain.+ pub use openhuman_core::voice::VOICE_COMPILED_IN;+pub use agent::ToolAttachmentError;pub use agent::{- Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, MemoryBinding, SandboxModeSpec,- ToolScopeSpec,+ Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals,+ ApprovalsError, MemoryBinding, PendingApproval, SandboxModeSpec, ToolScopeSpec,};pub use auth::{Auth, AuthState, Session};pub use config::{Config, RuntimeFlags};@@@ -110,8 -144,24 +144,27 @@@ pub use harness::};#[cfg(feature = "mcp")]pub use harness::{HttpHeader, McpAuthConfig, McpServer};+pub use runtime::builder::DEFAULT_MAX_AGENTS;- pub use runtime::{ApiKey, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError};+ /// Read-only view of a [`RuntimeBuilder`], for the layered crates' tests.+ #[doc(hidden)]+ pub use runtime::BuilderSummary;-pub use runtime::{run_from_args, ApiKey, ConfigSource, Runtime, RuntimeBuilder, RuntimeError};++pub use runtime::{++ run_from_args, ApiKey, ConfigSource, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError,++};++ /// The types the [`RuntimeBuilder`] seam options take: controller+ /// extensions, embedder hooks, the CLI server launcher and the live security+ /// policy. A `tool_search` ranker implements `tinytools::ToolRanker`; take+ /// `tinytools` from the vendored path (`vendor/tinyagents/vendor/tinytools`)+ /// so the trait unifies — re-exporting it here would break the+ /// agent-runtime ownership boundary.+ pub mod seams {+ pub use openhuman_core::agent::hooks::{PostTurnHook, ToolHook};+ pub use openhuman_core::agent::hooks::{ToolHookContext, ToolHookDecision, TurnContext};+ pub use openhuman_core::core::all::{ControllerExtension, DomainGroup};+ pub use openhuman_core::core::server_launcher::{ServeRequest, ServerLauncher};+ pub use openhuman_core::security::SecurityPolicy;+ }/// The session store port: what a host implements to keep every agent's/// conversations in its own database ([`RuntimeBuilder::session_store`]),diff --cc crates/openhuman-embed/src/runtime/README.mdindex 714046292d,2fc29e9885..edf3205eb8--- a/crates/openhuman-embed/src/runtime/README.md+++ b/crates/openhuman-embed/src/runtime/README.md@@@ -23,38 -95,57 +95,56 @@@ releases `RUNTIME_LIVE`The runtime owns everything process-scoped in the core: the event bus, thekeyring and credential store, the RPC bearer, the background `ServiceSet`,- the compiled `DomainSet`, and the API key. An agent owns everything the core- reads through its own ambient context: its `Config` (provider route, model,+ the registered `DomainSet`, and the API key. An agent owns everything the+ core reads through its own context: its `Config` (provider route and model,MCP servers, autonomy tier, `action_dir`), its `AgentDefinition` (system-prompt, tool scope, sandbox mode), its skills root, and its narrowed-`DomainSet` and `ToolGroups`. Some settings, such as-`autonomy.auto_approve` and the memory guard's autonomy tier, are still read-from the runtime's boot config by every agent; check the crate README's list-of settings that are still runtime-wide before assuming an agent-level-override reaches them.+prompt, tool scope, sandbox mode), its skills root, its narrowed+`DomainSet` and `ToolGroups`, its approval settings and parked approvals,+its sub-agents, its MCP host, its cron jobs and its per-turn state. The+crate README's "Still process-owned" list names what agents share, and its+"Lifecycle" section covers `max_agents` and `Runtime::remove_agent`.- ## One runtime per process+ ## Boundaries- `CoreContext::init` seeds the process-scoped state exactly once.- `RuntimeBuilder::build` returns `RuntimeError::AlreadyRunning` for a second- runtime rather than letting two runtimes share a keyring and event bus while- each believes it owns a separate workspace. Agents, not runtimes, are the- unit of multiplicity: build one runtime and put every agent the host needs on- it with `Runtime::agent`.+ - Booting the core (`CoreBuilder`, `CoreContext`, service startup) belongs to+ `openhuman_core::core::runtime`. See its+ [README](../../../openhuman-core/src/core/runtime/README.md).+ - No backend transport is installed here. `openhuman-tinyhumans`'s+ `RuntimeBuilder` ([`crates/openhuman-tinyhumans/src/runtime.rs`](../../../openhuman-tinyhumans/src/runtime.rs)) wraps this+ builder and installs the SDK transport on `build()`; see+ [`gitbooks/developing/tinyhumans-api-key.md`](../../../../gitbooks/developing/tinyhumans-api-key.md).+ - The session store port (`SessionStoreProvider`) is defined by+ [`vendor/tinyagents`](../../../../vendor/tinyagents/) and the core's `agent::session_store`; the classic+ on-disk provider lives in `openhuman-rpc`'s `session_store`.- ## The tokio runtime is the host's job+ ## Gotchas- An agent turn is a deep async state machine, and delegating to a sub-agent- nests another one inside it. Build the host's tokio runtime with- `AGENT_WORKER_STACK_BYTES` and `MAX_BLOCKING_THREADS`- (`openhuman_core::core::runtime`) or the default 2 MiB worker stack can- overflow.+ - One runtime per process. `CoreContext::init` seeds the process-scoped+ state once, so `build` returns `RuntimeError::AlreadyRunning` rather than+ letting two runtimes share a keyring and event bus while each believes it+ owns a separate workspace. Agents are the unit of multiplicity.+ - The tokio runtime is the host's job. Build it with+ `AGENT_WORKER_STACK_BYTES` and `MAX_BLOCKING_THREADS`+ (`openhuman_core::core::runtime`) or a turn with a nested sub-agent+ overflows the default 2 MiB worker stack.+ - The provider's route is never written into the config; only its model is+ (`apply_provider`). Config routes persist, and a library caller must not+ repoint the operator's install.+ - `memory_engine` and `session_store` are process-wide, like the runtime.+ The session store is removed with the runtime.- ## Where to look next+ ## Tests- - [`../agent/README.md`](../agent/README.md): what `Runtime::agent` builds.- - [`../harness/README.md`](../harness/README.md): the one-agent shorthand- built on top of a `Runtime` and an `Agent`.- - `openhuman-tinyhumans`'s `RuntimeBuilder` extension- (`crates/openhuman-tinyhumans/src/lib.rs`) boots a runtime already connected- to the hosted backend; see- [`gitbooks/developing/tinyhumans-api-key.md`](../../../../gitbooks/developing/tinyhumans-api-key.md).+ [`builder_tests.rs`](builder_tests.rs) and [`api_key_tests.rs`](api_key_tests.rs) sit beside their modules. The+ end-to-end suites in [`../../tests/`](../../tests/README.md) build real+ runtimes.++ ```bash+ cargo test -p openhuman-embed --features inference,mcp,skills runtime::+ ```++ ## Further reading++ - [`gitbooks/developing/embedding.md`](../../../../gitbooks/developing/embedding.md): embedding the core in another product.+ - [`gitbooks/developing/tinyhumans-api-key.md`](../../../../gitbooks/developing/tinyhumans-api-key.md): running on a TinyHumans API key.+ - [`crates/openhuman-embed/README.md`](../../README.md): the openhuman-embed crate README.diff --cc crates/openhuman-embed/src/runtime/build.rsindex 0000000000,b301f1749e..85889fb409mode 000000,100644..100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@@ -1,0 -1,385 +1,386 @@@+ //! [`RuntimeBuilder::build`]: the boot sequence.++ use std::path::Path;+ use std::sync::Arc;++ use openhuman_core::agent::session_store::SessionStoreProvider;+ use openhuman_core::config::Config;+ use openhuman_core::core::runtime::CoreBuilder;+ use openhuman_core::core::types::HostKind;++ use super::builder::ConfigSource;+ use super::presets::{default_domains, default_services};+ use super::{ApiKey, Runtime, RuntimeBuilder, RuntimeError, RUNTIME_LIVE};+ use crate::harness::workspace::ResolvedWorkspace;+ use crate::harness::{Provider, Workspace};+ use crate::Core;++ struct SessionStoreCleanup {+ installed: Option<Arc<dyn SessionStoreProvider>>,+ previous: Option<Arc<dyn SessionStoreProvider>>,+ }++ impl Drop for SessionStoreCleanup {+ fn drop(&mut self) {+ let Some(installed) = self.installed.take() else {+ return;+ };+ if openhuman_core::agent::session_store::clear_if(&installed) {+ openhuman_core::agent::session_store::restore(self.previous.take());+ }+ }+ }++ /// Releases [`RUNTIME_LIVE`] unless disarmed: held across+ /// [`RuntimeBuilder::build`]'s boot so a failed or cancelled build never+ /// leaves the process slot claimed.+ struct SlotClaim {+ armed: bool,+ }++ impl Drop for SlotClaim {+ fn drop(&mut self) {+ if self.armed {+ RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);+ log::debug!("[embed][runtime] build did not complete; process slot released");+ }+ }+ }++ impl RuntimeBuilder {+ /// Build the core and return a runtime ready to host agents.+ ///+ /// # Errors+ ///+ /// [`RuntimeError::AlreadyRunning`] if this process already has one;+ /// [`RuntimeError::BlankApiKey`] for an empty key;+ /// [`RuntimeError::Invalid`] for a knob the [`ConfigSource`] cannot+ /// honour or a refused controller extension.+ pub async fn build(self) -> Result<Runtime, RuntimeError> {+ // Claim the process slot before doing any work, so a losing racer+ // neither creates a temp dir nor half-initializes global state.+ if RUNTIME_LIVE.swap(true, std::sync::atomic::Ordering::AcqRel) {+ return Err(RuntimeError::AlreadyRunning);+ }+ // From here on every early return must release the slot, or a failed+ // build would permanently poison the process against retrying. The+ // claim is a drop guard rather than a match on the result so that a+ // *cancelled* build (the future dropped mid-boot, as the desktop+ // shell's startup timeout does to its server task) releases it too.+ let mut claim = SlotClaim { armed: true };+ let result = self.build_inner().await;+ if result.is_ok() {+ // The runtime's `CoreGuard` owns the slot from here.+ claim.armed = false;+ }+ result+ }++ /// Refuse combinations the chosen [`ConfigSource`] cannot honour.+ pub(super) fn validate(&self) -> Result<(), RuntimeError> {+ if self.api_key.as_ref().is_some_and(ApiKey::is_blank) {+ return Err(RuntimeError::BlankApiKey);+ }+ if matches!(self.workspace, Workspace::Stateless) && self.session_store.is_none() {+ return Err(RuntimeError::NoSessionStore);+ }+ if self.config_source == ConfigSource::Discovered {+ if !matches!(self.workspace, Workspace::Inherit) {+ return Err(RuntimeError::Invalid(+ "ConfigSource::Discovered needs Workspace::Inherit: the core discovers \+ the operator's install"+ .into(),+ ));+ }+ let edits = [+ ("config", self.config.is_some()),+ ("backend_url", self.backend_url.is_some()),+ ("workspace_dir", self.workspace_dir.is_some()),+ ("action_dir", self.action_dir.is_some()),+ ("api_key", self.api_key.is_some()),+ ];+ if let Some((knob, _)) = edits.iter().find(|(_, set)| *set) {+ return Err(RuntimeError::Invalid(format!(+ "`{knob}` edits the boot config, which ConfigSource::Discovered leaves \+ to the core; use ConfigSource::Resolved"+ )));+ }+ }+ Ok(())+ }++ async fn build_inner(mut self) -> Result<Runtime, RuntimeError> {+ self.validate()?;+ let discovered = self.config_source == ConfigSource::Discovered;+ let inherit = self.workspace.is_operator_owned();+ let resolved = ResolvedWorkspace::resolve(&self.workspace, self.action_dir.as_deref())+ .map_err(map_ws)?;++ // Discovered: the core loads its own config during boot; nothing to+ // assemble here. Resolved: `Inherit` starts from the operator's own+ // config — loaded here rather than left to the core to discover,+ // because the other knobs are applied *on top* of it.+ let mut config = if discovered {+ None+ } else {+ Some(self.resolve_config(&resolved).await?)+ };++ // The seams are the last fallible step before side effects a failed+ // build cannot undo (the stored API key, the host memory engine), so+ // a refused controller extension leaves neither behind. Restorable+ // seams are undone by this guard if the boot below fails.+ let mut seams = std::mem::take(&mut self.seams)+ .install()+ .map_err(RuntimeError::Invalid)?;++ // Before `CoreBuilder::build()`: the scheduler gate reads the credential+ // store exactly once, at boot, to decide whether it is signed in.+ let has_api_key = match (self.api_key.as_ref(), config.as_ref()) {+ (Some(key), Some(config)) => {+ store_api_key(config, key)?;+ true+ }+ _ => false,+ };++ // An endpoint without a model is deliberately ignored by the route+ // applicator, so host policy follows the effective behaviour: only a+ // *usable* runtime-default route exempts an inherited install from+ // its session gate. An API key is a credential in its own right.+ let routed_provider_effective = routed_provider_effective(&self.provider, config.as_ref());+ let host_kind = effective_host_kind(+ self.host_kind,+ inherit,+ routed_provider_effective || has_api_key,+ );++ let domains = self.domains.unwrap_or_else(default_domains);+ let tool_groups = self.tool_groups.clone().unwrap_or_default();+ let services = self.services.unwrap_or_else(default_services);++ if let Some(engine) = self.memory_engine.clone() {+ openhuman_core::memory::engine::install_host_engine(engine);+ }++ // Install only after all fallible workspace/config resolution has+ // completed; core boot performs recovery against this provider.+ let installed_session_store = self.session_store.clone();+ let previous_session_store = installed_session_store+ .clone()+ .and_then(openhuman_core::agent::session_store::install);+ let mut session_store_cleanup = SessionStoreCleanup {+ installed: installed_session_store,+ previous: previous_session_store,+ };++ log::debug!(+ "[embed][runtime] building host_kind={host_kind:?} config_source={:?} \+ inherit_workspace={inherit} routed_provider={} api_key={has_api_key} \+ domains={domains:?} services={services:?} tool_groups={tool_groups:?} \+ listen_host={:?} listen_port={:?}",+ self.config_source,+ self.provider.is_routed(),+ self.listen_host,+ self.listen_port,+ );++ let mut builder = CoreBuilder::new(host_kind)+ .domains(domains)+ .tool_groups(tool_groups.clone())+ .services(services)+ .token(std::mem::replace(+ &mut self.token,+ openhuman_core::core::runtime::TokenSource::EnvOrFile,+ ));+ if let Some(config) = config.clone() {+ builder = builder.config(config);+ }+ if let Some(host) = self.listen_host.take() {+ builder = builder.host(host);+ }+ if let Some(port) = self.listen_port {+ builder = builder.port(port);+ }+ if let Some(transport) = self.backend_transport.take() {+ builder = builder.backend_transport(transport);+ }+ let runtime = builder.build().await.map_err(|error| {+ log::warn!("[embed][runtime] core build failed: {error:#}");+ RuntimeError::Build(error)+ })?;+ let core = Core::from_runtime(Arc::new(runtime));++ // Discovered: agents start from the config the core just loaded.+ let (mut base_config, config_unavailable) = match config.take() {+ Some(config) => (config, None),+ None => discovered_base_config().await,+ };+ if discovered {+ // Agent defaults only — the core's own config is not edited.+ self.access.apply(&mut base_config);+ apply_provider(&mut base_config, &self.provider);+ }++ if seams.has_pending_live_policy() {+ seams.install_live_policy(&base_config.workspace_dir, &base_config.action_dir);+ }++ if let Some(session) = self.session.take() {+ core.auth().store(session).await?;+ }++ let installed_session_store = session_store_cleanup.installed.take();+ let previous_session_store = session_store_cleanup.previous.take();+ log::debug!("[embed][runtime] built host_kind={host_kind:?}");++ Ok(Runtime::new(+ core,+ resolved,+ installed_session_store,+ previous_session_store,+ Some(seams),+ base_config,+ config_unavailable,+ inherit,+ domains,+ tool_groups,+ self.provider,+ self.access,++ self.max_agents,+ ))+ }++ /// The config a [`ConfigSource::Resolved`] runtime hands the core.+ async fn resolve_config(+ &mut self,+ resolved: &ResolvedWorkspace,+ ) -> Result<Config, RuntimeError> {+ let mut config = match (&self.workspace, self.config.take()) {+ (Workspace::Inherit, Some(config)) => config,+ (Workspace::Inherit, None) => {+ Config::load_or_init().await.map_err(RuntimeError::Build)?+ }+ (_, supplied) => {+ let mut config = supplied.unwrap_or_default();+ config.workspace_dir = resolved.workspace_dir.clone();+ config.action_dir = resolved.action_dir.clone();+ // Credential state, auth profiles and the keyring file backend+ // all resolve against this path's parent, not `workspace_dir`.+ config.config_path = resolved.config_path.clone();+ config+ }+ };+ // Raw paths refine the resolved workspace field by field; the+ // credential root (`config_path`) is left to the `Workspace`.+ if let Some(dir) = self.workspace_dir.clone() {+ create_dir(&dir, "create the workspace_dir")?;+ log::debug!("[embed][runtime] workspace_dir override applied");+ config.workspace_dir = dir;+ }+ if let Some(dir) = self.action_dir.clone() {+ create_dir(&dir, "create the action_dir")?;+ log::debug!("[embed][runtime] action_dir override applied");+ config.action_dir = dir;+ }+ if let Some(url) = self.backend_url.clone() {+ config.api_url = Some(url);+ }+ self.access.apply(&mut config);+ apply_provider(&mut config, &self.provider);+ Ok(config)+ }+ }++ /// The base config for agents of a runtime whose core discovered its own:+ /// the same `load_or_init` the core just ran, so the two agree.+ ///+ /// When it fails the core has already booted without its workspace-bound+ /// stores. The runtime still comes up (a host that never creates an agent,+ /// like the desktop shell, keeps working), but the failure is returned with+ /// the placeholder config so [`Runtime::agent`] refuses instead of laying an+ /// agent out under the default root, a different workspace and credential+ /// store from the one the operator selected.+ async fn discovered_base_config() -> (Config, Option<String>) {+ match Config::load_or_init().await {+ Ok(config) => (config, None),+ Err(error) => {+ log::warn!(+ "[embed][runtime] discovered config failed to load; agents will be refused: {error:#}"+ );+ (Config::default(), Some(format!("{error:#}")))+ }+ }+ }++ /// Whether the runtime-default provider route would actually take effect. An+ /// endpoint without a model is deliberately ignored by the route applicator,+ /// so host policy follows the effective behaviour: only a usable route with a+ /// model exempts an inherited install from its session gate. A+ /// [`ConfigSource::Discovered`] build has no config yet (`None`), but the+ /// provider is applied to the agents' base config after boot, so it is judged+ /// by the model it carries itself.+ pub(crate) fn routed_provider_effective(provider: &Provider, config: Option<&Config>) -> bool {+ provider.has_usable_route()+ && match config {+ Some(config) => config.default_model.as_deref(),+ None => provider.model_id(),+ }+ .is_some_and(|model| !model.trim().is_empty())+ }++ fn store_api_key(config: &Config, key: &ApiKey) -> Result<(), RuntimeError> {+ let state_dir = config+ .config_path+ .parent()+ .map(Path::to_path_buf)+ .unwrap_or_else(|| config.config_path.clone());+ openhuman_core::security::credentials::api_key::store_api_key_in(+ &state_dir,+ config.secrets.encrypt,+ key.expose(),+ )+ .map(|_| ())+ .map_err(RuntimeError::Build)+ }++ fn create_dir(dir: &Path, what: &'static str) -> Result<(), RuntimeError> {+ std::fs::create_dir_all(dir).map_err(|source| RuntimeError::Workspace { what, source })+ }++ fn map_ws(err: crate::HarnessError) -> RuntimeError {+ match err {+ crate::HarnessError::Workspace { what, source } => RuntimeError::Workspace { what, source },+ crate::HarnessError::Invalid(msg) => RuntimeError::Invalid(msg),+ crate::HarnessError::Build(e) => RuntimeError::Build(e),+ crate::HarnessError::Call(e) => RuntimeError::Call(e),+ crate::HarnessError::AlreadyRunning => RuntimeError::AlreadyRunning,+ }+ }++ /// Preserve the installed application's authentication policy when the+ /// runtime borrows both its workspace and provider. `Library` means the host+ /// supplied inference (a route or an API key); it must not become a blanket+ /// way to bypass the session gate around an operator-installed provider.+ pub(crate) fn effective_host_kind(+ requested: HostKind,+ inherit_workspace: bool,+ host_supplied_credential: bool,+ ) -> HostKind {+ if requested == HostKind::Library && inherit_workspace && !host_supplied_credential {+ HostKind::Cli+ } else {+ requested+ }+ }++ /// Apply a [`Provider`]'s model to the config.+ ///+ /// Only the model: the *route* is a per-turn parameter, never a config write,+ /// because config routes persist. See the [`provider`](crate::harness::provider)+ /// module docs.+ pub(crate) fn apply_provider(config: &mut Config, provider: &Provider) {+ if let Some(model) = provider.model_id() {+ config.default_model = Some(model.to_string());+ }+ }diff --cc crates/openhuman-embed/src/runtime/builder.rsindex 64949b3b9c,e8d2c34d86..cf204415ce--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@@ -13,52 -21,73 +21,78 @@@ use openhuman_core::core::runtime::{Domuse openhuman_core::core::types::HostKind;use openhuman_core::tools::toolpacks::ToolGroups;- use openhuman_core::agent::session_store::SessionStoreProvider;-- use super::{ApiKey, Runtime, RuntimeError, RUNTIME_LIVE};- use crate::harness::workspace::ResolvedWorkspace;+ use super::seams::HostSeams;+ use super::ApiKey;use crate::harness::{Access, Provider, Workspace};- use crate::{Core, Session};+ use crate::Session;- struct SessionStoreCleanup {- installed: Option<Arc<dyn SessionStoreProvider>>,- previous: Option<Arc<dyn SessionStoreProvider>>,- }+ // Re-exported for the sibling test module and older call sites that reached+ // the default triples through this module.+ pub(crate) use super::build::apply_provider;+ #[cfg(test)]+ pub(crate) use super::build::{effective_host_kind, routed_provider_effective};+ #[cfg(test)]+ pub(crate) use super::presets::{default_domains, default_services};+ #[cfg(test)]+ pub(crate) use super::{RuntimeError, RUNTIME_LIVE};- impl Drop for SessionStoreCleanup {- fn drop(&mut self) {- let Some(installed) = self.installed.take() else {- return;- };- if openhuman_core::agent::session_store::clear_if(&installed) {- openhuman_core::agent::session_store::restore(self.previous.take());- }- }+ /// Who produces the [`Config`] the core boots with.+ ///+ /// The choice is not cosmetic. A config the core is *handed* makes it a+ /// scoped embedder: credentials live under that config's root, the operator's+ /// `active_user.toml` is never read or written, and handlers see that exact+ /// config for the life of the process. A config the core *discovers* is the+ /// operator's install, re-read from `config.toml` and the environment, with+ /// per-user activation — what the desktop app, the CLI and the TUI run.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+ pub enum ConfigSource {+ /// The builder resolves the config — from the [`Workspace`], a supplied+ /// [`RuntimeBuilder::config`], and the other knobs — and hands it to the+ /// core verbatim. The library default.+ #[default]+ Resolved,+ /// The core discovers its config itself, exactly as a desktop, CLI or TUI+ /// host does. Requires [`Workspace::Inherit`]; refuses the knobs that+ /// would edit a config (`config`, `backend_url`, `workspace_dir`,+ /// `action_dir`, `api_key`), because there is no config in hand to edit.+ /// [`RuntimeBuilder::access`] and [`RuntimeBuilder::provider`] then only+ /// set the defaults of agents created with [`Runtime::agent`](super::Runtime::agent).+ Discovered,}- /// Builder for a [`Runtime`]. Obtain with [`Runtime::builder`].+ /// Builder for a [`Runtime`](super::Runtime). Obtain with+ /// [`Runtime::builder`](super::Runtime::builder) or one of the host presets+ /// ([`RuntimeBuilder::library`], [`desktop`](RuntimeBuilder::desktop),+ /// [`cli`](RuntimeBuilder::cli), [`tui`](RuntimeBuilder::tui)).pub struct RuntimeBuilder {- workspace: Workspace,- provider: Provider,- access: Access,- services: Option<ServiceSet>,- domains: Option<DomainSet>,- tool_groups: Option<ToolGroups>,- host_kind: HostKind,- config: Option<Config>,- session: Option<Session>,- backend_url: Option<String>,- api_key: Option<ApiKey>,- backend_transport: Option<Arc<dyn BackendTransport>>,- memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,- session_store: Option<Arc<dyn SessionStoreProvider>>,- max_agents: usize,+ pub(super) workspace: Workspace,+ pub(super) workspace_dir: Option<PathBuf>,+ pub(super) action_dir: Option<PathBuf>,+ pub(super) config_source: ConfigSource,+ pub(super) provider: Provider,+ pub(super) access: Access,+ pub(super) services: Option<ServiceSet>,+ pub(super) domains: Option<DomainSet>,+ pub(super) tool_groups: Option<ToolGroups>,+ pub(super) host_kind: HostKind,+ pub(super) token: TokenSource,+ pub(super) listen_host: Option<String>,+ pub(super) listen_port: Option<u16>,+ pub(super) config: Option<Config>,+ pub(super) session: Option<Session>,+ pub(super) backend_url: Option<String>,+ pub(super) api_key: Option<ApiKey>,+ pub(super) backend_transport: Option<Arc<dyn BackendTransport>>,+ pub(super) memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,+ pub(super) session_store: Option<Arc<dyn SessionStoreProvider>>,+ pub(super) seams: HostSeams,++ pub(super) max_agents: usize,}+/// Live agents a runtime hosts unless [`RuntimeBuilder::max_agents`] says+/// otherwise.+pub const DEFAULT_MAX_AGENTS: usize = 1024;+impl Default for RuntimeBuilder {fn default() -> Self {Self::new()@@@ -85,7 -121,7 +126,8 @@@ impl RuntimeBuilderbackend_transport: None,memory_engine: None,session_store: None,+ seams: HostSeams::default(),+ max_agents: DEFAULT_MAX_AGENTS,}}@@@ -131,17 -168,11 +174,20 @@@self}+ /// The most agents this runtime hosts at once; [`Runtime::agent`]+ /// returns [`AgentError::AgentLimit`](crate::AgentError::AgentLimit)+ /// beyond it. Removed and dropped agents do not count. Defaults to+ /// [`DEFAULT_MAX_AGENTS`].+ pub fn max_agents(mut self, limit: usize) -> Self {+ self.max_agents = limit;+ self+ }+/// Where the runtime keeps its credential store, session database and/// every agent's memory, transcripts and skills.+ ///+ /// [`workspace_dir`](Self::workspace_dir) and+ /// [`action_dir`](Self::action_dir) refine the paths this resolves to.pub fn workspace(mut self, workspace: Workspace) -> Self {self.workspace = workspace;selfdiff --cc crates/openhuman-embed/src/runtime/mod.rsindex 184e6db58e,2eab94e084..62a15659b7--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@@ -67,12 -68,18 +67,20 @@@//! worker stack overflows.mod api_key;+ mod build;pub(crate) mod builder;+mod lifecycle;+ mod presets;+ mod run;+ mod seams;+ mod summary;pub use api_key::ApiKey;- pub use builder::RuntimeBuilder;+ pub use builder::{ConfigSource, RuntimeBuilder};+pub use lifecycle::RemoveAgent;+ pub use run::run_from_args;+ #[doc(hidden)]+ pub use summary::BuilderSummary;use std::collections::HashMap;use std::path::Path;diff --cc crates/openhuman-embed/src/turn.rsindex 36eb588639,c4137c248c..0f453a9b69--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@@ -585,42 -724,53 +725,56 @@@ async fn dispatch// inlined, and nesting it inside `Turn::send`'s own state machine// pushes rustc's layout query past its depth limit. One heap// allocation per turn is nothing next to the turn itself.- let turn: std::pin::Pin<- Box<dyn std::future::Future<Output = Result<String, CoreError>> + Send>,- > = Box::pin(async move {- use openhuman_core::inference::host_runtime::ops::{- agent_chat_for, AgentChatTarget,- };- let mut config = inner.config.clone();- let route = openhuman_core::config::schema::EphemeralRoute::from_params(- request.inference_url,- request.api_key,- );- let host = inner.composed_host_tools();- let target = AgentChatTarget::Definition {- definition: &inner.definition,- host: host.as_ref(),- seed: seed.as_deref(),- usage: Some(usage),- };- agent_chat_for(- &mut config,- target,- &request.message,- request.model_override,- request.temperature,- request.thread_id,- request.cwd,- route,- )- .await- .map(|outcome| outcome.value)- .map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))- });+ let turn: futures_box::BoxFuture<'_, Result<AgentReply, CoreError>> =+ Box::pin(async move {+ use openhuman_core::inference::host_runtime::ops::{+ agent_chat_for, AgentChatTarget,+ };+ let mut config = inner.config.clone();+ let route = openhuman_core::config::schema::EphemeralRoute::from_params(+ request.inference_url,+ request.api_key,+ );+ let host = inner.composed_host_tools();+ let target = AgentChatTarget::Definition {+ definition: &inner.definition,+ host: host.as_ref(),+ seed: seed.as_deref(),+ usage: Some(usage),+ host_only: inner.host_only,+ untrusted_input: options.untrusted_input,+ shape: Some(&options.shape),+ };+ let outcome = agent_chat_for(+ &mut config,+ target,+ &request.message,+ request.model_override,+ request.temperature,+ request.thread_id,+ request.cwd,+ route,+ )+ .await;+ // The session does not count reasoning tokens; the shape's+ // report does. Folded in before the meter or the outcome reads+ // the sink, on success and failure alike.+ let report = options.shape.report();+ if let Some(spent) = usage+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_mut()+ {+ spent.reasoning_tokens = report.reasoning_tokens;+ }+ outcome+ .map(|outcome| (outcome.value, Some(report)))+ .map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))+ });- runtime.run_in(ctx, turn).await+ agent+ .lifecycle+ .admit(&agent.id, AGENT_CHAT, runtime.run_in(ctx, turn))+ .await}}}diff --cc scripts/ci/check-openhuman-rust-layout.mjsindex 73b23eeac3,cf3c9a9005..67bb09c700--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@@ -43,21 -43,20 +43,20 @@@ const LEGACY_LIMIT_ENTRIES =// provider, security, memory, tool and prompt policy. Generic session// state moved to tinyagents-runtime; this remaining composition is split in// a follow-up without reintroducing an old harness/session exception.- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 986],+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 984],- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1309],- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1150],+ ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1306],- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1148],++ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1146],["crates/openhuman-core/src/tools/ops.rs", 1209],["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1304],// These established external test modules grew with upstream coverage. Pin// their current sizes while follow-up work separates their test concerns.// `core/` was pruned from the line limit by name until these pins; its// oversized files are pinned at the size they had when enforcement began.- ["crates/openhuman-core/src/core/all.rs", 1492],- ["crates/openhuman-core/src/core/all_tests.rs", 1632],+ ["crates/openhuman-core/src/core/all.rs", 1355],+ ["crates/openhuman-core/src/core/all_tests.rs", 1533],["crates/openhuman-core/src/core/events.rs", 1808],- ["crates/openhuman-core/src/core/events_tests.rs", 1003],+ ["crates/openhuman-core/src/core/events_tests.rs", 997],["crates/openhuman-core/src/core/observability.rs", 3502],- ["crates/openhuman-core/src/core/runtime/builder.rs", 813],];const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);