The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(agent): replace registry current() with global() and drop searches_connected_mcp
Steven Enamakele1cbc932767c
diff --git a/crates/openhuman-core/src/agent/bus.rs b/crates/openhuman-core/src/agent/bus.rsindex c18f3842ab..000d4242f9 100644--- a/crates/openhuman-core/src/agent/bus.rs+++ b/crates/openhuman-core/src/agent/bus.rs@@ -272,10 +272,8 @@ async fn handle_agent_run_turn(req: AgentTurnRequest) -> Result<AgentTurnRespons// the bus without bootstrapping definitions).let sandbox_mode = target_agent_id.as_deref()- .and_then(|id| {- AgentDefinitionRegistry::current()- .and_then(|reg| reg.get(id).map(|def| def.sandbox_mode))- })+ .and_then(|id| AgentDefinitionRegistry::global().and_then(|reg| reg.get(id)))+ .map(|def| def.sandbox_mode).unwrap_or(SandboxMode::None);// Scope the caller-supplied origin around the tool loop sodiff --git a/crates/openhuman-core/src/agent/debug/mod.rs b/crates/openhuman-core/src/agent/debug/mod.rsindex 9e2e20eace..19df0b49f9 100644--- a/crates/openhuman-core/src/agent/debug/mod.rs+++ b/crates/openhuman-core/src/agent/debug/mod.rs@@ -119,7 +119,7 @@ pub async fn dump_all_agent_prompts(AgentDefinitionRegistry::init_global(&config.workspace_dir).context("initialising AgentDefinitionRegistry for prompt dump")?;- let registry = AgentDefinitionRegistry::current()+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| anyhow!("AgentDefinitionRegistry missing after init"))?;let ids: Vec<String> = registrydiff --git a/crates/openhuman-core/src/agent/harness/builtin_definitions.rs b/crates/openhuman-core/src/agent/harness/builtin_definitions.rsindex 5fc645ff06..1d68a69aff 100644--- a/crates/openhuman-core/src/agent/harness/builtin_definitions.rs+++ b/crates/openhuman-core/src/agent/harness/builtin_definitions.rs@@ -80,7 +80,6 @@ pub(crate) fn test_main_def() -> AgentDefinition {],delegate_name: None,agent_tier: AgentTier::Chat,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}@@ -123,7 +122,6 @@ pub(crate) fn test_inherit_echo_def() -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}@@ -162,7 +160,6 @@ pub(crate) fn test_inherit_parallel_worker_def() -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rsindex c3e27dbbf7..ca712b51b5 100644--- a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs+++ b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs@@ -233,12 +233,6 @@ pub struct AgentDefinition {#[serde(default)]pub agent_tier: AgentTier,- /// Whether this agent's turns can search and call the tools of every- /// connected MCP server (deferred, through `tool_search`). Set for the- /// user-facing orchestrator; specialists reach MCP only through it.- #[serde(default)]- pub searches_connected_mcp: bool,-// ── source bookkeeping ──────────────────────────────────────────────/// Tracks where the definition was loaded from (Builtin vs. File).#[serde(skip)]diff --git a/crates/openhuman-core/src/agent/harness/definition/registry.rs b/crates/openhuman-core/src/agent/harness/definition/registry.rsindex 0355f88481..460f2e4258 100644--- a/crates/openhuman-core/src/agent/harness/definition/registry.rs+++ b/crates/openhuman-core/src/agent/harness/definition/registry.rs@@ -151,29 +151,4 @@ impl AgentDefinitionRegistry {pub fn global_arc() -> Option<Arc<Self>> {GLOBAL.get().cloned()}-- /// The catalogue sub-agent lookups resolve through: the ambient agent- /// context's own registry when it carries one, else the process registry.- pub fn current() -> Option<Arc<Self>> {- crate::core::runtime::CoreContext::current()- .and_then(|ctx| ctx.definitions())- .or_else(Self::global_arc)- }-- /// A copy of this registry with `definitions` added, replacing any- /// definition with the same id.- pub fn with_definitions(&self, definitions: impl IntoIterator<Item = AgentDefinition>) -> Self {- let mut registry = Self::default();- for definition in self.list() {- registry.insert(definition.clone());- }- for definition in definitions {- registry.insert(definition);- }- registry- }}--#[cfg(test)]-#[path = "registry_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/definition_tests.rs b/crates/openhuman-core/src/agent/harness/definition_tests.rsindex a28b3cae28..0ad1163d93 100644--- a/crates/openhuman-core/src/agent/harness/definition_tests.rs+++ b/crates/openhuman-core/src/agent/harness/definition_tests.rs@@ -28,7 +28,6 @@ fn make_def(id: &str) -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/library/ops.rs b/crates/openhuman-core/src/agent/library/ops.rsindex 92a89073d2..2879b7c5ba 100644--- a/crates/openhuman-core/src/agent/library/ops.rs+++ b/crates/openhuman-core/src/agent/library/ops.rs@@ -13,7 +13,7 @@ pub async fn list_definition_metadata() -> Result<Vec<AgentDefinitionDisplay>, SAgentDefinitionRegistry::init_global(&config.workspace_dir).map_err(|e| format!("failed to initialise AgentDefinitionRegistry: {e}"))?;}- let registry = AgentDefinitionRegistry::current()+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| "AgentDefinitionRegistry not initialised".to_string())?;let definitions = registry.list()diff --git a/crates/openhuman-core/src/agent/library/ops_tests.rs b/crates/openhuman-core/src/agent/library/ops_tests.rsindex 62c7059d5e..76dcc628c2 100644--- a/crates/openhuman-core/src/agent/library/ops_tests.rs+++ b/crates/openhuman-core/src/agent/library/ops_tests.rs@@ -34,7 +34,6 @@ fn definition() -> AgentDefinition {],delegate_name: None,agent_tier: AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rsindex 877911a5f2..19e5190401 100644--- a/crates/openhuman-core/src/agent/multimodal.rs+++ b/crates/openhuman-core/src/agent/multimodal.rs@@ -125,7 +125,7 @@ impl TextExtractor for DocumentsTextExtractor {use crate::modules::documents;match tokio::time::timeout(PDF_EXTRACTION_TIMEOUT, async {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::Config::load_or_init().await.map_err(|error| format!("config unavailable for pdf extraction: {error}"))?;documents::extract_text(&config, bytes)diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rsindex f22182cc0a..141049422b 100644--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs@@ -179,7 +179,7 @@ pub async fn start_member_run(// worker keeps the label the approval gate needs. Inherit-only: no origin// in scope means the worker stays unlabelled and fails closed as before.let inherited_origin = crate::agent::turn_origin::capture();- crate::core::runtime::spawn_scoped(async move {+ tokio::spawn(async move {crate::agent::turn_origin::with_inherited_origin(inherited_origin,run_member_loop(diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rsindex 9b6c44d0c8..2b2b377b91 100644--- a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs+++ b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs@@ -147,11 +147,9 @@ fn handle_agent_work_control(params: Map<String, Value>) -> ControllerFuture {/// Resolve an agent id to its registry display name, if the registry is up and/// the agent is known. Returns `None` otherwise (e.g. custom/removed agents).fn resolve_display_name(agent_id: &str) -> Option<String> {- AgentDefinitionRegistry::current().and_then(|registry| {- registry- .get(agent_id)- .map(|definition| definition.display_name().to_string())- })+ AgentDefinitionRegistry::global()+ .and_then(|registry| registry.get(agent_id))+ .map(|definition| definition.display_name().to_string())}fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {diff --git a/crates/openhuman-core/src/agent/orchestration/fleet_tools.rs b/crates/openhuman-core/src/agent/orchestration/fleet_tools.rsindex b4e34920da..1d01d9f9e7 100644--- a/crates/openhuman-core/src/agent/orchestration/fleet_tools.rs+++ b/crates/openhuman-core/src/agent/orchestration/fleet_tools.rs@@ -44,7 +44,7 @@ impl FleetToolSet {/// Resolve the set for `agent_definition_id` from the global registry.pub(crate) fn for_parent(agent_definition_id: &str) -> Self {- let Some(registry) = AgentDefinitionRegistry::current() else {+ let Some(registry) = AgentDefinitionRegistry::global() else {return Self::all();};let Some(definition) = registry.get(agent_definition_id) else {diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rsindex bdff6d130e..4c77048854 100644--- a/crates/openhuman-core/src/agent/orchestration/ops.rs+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs@@ -338,8 +338,9 @@ impl AgentOrchestrationSession {let progress_sink = parent.on_progress.clone();if let Some(progress) = progress_sink.clone() {- let resolved_display_name = AgentDefinitionRegistry::current()- .and_then(|reg| reg.get(&agent_id).map(|def| def.display_name().to_string()));+ let resolved_display_name = AgentDefinitionRegistry::global()+ .and_then(|reg| reg.get(&agent_id))+ .map(|def| def.display_name().to_string());let _ = progress.send(AgentProgress::SubagentSpawned {agent_id: agent_id.clone(),@@ -663,7 +664,7 @@ fn resolve_definition(request: &SpawnAgentRequest) -> Result<AgentDefinition, Orreturn Err(OrchestrationError::InvalidSpawnRequest);}let registry =- AgentDefinitionRegistry::current().ok_or(OrchestrationError::RegistryUnavailable)?;+ AgentDefinitionRegistry::global().ok_or(OrchestrationError::RegistryUnavailable)?;registry.get(agent_id).cloned()diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rsindex 8349ea765f..63a5fd7390 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs@@ -47,7 +47,7 @@ pub(crate) async fn run_spawn_parallel_tasks_with_cancellation_and_workspace(max_parallel,"[spawn_parallel_agents] validated_parent_context");- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(registry) => registry,None => {tracing::debug!("[spawn_parallel_agents] registry_unavailable");@@ -62,7 +62,7 @@ pub(crate) async fn run_spawn_parallel_tasks_with_cancellation_and_workspace(let progress_sink = parent.on_progress.clone();let action_root =resolve_spawn_parallel_action_root(parent_workspace_descriptor.as_ref()).await;- let definitions = snapshot_agent_definitions(®istry);+ let definitions = snapshot_agent_definitions(registry);if cancel.is_cancelled() {return Ok(SpawnParallelGraphOutcome::Cancelled("spawn_parallel_agents cancelled at validate".to_string(),diff --git a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rsindex 04255ca5c8..a14e87b74d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs@@ -372,7 +372,7 @@ impl ContinueSubagentTool {}// Look up the agent definition- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(reg) => reg,None => {return Ok(ToolResult::error(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rsindex d795c944c9..0208746795 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs@@ -12,6 +12,7 @@use crate::agent::harness::definition::AgentDefinitionRegistry;use crate::agent::orchestration::delegation::run_subagent_delegation_with_parent_context;+use crate::config::Config;use async_trait::async_trait;use serde_json::json;use std::sync::Arc;@@ -110,7 +111,7 @@ impl Tool for DelegateGraphTool {}fn parameters_schema(&self) -> serde_json::Value {- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::global().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();@@ -211,7 +212,7 @@ impl DelegateGraphTool {.map(|n| (n as usize).min(MAX_MAX_REVISIONS)).unwrap_or(DEFAULT_MAX_REVISIONS);- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(reg) => reg,None => {return Ok(ToolResult::error(@@ -228,7 +229,7 @@ impl DelegateGraphTool {}};- let config = match crate::config::ops::load_current_or_init().await {+ let config = match Config::load_or_init().await {Ok(cfg) => Arc::new(cfg),Err(e) => {return Ok(ToolResult::error(format!(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rsindex 357e2d3744..e1c09cac96 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs@@ -48,7 +48,7 @@ impl DelegationDispatch {// `delegate_graph` is a concrete durable graph tool with its own// typed dispatcher, and arbitrary `delegate_*` tools must not be// mistaken for an agent target merely because of their spelling.- name if AgentDefinitionRegistry::current().is_some_and(|registry| {+ name if AgentDefinitionRegistry::global().is_some_and(|registry| {registry.list().into_iter().any(|definition| {definition.delegate_name@@ -102,7 +102,7 @@ impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for D.await}DelegationDispatchKind::Archetype => {- let Some(agent_id) = AgentDefinitionRegistry::current().and_then(|registry| {+ let Some(agent_id) = AgentDefinitionRegistry::global().and_then(|registry| {registry.list().into_iter().find_map(|definition| {let name = definition.delegate_name@@ -163,7 +163,7 @@ pub(crate) async fn dispatch_subagent_with_live_parent(let parent_workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned()).or_else(|| run_context.workspace.clone());- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(reg) => reg,None => {return Ok(ToolResult::error(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rsindex 6c3cdc93de..5dde5cba7d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs@@ -168,7 +168,7 @@ impl Tool for SpawnAsyncSubagentTool {let agent_ids: Vec<String> = if scoped {self.advertised_ids.clone()} else {- AgentDefinitionRegistry::current()+ AgentDefinitionRegistry::global().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default()};diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rsindex 5006e5c60b..1418abf888 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs@@ -46,7 +46,7 @@ impl SpawnAsyncSubagentTool {}};- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(registry) => registry,None => {return Ok(ToolResult::error(@@ -141,7 +141,7 @@ impl SpawnAsyncSubagentTool {workspace.root.clone()}).or_else(|| {- crate::security::live_policy::effective().map(|policy| policy.action_dir.clone())+ crate::security::live_policy::current().map(|policy| policy.action_dir.clone())});let selector = SubagentSessionSelector {parent_session: parent_session.clone(),diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rsindex 17c7a79218..2b5e5fbcdb 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs@@ -168,7 +168,7 @@ impl Tool for SpawnParallelAgentsTool {}fn parameters_schema(&self) -> serde_json::Value {- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::global().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();let agent_id_schema = if agent_ids.is_empty() {diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rsindex 16c98ada2f..050ccd6cd7 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs@@ -170,7 +170,6 @@ fn definition_with_tool_scope(subagents: Vec::new(),delegate_name: None,agent_tier: AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_parameters.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_parameters.rsindex 9f0a1a6cac..a8d9d59b15 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_parameters.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_parameters.rs@@ -16,7 +16,7 @@ fn spawn_subagent_parameters_schema() -> serde_json::Value {// Build the agent_id enum dynamically from the global registry// when it's been initialised. Falls back to a string-with-hint// when the registry hasn't been set up yet (e.g. early tests).- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::global().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rsindex 3180ef9023..f51aece529 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs@@ -131,7 +131,7 @@ impl SpawnSubagentTool {if prompt.is_empty() {return Ok(ToolResult::error("spawn_subagent: `prompt` is required"));}- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(reg) => reg,None => {return Ok(ToolResult::error(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rsindex 7980043627..58f4a3eee7 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs@@ -88,7 +88,7 @@ impl Tool for SpawnWorkerThreadTool {}fn parameters_schema(&self) -> serde_json::Value {- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::global().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();@@ -269,7 +269,7 @@ impl SpawnWorkerThreadTool {}}- let registry = AgentDefinitionRegistry::current()+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| anyhow::anyhow!("AgentDefinitionRegistry not initialised"))?;let definition = registrydiff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rsindex d16a303246..4ce684d3ba 100644--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs@@ -68,8 +68,8 @@ pub async fn start_workflow_run(// sub-agents whose tool calls the approval gate judges by that label.// Inherit-only: `None` leaves the loop unlabelled and failing closed.let inherited_origin = crate::agent::turn_origin::capture();- crate::core::runtime::spawn_scoped(async move {- match crate::config::ops::load_current_or_init().await {+ tokio::spawn(async move {+ match Config::load_or_init().await {Ok(task_config) => {crate::agent::turn_origin::with_inherited_origin(inherited_origin,@@ -208,8 +208,8 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu// Same inherit-only origin propagation as `start_workflow_run`: the resumed// loop runs on a fresh task, which would otherwise drop the caller's label.let inherited_origin = crate::agent::turn_origin::capture();- crate::core::runtime::spawn_scoped(async move {- match crate::config::ops::load_current_or_init().await {+ tokio::spawn(async move {+ match Config::load_or_init().await {Ok(task_config) => {crate::agent::turn_origin::with_inherited_origin(inherited_origin,diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rsindex 82e4361095..c5e80a08e4 100644--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs@@ -68,7 +68,7 @@ impl OpenHumanWorkflowExecutor {fn admit_child(&self, agent_id: &str) -> Result<(), OrchestrationError> {match self.safety_tier {WorkflowSafetyTier::ReadOnly => {- let registry = AgentDefinitionRegistry::current().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| {OrchestrationError("workflow safety admission requires the agent registry".to_owned(),)diff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.toml b/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.tomlindex a55d436b70..347d6c06b9 100644--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.toml+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.toml@@ -14,8 +14,6 @@ sandbox_mode = "sandboxed"# Loader enforces: a `chat` agent must NOT list any other `chat` agent# in `subagents` below — handoff goes directly to `worker` specialists. See `AgentTier` in `crates/openhuman-core/src/agent/harness/definition.rs`.agent_tier = "chat"-# Connected MCP servers' tools join this agent's deferred catalogue.-searches_connected_mcp = true# Identity now loads from the workspace rather than from this agent's compiled# prompt (#5701). `IdentitySection` injects SOUL.md (product persona, shared by# every agent that opts in) and ROLE.md (this agent's own role brief, which useddiff --git a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rsindex 56713425bf..db153a9621 100644--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs@@ -153,13 +153,13 @@ fn render_withheld_specialists(ctx: &PromptContext<'_>) -> String {);return String::new();}- let Some(registry) = AgentDefinitionRegistry::current() else {+ let Some(registry) = AgentDefinitionRegistry::global() else {tracing::debug!("[orchestrator-prompt] no agent registry; withheld-specialist section omitted");return String::new();};- let Some(definition) = resolve_definition(®istry, ctx.agent_id) else {+ let Some(definition) = resolve_definition(registry, ctx.agent_id) else {tracing::debug!(agent = ctx.agent_id,"[orchestrator-prompt] agent id does not resolve to a registry entry"@@ -237,8 +237,8 @@ fn render_withheld_specialists(ctx: &PromptContext<'_>) -> String {/// visible set exactly like [`render_withheld_specialists`], never hand-written,/// so a pack or allowlist change moves the prose with it (#6302).fn hand_off_route(ctx: &PromptContext<'_>, specialist: &str) -> Option<String> {- let registry = AgentDefinitionRegistry::current()?;- let definition = resolve_definition(®istry, ctx.agent_id)?;+ let registry = AgentDefinitionRegistry::global()?;+ let definition = resolve_definition(registry, ctx.agent_id)?;let listed = definition.subagents.iter()@@ -297,10 +297,10 @@ fn run_workflow_route(ctx: &PromptContext<'_>) -> Option<String> {/// is callable for an agent only when its belt mentions one of the pack's tools.fn belt_lists(ctx: &PromptContext<'_>, tool: &str) -> bool {use crate::agent::harness::definition::ToolScope;- let Some(registry) = AgentDefinitionRegistry::current() else {+ let Some(registry) = AgentDefinitionRegistry::global() else {return false;};- let Some(definition) = resolve_definition(®istry, ctx.agent_id) else {+ let Some(definition) = resolve_definition(registry, ctx.agent_id) else {return false;};match &definition.tools {diff --git a/crates/openhuman-core/src/agent/registry/defaults.rs b/crates/openhuman-core/src/agent/registry/defaults.rsindex 27d71607e0..a8c5dce3f2 100644--- a/crates/openhuman-core/src/agent/registry/defaults.rs+++ b/crates/openhuman-core/src/agent/registry/defaults.rs@@ -113,7 +113,6 @@ pub fn definition_from_registry_entry(entry: &AgentRegistryEntry) -> AgentDefini.collect(),delegate_name: None,agent_tier: AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::CustomRegistry,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/schemas.rs b/crates/openhuman-core/src/agent/schemas.rsindex 2d242c8085..5a2c7b13e7 100644--- a/crates/openhuman-core/src/agent/schemas.rs+++ b/crates/openhuman-core/src/agent/schemas.rs@@ -318,7 +318,7 @@ struct GetDefinitionParams {fn handle_get_definition(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let p = deserialize_params::<GetDefinitionParams>(params)?;- let registry = crate::agent::harness::AgentDefinitionRegistry::current()+ let registry = crate::agent::harness::AgentDefinitionRegistry::global().ok_or_else(|| "AgentDefinitionRegistry not initialised".to_string())?;match registry.get(p.id.trim()) {Some(def) => Ok(serde_json::json!({ "definition": def })),diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rsindex d8cc248d40..86b8541323 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs@@ -356,12 +356,12 @@ impl SessionHostBuilder {let hosted_config = Arc::new(hosted_config);#[cfg(test)]let definitions = Some(- crate::agent::harness::AgentDefinitionRegistry::current().unwrap_or_else(|| {+ crate::agent::harness::AgentDefinitionRegistry::global_arc().unwrap_or_else(|| {Arc::new(crate::agent::harness::AgentDefinitionRegistry::builtins_only())}),);#[cfg(not(test))]- let definitions = crate::agent::harness::AgentDefinitionRegistry::current();+ let definitions = crate::agent::harness::AgentDefinitionRegistry::global_arc();// A caller that brought its own definition is the authority for this// session, so it does not need a process registry to exist before it// may run a turn. The stand-in is deliberately *empty* rather thandiff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rsindex a50fd418eb..641dd53ed7 100644--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@ -112,7 +112,7 @@ impl OpenHumanSessionHost {}/// Build a session agent from a definition the caller already holds,- /// rather than an id resolved through `AgentDefinitionRegistry::current()`+ /// rather than an id resolved through `AgentDefinitionRegistry::global()`/// or `config.agent_registry`.////// The definition is authoritative for this agent's prompt, tool scope,@@ -428,7 +428,7 @@ impl OpenHumanSessionHost {Option<std::collections::HashSet<String>>,) = match (target_def,- crate::agent::harness::definition::AgentDefinitionRegistry::current(),+ crate::agent::harness::definition::AgentDefinitionRegistry::global(),) {// Host-only: no delegation; the host's names join an empty belt._ if host_only => (Vec::new(), Some(super::host_only::empty_belt())),@@ -436,7 +436,7 @@ impl OpenHumanSessionHost {let synthed = if should_synthesize_delegation_tools(def) {tools::orchestrator_tools::collect_orchestrator_tools(def,- ®,+ reg,prewarmed_integrations_slice,)} else {@@ -499,7 +499,7 @@ impl OpenHumanSessionHost {let synthed = match reg.get("orchestrator") {Some(orch_def) => tools::orchestrator_tools::collect_orchestrator_tools(orch_def,- ®,+ reg,prewarmed_integrations_slice,),None => {@@ -518,7 +518,7 @@ impl OpenHumanSessionHost {// existed, or — the common case today — a `CustomRegistry`// definition `resolve_target_definition` synthesizes// straight from `config.agent_registry.entries` without- // ever consulting `AgentDefinitionRegistry::current()`, see+ // ever consulting `AgentDefinitionRegistry::global()`, see// `agent_registry::find_custom_in_config`). Delegation-tool// synthesis needs the registry (to resolve named// subagents), so it's skipped here, but `def.tools` is a@@ -710,7 +710,7 @@ impl OpenHumanSessionHost {let payload_summarizer: Option<std::sync::Arc<dyn crate::agent::tinyagents::payload_summarizer::PayloadSummarizer>,> = if !host_only && super::summarizes_tool_output(agent_id, config) {- match crate::agent::harness::definition::AgentDefinitionRegistry::current() {+ match crate::agent::harness::definition::AgentDefinitionRegistry::global() {Some(reg) => match reg.get("summarizer") {Some(summarizer_def) => {log::info!(@@ -830,7 +830,7 @@ impl OpenHumanSessionHost {// second resident copy of a 95-field struct with nested `Vec`s// (openhuman#6218).agent.runtime_config = Some(Arc::clone(&base_config));- agent.hosted_base = AgentDefinitionRegistry::current().map(|definitions| {+ agent.hosted_base = AgentDefinitionRegistry::global_arc().map(|definitions| {Arc::new(crate::agent::tinyagents::host::OpenHumanHostBase {config: Arc::clone(&base_config),definitions,@@ -884,9 +884,9 @@ fn resolve_target_definition(config: &Config,agent_id: &str,) -> Result<Option<crate::agent::harness::definition::AgentDefinition>> {- let registry = AgentDefinitionRegistry::current();+ let registry = AgentDefinitionRegistry::global();- if let Some(reg) = registry.as_deref() {+ if let Some(reg) = registry {if let Some(def) = reg.get(agent_id) {return Ok(Some(def.clone()));}diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rsindex da250aca38..4aeae07382 100644--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs@@ -278,7 +278,7 @@ pub(super) fn should_synthesize_delegation_tools(def: &AgentDefinition) -> bool/// the name extends at an `_` boundary. Empty when the registry is not up or/// the id resolves to nothing, which leaves the schema untouched.fn allowed_subagent_ids_for(agent_id: &str) -> Vec<String> {- let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::current() else {+ let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::global() else {return Vec::new();};let definition = registry.get(agent_id).or_else(|| {diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rsindex a08264b002..0d5de02e76 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -10,25 +10,6 @@ use tinyagents_runtime::ToolSnapshot;use super::OpenHumanTurnPrelude;impl OpenHumanTurnPrelude {- /// The session's own definition, else the catalogue's entry for its id.- pub(super) fn session_definition(- &self,- registry: &crate::agent::harness::definition::AgentDefinitionRegistry,- ) -> Option<crate::agent::harness::definition::AgentDefinition> {- let definition = self- .definition- .as_deref()- .cloned()- .or_else(|| registry.get(&self.agent_definition_id).cloned());- if definition.is_none() {- tracing::trace!(- agent = %self.agent_definition_id,- "[session] no definition resolved; delegation surface unchanged"- );- }- definition- }-/// Takes the declarations the tinyagents session restored for this/// thread. Called before the boundary refresh so the rebuilt surface can/// include them.@@ -176,15 +157,7 @@ impl OpenHumanTurnPrelude {/// Called before the tool-surface lock is taken to keep lock order stable.#[cfg(feature = "mcp")]pub(super) fn collect_mcp_search_tools(&self) -> Vec<Box<dyn tinytools::Tool>> {- if !self- .definition- .as_ref()- .is_some_and(|definition| definition.searches_connected_mcp)- {- tracing::trace!(- agent = %self.agent_definition_id,- "[mcp] agent does not search connected MCP tools"- );+ if self.agent_definition_id != "orchestrator" {return Vec::new();}let Some(config) = self.runtime_config.as_ref() else {@@ -218,7 +191,7 @@ impl OpenHumanTurnPrelude {}let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::ops::load_current_or_init()+ None => crate::config::Config::load_or_init().await.ok().map(Arc::new),@@ -267,7 +240,7 @@ impl OpenHumanTurnPrelude {let skills_changed = self.drain_host_events();let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::ops::load_current_or_init()+ None => crate::config::Config::load_or_init().await.ok().map(Arc::new),diff --git a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rsindex 6c2a9e6363..7a2a7cac75 100644--- a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs@@ -141,7 +141,7 @@ impl OpenHumanSessionHost {/// the factory had one, else the process registry's entry for/// `agent_definition_id`.///- /// Prefer this over a bare `AgentDefinitionRegistry::current().get(..)` in+ /// Prefer this over a bare `AgentDefinitionRegistry::global().get(..)` in/// turn-path code that needs the agent's *own* settings (`sandbox_mode`,/// `subagents`): a session built from an explicit definition must not have/// them replaced by a same-id registry entry.@@ -149,8 +149,9 @@ impl OpenHumanSessionHost {&self,) -> Option<Arc<crate::agent::harness::definition::AgentDefinition>> {self.definition.clone().or_else(|| {- crate::agent::harness::definition::AgentDefinitionRegistry::current()- .and_then(|registry| registry.get(&self.agent_definition_id).cloned())+ crate::agent::harness::definition::AgentDefinitionRegistry::global()+ .and_then(|registry| registry.get(&self.agent_definition_id))+ .cloned().map(Arc::new)})}diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex ced685c839..5afbd5828b 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -94,7 +94,6 @@ struct OpenHumanTurnPrelude {Option<Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>>,allowed_subagent_ids: std::collections::HashSet<String>,sandbox_mode: crate::agent::harness::definition::SandboxMode,- definition: Option<Arc<crate::agent::harness::definition::AgentDefinition>>,runtime_config: Option<Arc<crate::config::Config>>,/// This session's tool-rule layers; see `tool_rules.rs`.tool_rules: Arc<tinytools::ToolRuleSet>,@@ -352,18 +351,19 @@ impl OpenHumanTurnPrelude {}/// Rebuild every delegation-dependent tool view from the current cached- /// integration set, replacing rather than appending. A revoked delegate is- /// removed from the executable source, schema, and policy together before- /// this request is prepared.+ /// integration set. This mirrors the legacy refresh's replace-not-append+ /// semantics, but keeps the mutable authority in hook state rather than a+ /// second turn loop. A revoked delegate is removed from the executable+ /// source, schema, and policy together before this request is prepared.fn refresh_delegation_tool_surface(&self) -> anyhow::Result<()> {use crate::agent::harness::definition::AgentDefinitionRegistry;use crate::tools::agent_policy::ToolPolicyEngine;use crate::tools::orchestrator_tools::collect_orchestrator_tools;- let Some(registry) = AgentDefinitionRegistry::current() else {+ let Some(registry) = AgentDefinitionRegistry::global() else {return Ok(());};- let Some(definition) = self.session_definition(®istry) else {+ let Some(definition) = registry.get(&self.agent_definition_id).cloned() else {return Ok(());};if definition.subagents.is_empty() {@@ -385,7 +385,7 @@ impl OpenHumanTurnPrelude {.tool_surface.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- let mut collected = collect_orchestrator_tools(&definition, ®istry, &integrations);+ let mut collected = collect_orchestrator_tools(&definition, registry, &integrations);#[cfg(feature = "mcp")]collected.extend(mcp_tools);let rebuilt = self.rebuilt_recorded_tools(@@ -1008,7 +1008,6 @@ impl OpenHumanSessionHost {.resolved_definition().map(|definition| definition.sandbox_mode).unwrap_or(crate::agent::harness::definition::SandboxMode::None),- definition: self.resolved_definition(),runtime_config: self.runtime_config.clone(),tool_rules: self.session_tool_rules(),tool_surface: Arc::new(std::sync::Mutex::new(OpenHumanTurnToolSurface {diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rsindex ce423d758b..5bd6ae37cc 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs@@ -178,7 +178,7 @@ impl OpenHumanTurnPrelude {return;};let prelude = self.clone();- crate::core::runtime::spawn_scoped(async move {+ tokio::spawn(async move {let Some(config) = prelude.memory_config().await else {return;};diff --git a/crates/openhuman-core/src/agent/session_host/turn/tools.rs b/crates/openhuman-core/src/agent/session_host/turn/tools.rsindex 5e3a0948b0..e55a00975e 100644--- a/crates/openhuman-core/src/agent/session_host/turn/tools.rs+++ b/crates/openhuman-core/src/agent/session_host/turn/tools.rs@@ -103,7 +103,7 @@ impl OpenHumanSessionHost {use crate::agent::harness::definition::AgentDefinitionRegistry;use crate::tools::orchestrator_tools::collect_orchestrator_tools;- let Some(reg) = AgentDefinitionRegistry::current() else {+ let Some(reg) = AgentDefinitionRegistry::global() else {// No registry — there's nothing we can do until the// registry is initialised. The agent's surface stays at// whatever the builder produced.@@ -125,7 +125,7 @@ impl OpenHumanSessionHost {// `retain` can never withdraw a durable tool's spec.let synthed = super::super::builder::drop_synthesized_name_collisions(&self.tools,- collect_orchestrator_tools(&def, ®, &self.connected_integrations),+ collect_orchestrator_tools(&def, reg, &self.connected_integrations),);let synthed_names: std::collections::HashSet<String> =synthed.iter().map(|t| t.name().to_string()).collect();diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rsindex de4e3cfb21..1dd6aca711 100644--- a/crates/openhuman-core/src/agent/session_import/live.rs+++ b/crates/openhuman-core/src/agent/session_import/live.rs@@ -99,7 +99,7 @@ pub async fn session_kv_store() -> Option<Arc<dyn Store>> {log::debug!("[session-store] registering the host session store's kv on RunContext.stores");return Some(stores.kv);}- let cfg = match crate::config::ops::load_current_or_init().await {+ let cfg = match crate::config::Config::load_or_init().await {Ok(cfg) => cfg,Err(err) => {log::warn!("[session-store] cannot resolve config for store registration: {err:#}");diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rsindex fddcdafd95..beea34f1f9 100644--- a/crates/openhuman-core/src/agent/session_store/mod.rs+++ b/crates/openhuman-core/src/agent/session_store/mod.rs@@ -16,11 +16,8 @@use std::sync::{Arc, LazyLock, PoisonError, RwLock};-pub use agent_transcripts::{agent_transcript_root, AgentTranscriptFiles};pub use tinyagents_session::port::{AgentStores, SessionStoreProvider};-mod agent_transcripts;-static PROVIDER: LazyLock<RwLock<Option<Arc<dyn SessionStoreProvider>>>> =LazyLock::new(|| RwLock::new(None));@@ -139,30 +136,12 @@ pub fn transcripts_or_files(workspace_dir: &std::path::Path,) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {transcripts_for(agent_id).unwrap_or_else(|| {- match crate::core::runtime::agent_scope::current_agent_id() {- Some(embedded) => {- log::debug!(- "[session_store] transcripts under the agent's directory agent={embedded}"- );- Arc::new(AgentTranscriptFiles::new(workspace_dir, &embedded))- }- None => Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(- workspace_dir,- )),- }+ Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(+ workspace_dir,+ ))})}-/// The workspace root transcripts are written under: the agent's own-/// directory under an embedded agent's context, else `workspace_dir`.-#[must_use]-pub fn transcript_root(workspace_dir: &std::path::Path) -> std::path::PathBuf {- match crate::core::runtime::agent_scope::current_agent_id() {- Some(agent) => agent_transcript_root(workspace_dir, &agent),- None => workspace_dir.to_path_buf(),- }-}-/// The stores of the agent the current [`CoreContext`] works for — the one/// it was derived for ([`CoreContext::session_agent`]), else/// [`DEFAULT_AGENT`] — or `None` when the core keeps the on-disk layout.diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rsindex 09629d9ec3..ed78d48610 100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs@@ -9,7 +9,7 @@ use std::{collections::HashMap,fs::OpenOptions,path::PathBuf,- sync::{Arc, Mutex},+ sync::{Arc, Mutex, OnceLock},};use async_trait::async_trait;@@ -130,7 +130,7 @@ pub struct OpenHumanSubagentHost {/// independently constructed host adapters. Durable persistence remains the/// cross-process authority; this prevents duplicate local child graphs.#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub(super) struct HostLifecycleKey {+struct HostLifecycleKey {checkpoint_dir: PathBuf,task_key: SubagentTaskKey,}@@ -212,8 +212,11 @@ fn host_observer_outcome(mut outcome: SubagentRunOutcome) -> SubagentRunOutcomeoutcome}-pub(super) fn host_in_flight() -> Arc<AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>>> {- crate::core::runtime::current_slot()+static HOST_IN_FLIGHT: OnceLock<AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>>> =+ OnceLock::new();++fn host_in_flight() -> &'static AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>> {+ HOST_IN_FLIGHT.get_or_init(|| AsyncMutex::new(HashMap::new()))}fn absolute_checkpoint_dir(path: PathBuf) -> PathBuf {@@ -301,7 +304,7 @@ impl OpenHumanSubagentHost {task_key: task_key.clone(),};let (entry, is_leader) = {- let mut entries = host_in_flight().lock_owned().await;+ let mut entries = host_in_flight().lock().await;match entries.get(&lifecycle_key) {Some(entry) => (entry.clone(), false),None => {@@ -339,7 +342,7 @@ impl OpenHumanSubagentHost {)).await;entry.complete(result.as_ref().ok().cloned()).await;- let mut entries = host_in_flight().lock_owned().await;+ let mut entries = host_in_flight().lock().await;if entries.get(&lifecycle_key).is_some_and(|current| Arc::ptr_eq(current, &entry))diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rsindex e230176aaf..25bd69fc2e 100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs@@ -4,8 +4,7 @@ use tinyagents_orchestration::subagent::{};use super::lifecycle::{- host_in_flight, load_subagent_checkpoint, merged_resume_history, HostInFlight,- OpenHumanPersistence,+ load_subagent_checkpoint, merged_resume_history, HostInFlight, OpenHumanPersistence,};use super::{SubagentMode, SubagentRunOutcome, SubagentRunStatus, SubagentUsage};@@ -320,21 +319,3 @@ async fn host_coalescer_keeps_the_leader_winner_and_cancels_only_the_observer()tinyagents_orchestration::subagent::SubagentPersistenceDisposition::TerminalExisting);}--#[tokio::test]-async fn each_agent_dedupes_its_own_in_flight_sub_agents() {- use crate::core::runtime::agent_scope::test_agent_context;- use crate::core::runtime::{context::CoreContext, DomainSet};- use std::sync::Arc;-- let root = CoreContext::for_test(DomainSet::full(), None);- let alpha = test_agent_context(&root, "alpha");- let beta = test_agent_context(&root, "beta");-- let alpha_map = CoreContext::scope(Arc::clone(&alpha), async { host_in_flight() }).await;- let beta_map = CoreContext::scope(beta, async { host_in_flight() }).await;- let alpha_again = CoreContext::scope(alpha, async { host_in_flight() }).await;-- assert!(!Arc::ptr_eq(&alpha_map, &beta_map));- assert!(Arc::ptr_eq(&alpha_map, &alpha_again));-}diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rsindex 8f267b6979..073f6002f3 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/transcript.rs@@ -56,8 +56,7 @@ pub(super) fn persist_subagent_transcript() {use tinyagents_session::transcript;- let root = crate::agent::session_store::transcript_root(workspace_dir);- let path = match transcript::resolve_keyed_transcript_path(&root, transcript_stem) {+ let path = match transcript::resolve_keyed_transcript_path(workspace_dir, transcript_stem) {Ok(p) => p,Err(err) => {tracing::debug!(diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 2eeb4a694c..3296d45879 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -280,10 +280,8 @@ pub(crate) async fn run_subagent_direct(// through that walk. Resolve the parent's tier from the registry by its// definition id; `tier_gate_decision` rejects (and logs) any forbidden// chat/reasoning hop while exempting unresolved + worker parents.- let parent_registry = AgentDefinitionRegistry::current();- let parent_def = parent_registry- .as_deref()- .and_then(|reg| reg.get(&parent.agent_definition_id));+ let parent_def =+ AgentDefinitionRegistry::global().and_then(|reg| reg.get(&parent.agent_definition_id));tier_gate_decision(parent_def, definition, &parent.agent_definition_id, &task_id)?;// Configured `subagentStart` hooks — the last gate before a spawn costs@@ -314,9 +312,15 @@ pub(crate) async fn run_subagent_direct(return Err(SubagentRunError::HookDenied(reason));}- // Loaded once per spawn (see `LoadedConfig`), after the tier gate so a- // rejected spawn never initialises config on first run.- let loaded_config: LoadedConfig = Box::pin(crate::config::ops::load_current_or_init())+ // Load the host config exactly once for this spawn and hand it to+ // everything below. See `LoadedConfig` — `load_or_init` re-reads+ // config.toml on every call, and the runtime below is slated to move+ // into TinyAgents, where there is no config file to load.+ //+ // Deliberately placed *after* `tier_gate_decision`: `load_or_init` can+ // initialize config on first run, and a spawn the tier gate rejects+ // should not have that side effect.+ let loaded_config: LoadedConfig = Box::pin(crate::config::Config::load_or_init()).await.map(std::sync::Arc::new).map_err(|e| e.to_string());@@ -461,7 +465,7 @@ async fn offload_outcome_artifacts(// A worktree-isolated worker offloads into its own checkout; everyone else// uses the live policy's action root, which is the same root a parent's// relative read resolves the returned path against.- let policy = crate::security::live_policy::effective();+ let policy = crate::security::live_policy::current();let Some(action_dir) = options.worktree_action_dir.clone()diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rsindex a2747625c1..a29981f088 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs@@ -30,7 +30,6 @@ fn make_def_named_tools(names: &[&str]) -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: crate::agent::harness::definition::DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rsindex ff00780d38..f14d65e8c4 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs@@ -75,7 +75,7 @@ pub(super) fn is_subagent_spawn_tool(name: &str) -> bool {// which let wildcard-scoped children inherit the orchestrator's spawn// surface. Resolve the override names via the registry so the strip// stays in lockstep with `collect_orchestrator_tools`'s naming.- if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::current() {+ if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::global() {return registry.list().iter()diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rsindex 88351d45d9..938fd73391 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs@@ -233,7 +233,7 @@ pub(super) fn register_turn_tools_and_agents(// remains the deferred follow-up.let mut registered_agents: HashSet<String> = HashSet::new();let mut runtime_agent_count = 0usize;- if let Some(runtime) = crate::agent::harness::definition::AgentDefinitionRegistry::current() {+ if let Some(runtime) = crate::agent::harness::definition::AgentDefinitionRegistry::global() {for def in runtime.list() {if registered_agents.insert(def.id.clone()) {let _ =diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rsindex 80a31d9988..abcc191c54 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs@@ -127,7 +127,7 @@ pub struct OpenHumanSecurityGate {/// Fallback policy used when no process-global live policy is installed.////// Per-call resolution prefers- /// [`crate::security::live_policy::effective`] so an autonomy+ /// [`crate::security::live_policy::current`] so an autonomy/// change made mid-session is observed on the very next tool call — the/// same live-first / snapshot-fallback discipline `ApprovalGate` uses for/// `auto_approve`. The trait explicitly forbids the runtime caching a@@ -211,10 +211,10 @@ impl OpenHumanSecurityGate {.remove(call_id)}- /// The policy to answer this call against: the agent's or the live one when+ /// The policy to answer this call against: the live process-global one when/// installed, else the constructor snapshot.fn effective_policy(&self) -> Arc<SecurityPolicy> {- crate::security::live_policy::effective().unwrap_or_else(|| self.policy.clone())+ crate::security::live_policy::current().unwrap_or_else(|| self.policy.clone())}/// Finds the registered [`Tool`] named `name`, if any.diff --git a/crates/openhuman-core/src/agent/tinyagents/journal.rs b/crates/openhuman-core/src/agent/tinyagents/journal.rsindex 3e719fa573..4b81b1187f 100644--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs@@ -47,6 +47,8 @@ use std::collections::HashMap;use std::path::PathBuf;use std::sync::{Arc, Mutex};+use once_cell::sync::Lazy;+use tinyagents_harness::events::{EventSink, HarnessRunStatus};use tinyagents_harness::ids::{ComponentId, HarnessPhase, RunId, ThreadId};use tinyagents_harness::observability::{@@ -60,14 +62,11 @@ use tinyagents_session::transcript::import::ops::open_session_stores;/// Best-effort live request → durable tinyagents journal stream map. The web/// progress bridge uses this at turn end to shadow-project spans from the/// journal and compare them against the live `SpanCollector` path during C4 S3.-fn request_journal_runs() -> std::sync::Arc<RequestJournalRuns> {- crate::core::runtime::current_slot::<RequestJournalRuns>()-}--type RequestJournalRuns = Mutex<HashMap<String, String>>;+static REQUEST_JOURNAL_RUNS: Lazy<Mutex<HashMap<String, String>>> =+ Lazy::new(|| Mutex::new(HashMap::new()));pub(crate) fn register_request_journal_run(request_id: &str, run_id: &str) {- match request_journal_runs().lock() {+ match REQUEST_JOURNAL_RUNS.lock() {Ok(mut runs) => {runs.insert(request_id.to_string(), run_id.to_string());log::debug!(@@ -86,7 +85,7 @@ pub(crate) fn register_request_journal_run(request_id: &str, run_id: &str) {}pub(crate) fn take_request_journal_run(request_id: &str) -> Option<String> {- request_journal_runs()+ REQUEST_JOURNAL_RUNS.lock().ok().and_then(|mut runs| runs.remove(request_id))@@ -96,7 +95,7 @@ pub(crate) fn take_request_journal_run(request_id: &str) -> Option<String> {/// `tinyagents_store/` subtree holds the journal + kv stores. Async because the/// config load is async; errors are surfaced so callers can log-and-skip.async fn resolve_workspace() -> anyhow::Result<PathBuf> {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::Config::load_or_init().await.map_err(|e| anyhow::anyhow!("[journal] load config for workspace: {e}"))?;Ok(config.workspace_dir)@@ -264,7 +263,3 @@ pub(crate) async fn read_run_events(.await.map_err(|e| anyhow::anyhow!("[journal] read_run_events failed run_id={run_id}: {e}"))}--#[cfg(test)]-#[path = "journal_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rsindex 70b0ce4890..f2977283ad 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs@@ -110,7 +110,7 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {Ok(Box::new(move |request: GenerateRequest| {Box::pin(async move {- let config_loaded = crate::config::ops::load_current_or_init().await;+ let config_loaded = crate::config::Config::load_or_init().await;let (source, model) = subagent_host::resolve_subagent_source(&definition.model,&definition.id,diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rsindex b2ef8ca627..80401a1cdd 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs@@ -34,7 +34,6 @@ fn dummy_definition() -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/agent/tinyagents/reasoning.rs b/crates/openhuman-core/src/agent/tinyagents/reasoning.rsindex 81972de0fe..95cee0a6a1 100644--- a/crates/openhuman-core/src/agent/tinyagents/reasoning.rs+++ b/crates/openhuman-core/src/agent/tinyagents/reasoning.rs@@ -14,17 +14,16 @@//! Nothing set means the provider keeps its own default.use std::collections::HashMap;-use std::sync::Arc;+use std::sync::OnceLock;use parking_lot::Mutex;use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};use crate::config::Config;-type ThreadEfforts = Mutex<HashMap<String, ReasoningEffort>>;--fn thread_efforts() -> Arc<ThreadEfforts> {- crate::core::runtime::current_slot::<ThreadEfforts>()+fn thread_efforts() -> &'static Mutex<HashMap<String, ReasoningEffort>> {+ static EFFORTS: OnceLock<Mutex<HashMap<String, ReasoningEffort>>> = OnceLock::new();+ EFFORTS.get_or_init(|| Mutex::new(HashMap::new()))}/// The effort a thread's user picked, if any.@@ -34,8 +33,7 @@ pub(crate) fn thread_effort(thread_id: &str) -> Option<ReasoningEffort> {/// Records (`Some`) or clears (`None`) a thread's chosen effort.pub(crate) fn set_thread_effort(thread_id: &str, effort: Option<ReasoningEffort>) {- let efforts = thread_efforts();- let mut map = efforts.lock();+ let mut map = thread_efforts().lock();let previous = match effort {Some(effort) => map.insert(thread_id.to_string(), effort),None => map.remove(thread_id),diff --git a/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rs b/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rsindex 5814d3f6c0..f45d6d9a14 100644--- a/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rs@@ -228,27 +228,3 @@ fn a_cap_too_small_for_a_provider_minimum_budget_keeps_the_effort_only() {Some(ReasoningConfig::effort(ReasoningEffort::Low)));}--#[tokio::test]-async fn reasoning_effort_stays_with_the_agent_that_chose_it() {- use crate::core::runtime::agent_scope::test_agent_context;- use crate::core::runtime::{context::CoreContext, DomainSet};- let root = CoreContext::for_test(DomainSet::full(), None);- let alpha = test_agent_context(&root, "alpha");- let beta = test_agent_context(&root, "beta");- let thread = "effort-shared-thread";-- CoreContext::scope(std::sync::Arc::clone(&alpha), async {- set_thread_effort(thread, Some(ReasoningEffort::High));- })- .await;-- assert_eq!(- CoreContext::scope(alpha, async { thread_effort(thread) }).await,- Some(ReasoningEffort::High)- );- assert_eq!(- CoreContext::scope(beta, async { thread_effort(thread) }).await,- None- );-}diff --git a/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs b/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rsindex 9393c5a9b9..a17edb970f 100644--- a/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs+++ b/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs@@ -221,7 +221,7 @@ fn replay_schema(function: &str) -> ControllerSchema {/// Resolve the configured internal workspace whose `tinyagents_store/` holds the/// journal + status stores.async fn configured_workspace() -> Result<std::path::PathBuf, String> {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::Config::load_or_init().await.map_err(|e| format!("failed to load config: {e}"))?;Ok(config.workspace_dir)diff --git a/crates/openhuman-core/src/agent/tinyagents/run_mode.rs b/crates/openhuman-core/src/agent/tinyagents/run_mode.rsindex bb11a50a40..a8e3438fa0 100644--- a/crates/openhuman-core/src/agent/tinyagents/run_mode.rs+++ b/crates/openhuman-core/src/agent/tinyagents/run_mode.rs@@ -16,7 +16,7 @@//! for the thread.use std::collections::HashMap;-use std::sync::Arc;+use std::sync::OnceLock;use parking_lot::Mutex;use tinyagents_harness::middleware::{RunMode, RunModeHandle};@@ -24,10 +24,9 @@ use tinyagents_harness::middleware::{RunMode, RunModeHandle};use crate::core::bus::BUS;use crate::core::events::DomainEvent;-type RunModeRegistry = Mutex<HashMap<String, RunModeHandle>>;--fn registry() -> Arc<RunModeRegistry> {- crate::core::runtime::current_slot::<RunModeRegistry>()+fn registry() -> &'static Mutex<HashMap<String, RunModeHandle>> {+ static REGISTRY: OnceLock<Mutex<HashMap<String, RunModeHandle>>> = OnceLock::new();+ REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))}/// Returns the [`RunModeHandle`] for `thread_id`, creating one (starting in@@ -35,8 +34,7 @@ fn registry() -> Arc<RunModeRegistry> {/// the same underlying atomic, so every clone (a live turn's middleware, this/// registry's own copy, a later RPC call) observes the same live value.pub fn handle_for_thread(thread_id: &str) -> RunModeHandle {- let registry = registry();- let mut map = registry.lock();+ let mut map = registry().lock();map.entry(thread_id.to_string()).or_insert_with(|| RunModeHandle::new(RunMode::Build)).clone()diff --git a/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rs b/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rsindex a91f77e9a1..324e52f0e1 100644--- a/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rs@@ -31,27 +31,3 @@ fn mode_label_round_trips() {assert_eq!(parse_mode_label("build"), Some(RunMode::Build));assert_eq!(parse_mode_label("nonsense"), None);}--#[tokio::test]-async fn plan_mode_stays_with_the_agent_that_set_it() {- use crate::core::runtime::agent_scope::test_agent_context;- use crate::core::runtime::{context::CoreContext, DomainSet};- let root = CoreContext::for_test(DomainSet::full(), None);- let alpha = test_agent_context(&root, "alpha");- let beta = test_agent_context(&root, "beta");- let thread = "plan-mode-shared-thread";-- CoreContext::scope(std::sync::Arc::clone(&alpha), async {- set_mode(thread, RunMode::Plan);- })- .await;-- assert_eq!(- CoreContext::scope(alpha, async { get_mode(thread) }).await,- RunMode::Plan- );- assert_eq!(- CoreContext::scope(beta, async { get_mode(thread) }).await,- RunMode::Build- );-}diff --git a/crates/openhuman-core/src/agent/tools/run_workflow.rs b/crates/openhuman-core/src/agent/tools/run_workflow.rsindex abbccd3645..c7d9a6ec66 100644--- a/crates/openhuman-core/src/agent/tools/run_workflow.rs+++ b/crates/openhuman-core/src/agent/tools/run_workflow.rs@@ -20,7 +20,7 @@//! If the shepherd finishes its first pass quickly the crusher gets the//! result inline; if not, it gets a `run_id` and can move on.//!-//! Guardrails (see the `guard` module): a per-agent spawn backstop,+//! Guardrails (see the `guard` module): a process-lifetime spawn backstop,//! a concurrency/nesting cap on synchronous awaits, and a re-entrancy lock//! keyed on workflow-id + inputs so an LLM that loses track can't tip a//! legitimate A→B→A chain into an unbounded loop. These are deliberately@@ -55,64 +55,55 @@ const MAX_WAIT_SECONDS: u64 = 600;mod guard {use std::collections::HashSet;use std::sync::atomic::{AtomicU64, Ordering};- use std::sync::{Arc, Mutex};+ use std::sync::{LazyLock, Mutex};- /// Per-agent lifetime backstop against a runaway spawn loop.+ /// Process-lifetime backstop against a runaway spawn loop.const TOTAL_SPAWN_BACKSTOP: u64 = 500;/// Max workflows being synchronously awaited at once. Because an awaiting/// call holds its slot for the whole nested wait, this also bounds the/// depth of synchronous workflow→workflow chains.const MAX_ACTIVE_AWAITS: u64 = 8;- /// The spawn counter, await count and re-entrancy keys of one agent- /// context.- #[derive(Default)]- struct GuardState {- total_spawns: AtomicU64,- active_awaits: AtomicU64,- active_keys: Mutex<HashSet<String>>,- }-- fn state() -> Arc<GuardState> {- crate::core::runtime::current_slot::<GuardState>()- }+ static TOTAL_SPAWNS: AtomicU64 = AtomicU64::new(0);+ static ACTIVE_AWAITS: AtomicU64 = AtomicU64::new(0);+ static ACTIVE_KEYS: LazyLock<Mutex<HashSet<String>>> =+ LazyLock::new(|| Mutex::new(HashSet::new()));/// RAII guard held while a call awaits a run. Dropping it frees the/// active-await slot and clears the re-entrancy key.pub struct AwaitGuard {key: String,- state: Arc<GuardState>,}impl Drop for AwaitGuard {fn drop(&mut self) {- self.state.active_awaits.fetch_sub(1, Ordering::SeqCst);- if let Ok(mut keys) = self.state.active_keys.lock() {+ ACTIVE_AWAITS.fetch_sub(1, Ordering::SeqCst);+ if let Ok(mut keys) = ACTIVE_KEYS.lock() {keys.remove(&self.key);}}}- /// Account a spawn against the agent's backstop. Returns `Err`+ /// Account a spawn against the process-lifetime backstop. Returns `Err`/// once the cap trips. Called by both the awaited and the fire-and-forget/// paths so neither can loop forever.pub fn account_spawn() -> Result<(), String> {- let n = state().total_spawns.fetch_add(1, Ordering::SeqCst) + 1;+ let n = TOTAL_SPAWNS.fetch_add(1, Ordering::SeqCst) + 1;if n > TOTAL_SPAWN_BACKSTOP {return Err(format!(- "refused — spawn backstop hit ({TOTAL_SPAWN_BACKSTOP} workflow runs \+ "refused — process spawn backstop hit ({TOTAL_SPAWN_BACKSTOP} workflow runs \spawned this session). This guards against a runaway spawn loop."));}Ok(())}- /// Test-only reader for the agent's spawn counter. Used by the+ /// Test-only reader for the process-lifetime spawn counter. Used by the/// regression test that asserts a rejected spawn (e.g. unknown workflow/// id) doesn't consume a backstop slot.#[cfg(test)]pub fn total_spawns() -> u64 {- state().total_spawns.load(Ordering::SeqCst)+ TOTAL_SPAWNS.load(Ordering::SeqCst)}/// Acquire an await slot + re-entrancy lock for `key` (a workflow-id +@@ -120,9 +111,7 @@ mod guard {/// many awaits are in flight (nesting/fan-out cap) or the same key is/// already being awaited up the stack (re-entrant tight loop).pub fn acquire_await(key: String) -> Result<AwaitGuard, String> {- let state = state();- let mut keys = state- .active_keys+ let mut keys = ACTIVE_KEYS.lock().map_err(|_| "internal guard lock poisoned".to_string())?;if keys.contains(&key) {@@ -132,7 +121,7 @@ mod guard {.to_string(),);}- if state.active_awaits.load(Ordering::SeqCst) >= MAX_ACTIVE_AWAITS {+ if ACTIVE_AWAITS.load(Ordering::SeqCst) >= MAX_ACTIVE_AWAITS {return Err(format!("refused — {MAX_ACTIVE_AWAITS} workflows are already being awaited concurrently \(nesting/fan-out cap). Let some finish, or spawn with `wait_seconds: 0` to \@@ -140,9 +129,8 @@ mod guard {));}keys.insert(key.clone());- state.active_awaits.fetch_add(1, Ordering::SeqCst);- drop(keys);- Ok(AwaitGuard { key, state })+ ACTIVE_AWAITS.fetch_add(1, Ordering::SeqCst);+ Ok(AwaitGuard { key })}}@@ -338,7 +326,7 @@ impl Tool for RunWorkflowTool {// Awaited path: take the re-entrancy/nesting slot first (so a tight// loop is rejected before we even spawn), then account the spawn —// but only once it actually starts, so a rejected spawn doesn't burn- // the backstop.+ // the process backstop.let _guard = match guard::acquire_await(reentrancy_key(&workflow_id, &inputs)) {Ok(g) => g,Err(e) => return Ok(ToolResult::error(format!("run_workflow: {e}"))),diff --git a/crates/openhuman-core/src/agent/tools/run_workflow_tests.rs b/crates/openhuman-core/src/agent/tools/run_workflow_tests.rsindex 5117fb54a8..fd7c5892f5 100644--- a/crates/openhuman-core/src/agent/tools/run_workflow_tests.rs+++ b/crates/openhuman-core/src/agent/tools/run_workflow_tests.rs@@ -162,26 +162,3 @@ fn account_spawn_trips_the_process_backstop() {let err = last.expect_err("the spawn backstop must trip within 600 accounted spawns");assert!(err.contains("backstop"), "got: {err}");}--#[tokio::test]-async fn each_agent_owns_its_workflow_await_guard() {- use crate::core::runtime::agent_scope::test_agent_context;- use crate::core::runtime::{context::CoreContext, DomainSet};- let root = CoreContext::for_test(DomainSet::full(), None);- let alpha = test_agent_context(&root, "alpha");- let beta = test_agent_context(&root, "beta");- let key = "agent-guard-shared-key".to_string();-- let held = CoreContext::scope(std::sync::Arc::clone(&alpha), async {- super::guard::acquire_await(key.clone()).expect("alpha acquires")- })- .await;-- let beta_result =- CoreContext::scope(beta, async { super::guard::acquire_await(key.clone()) }).await;- assert!(beta_result.is_ok(), "beta is not blocked by alpha's await");- let alpha_again =- CoreContext::scope(alpha, async { super::guard::acquire_await(key.clone()) }).await;- assert!(alpha_again.is_err(), "alpha still holds its own key");- drop(held);-}diff --git a/crates/openhuman-core/src/agent/tools/todo.rs b/crates/openhuman-core/src/agent/tools/todo.rsindex 93e53bea7e..59fb348e13 100644--- a/crates/openhuman-core/src/agent/tools/todo.rs+++ b/crates/openhuman-core/src/agent/tools/todo.rs@@ -59,7 +59,7 @@ impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Tlet context = ToolExecutionContext::from_run_context(parent, call_id);let workspace_dir = match parent.data.parent.as_ref() {Some(parent_ctx) => parent_ctx.workspace_dir.clone(),- None => crate::config::ops::load_current_or_init()+ None => crate::config::Config::load_or_init().await.map(|c| c.workspace_dir).map_err(|e| anyhow::anyhow!("[tool][todo] load config: {e}"))?,diff --git a/crates/openhuman-core/src/agent/triage/escalation.rs b/crates/openhuman-core/src/agent/triage/escalation.rsindex cf9b0336a0..3c995bb7f3 100644--- a/crates/openhuman-core/src/agent/triage/escalation.rs+++ b/crates/openhuman-core/src/agent/triage/escalation.rs@@ -240,7 +240,7 @@ async fn dispatch_target_agent(agent_id: &str, prompt: &str) -> anyhow::Result<S));}- let config = crate::config::ops::load_current_or_init()+ let config = Config::load_or_init().await.context("loading config for sub-agent dispatch")?;@@ -248,7 +248,7 @@ async fn dispatch_target_agent(agent_id: &str, prompt: &str) -> anyhow::Result<S// `build_root_parent` (inside `build_triage_parent`) guarantees the registry// is initialised, so this lookup for the target definition is safe here.- let registry = AgentDefinitionRegistry::current()+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| anyhow!("AgentDefinitionRegistry not initialised"))?;let definition = registry.get(agent_id)diff --git a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs b/crates/openhuman-core/src/agent/triage/evaluator/arm.rsindex 4d17e54cd1..a8b1e65b86 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/arm.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/arm.rs@@ -80,7 +80,7 @@ pub(super) async fn try_arm("[triage::evaluator] starting triage turn");- let registry = AgentDefinitionRegistry::current().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| {ArmError::Fatal(anyhow!("AgentDefinitionRegistry not initialised — did startup wiring \skip `init_global`?"diff --git a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs b/crates/openhuman-core/src/agent/triage/evaluator/chain.rsindex 08f116b842..36df152441 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/chain.rs@@ -7,6 +7,7 @@ use std::time::Duration;use anyhow::Context;+use crate::config::Config;use crate::cron::scheduler_gate::LlmPermit;use super::super::envelope::TriggerEnvelope;@@ -76,7 +77,7 @@ fn retry_state() -> &'static RetryState {/// 5. On local failure, return `TriageOutcome::Deferred` so the/// caller can retry when a local arm is available.pub async fn run_triage(envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutcome> {- let config = crate::config::ops::load_current_or_init()+ let config = Config::load_or_init().await.context("loading config for triage turn")?;let cloud = resolve_provider_with_config(&config)diff --git a/crates/openhuman-core/src/agent/turn_origin.rs b/crates/openhuman-core/src/agent/turn_origin.rsindex 797e51138c..a8f37459ae 100644--- a/crates/openhuman-core/src/agent/turn_origin.rs+++ b/crates/openhuman-core/src/agent/turn_origin.rs@@ -281,8 +281,8 @@ pub async fn with_inherited_origin<F: std::future::Future>(}}-/// Carry the origin and the [`CoreContext`](crate::core::runtime::CoreContext)-/// scoped **right now** into a future that will run on another task.+/// Carry the origin scoped **right now** into a future that will run on+/// another task.////// A `tokio::task_local` does not cross `tokio::spawn`: a detached sub-agent/// (`spawn_async_subagent`, the orchestration `spawn_agent` task) starts on a@@ -309,17 +309,10 @@ pub async fn with_inherited_origin<F: std::future::Future>(/// cannot manufacture trust that did not exist on the spawning task.pub fn propagate<F: std::future::Future>(fut: F) -> impl std::future::Future<Output = F::Output> {let captured = current();- let context = crate::core::runtime::CoreContext::scoped();async move {- let run = async move {- match captured {- Some(origin) => with_origin(origin, fut).await,- None => fut.await,- }- };- match context {- Some(context) => crate::core::runtime::CoreContext::scope(context, run).await,- None => run.await,+ match captured {+ Some(origin) => with_origin(origin, fut).await,+ None => fut.await,}}}diff --git a/crates/openhuman-core/src/channels/host/channel_events_tests.rs b/crates/openhuman-core/src/channels/host/channel_events_tests.rsindex f2f5ec1079..cccf6ec3a6 100644--- a/crates/openhuman-core/src/channels/host/channel_events_tests.rs+++ b/crates/openhuman-core/src/channels/host/channel_events_tests.rs@@ -81,7 +81,6 @@ fn approval(thread_id: Option<&str>, client_id: Option<&str>) -> DomainEvent {client_id: client_id.map(str::to_string),tool_call_id: None,expires_at: None,- agent_id: None,}}diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/mod_scoping_tests_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/mod_scoping_tests_tests.rsindex 04f0763fdf..729a69cbf7 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/mod_scoping_tests_tests.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/mod_scoping_tests_tests.rs@@ -73,7 +73,6 @@ fn def_with_scope(scope: ToolScope) -> AgentDefinition {subagents: vec![],delegate_name: None,agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/routing.rs b/crates/openhuman-core/src/channels/runtime/dispatch/routing.rsindex 7a41460140..d2f7f5afd0 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/routing.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/routing.rs@@ -79,7 +79,7 @@ pub(super) async fn resolve_target_agent(channel: &str) -> AgentScoping {"[dispatch::routing] selected target agent");- let registry = match AgentDefinitionRegistry::current() {+ let registry = match AgentDefinitionRegistry::global() {Some(reg) => reg,None => {tracing::warn!(@@ -154,7 +154,7 @@ pub(super) async fn resolve_target_agent(channel: &str) -> AgentScoping {connected_integration_count = connected.len(),"[dispatch::routing] fetched connected integrations for delegation expansion");- orchestrator_tools::collect_orchestrator_tools(definition, ®istry, &connected)+ orchestrator_tools::collect_orchestrator_tools(definition, registry, &connected)} else {Vec::new()};diff --git a/crates/openhuman-core/src/config/ops/loader.rs b/crates/openhuman-core/src/config/ops/loader.rsindex b75f07965e..fa25a8f0fa 100644--- a/crates/openhuman-core/src/config/ops/loader.rs+++ b/crates/openhuman-core/src/config/ops/loader.rs@@ -7,8 +7,8 @@ mod runtime_flags;mod snapshot;pub use load::{- load_config_for_workspace_with_timeout, load_config_with_timeout, load_current_or_init,- reload_config_from_paths, reload_config_snapshot_with_timeout,+ load_config_for_workspace_with_timeout, load_config_with_timeout, reload_config_from_paths,+ reload_config_snapshot_with_timeout,};pub(crate) use paths::fallback_workspace_dir;#[cfg(test)]@@ -43,7 +43,3 @@ mod model_registry_seed_tests;#[cfg(test)]#[path = "loader_io_chain_tests.rs"]mod loader_io_chain_tests;--#[cfg(test)]-#[path = "loader_current_tests.rs"]-mod loader_current_tests;diff --git a/crates/openhuman-core/src/config/ops/loader/load.rs b/crates/openhuman-core/src/config/ops/loader/load.rsindex dc01179acd..eb72552e19 100644--- a/crates/openhuman-core/src/config/ops/loader/load.rs+++ b/crates/openhuman-core/src/config/ops/loader/load.rs@@ -55,30 +55,6 @@ pub async fn load_config_with_timeout() -> Result<Config, String> {}}-/// The config of the ambient context: an embedded agent's own config under-/// its context, else the persisted config (initialised on first run).-///-/// The context-aware counterpart of [`Config::load_or_init`] for code that-/// runs inside a turn. Unlike [`load_config_with_timeout`], it keeps the-/// `anyhow` error and adds no timeout.-pub async fn load_current_or_init() -> anyhow::Result<Config> {- if let Some(mut config) = crate::core::runtime::context::CoreContext::current_embedder_config()- {- tracing::trace!(- agent = crate::core::runtime::agent_scope::current_agent_id()- .as_deref()- .unwrap_or(""),- "[config] using the context's config"- );- normalize_loaded_config(&mut config).await;- if let Some(route) = config.ephemeral_route.clone() {- crate::config::schema::ephemeral_route::apply(&mut config, route);- }- return Ok(config);- }- Config::load_or_init().await-}-/// Loads the config that belongs to `workspace_dir`, rather than whichever one/// the process-global active-user / `OPENHUMAN_WORKSPACE` resolution currently/// selects.diff --git a/crates/openhuman-core/src/config/ops/mod.rs b/crates/openhuman-core/src/config/ops/mod.rsindex 36a739dd29..d3718bddad 100644--- a/crates/openhuman-core/src/config/ops/mod.rs+++ b/crates/openhuman-core/src/config/ops/mod.rs@@ -24,9 +24,9 @@ pub use loader::{agent_server_status, client_config_json, core_rpc_url_from_env, get_config_snapshot,get_dashboard_settings, get_data_paths, get_data_paths_for_user, get_runtime_flags,load_and_get_client_config_snapshot, load_and_get_config_snapshot,- load_config_for_workspace_with_timeout, load_config_with_timeout, load_current_or_init,- reload_config_from_paths, reload_config_snapshot_with_timeout, reset_local_data,- set_browser_allow_all, snapshot_config_json, RuntimeFlagsOut,+ load_config_for_workspace_with_timeout, load_config_with_timeout, reload_config_from_paths,+ reload_config_snapshot_with_timeout, reset_local_data, set_browser_allow_all,+ snapshot_config_json, RuntimeFlagsOut,};// expose internal helpers needed by tests (ops_tests.rs uses super::*)#[cfg(test)]diff --git a/crates/openhuman-core/src/core/bus.rs b/crates/openhuman-core/src/core/bus.rsindex efba0df950..bbb3efb305 100644--- a/crates/openhuman-core/src/core/bus.rs+++ b/crates/openhuman-core/src/core/bus.rs@@ -83,9 +83,7 @@ pub const EVENTS_INTERFACE: &str = "ai.tinyhumans.openhuman.Events";/// `MemoryTreeBuildProgress`, `CacheRebuilt`) — nothing publishes them any/// more — and adds `ConversationTurnCommitted` (memory's conversation/// ingestion) and `CronSystemJobDue` (host-owned cron jobs).-/// `1.9.0` adds an optional `agent_id` to `ApprovalRequested`,-/// `ApprovalDecided` and `FlowApprovalRequested` (additive).-pub const EVENTS_VERSION: Version = Version::new(1, 9, 0);+pub const EVENTS_VERSION: Version = Version::new(1, 8, 0);/// The bus. Initialised once by [`init`]; safe to touch before that.pub static BUS: OnceBus<DomainEvent> = OnceBus::new();diff --git a/crates/openhuman-core/src/core/events.rs b/crates/openhuman-core/src/core/events.rsindex edfe2e3608..c38b5113f7 100644--- a/crates/openhuman-core/src/core/events.rs+++ b/crates/openhuman-core/src/core/events.rs@@ -531,10 +531,15 @@ pub enum DomainEvent {},// ── Approval ────────────────────────────────────────────────────────- /// Agent attempted a tool call that produces an external side effect;- /// awaiting user approval. Published by `ApprovalGate` before parking the- /// tool-call future. Carries no `session_id`: consumers need only the- /// request id plus optional chat thread/client routing.+ /// Agent attempted a tool call that produces an external side+ /// effect; awaiting user approval. Published by `ApprovalGate`+ /// before parking the tool-call future. Issue #1339.+ ///+ /// Note: this variant intentionally does not carry a `session_id`.+ /// Session provenance is internal to `ApprovalGate`; downstream+ /// surfaces (frontend approval card, audit log readers, web channel+ /// bridge) only need the request correlation id plus optional chat+ /// thread/client routing.ApprovalRequested {/// Unique id used to correlate the decision back to the/// parked future.@@ -565,9 +570,6 @@ pub enum DomainEvent {/// expiry or the publish site hasn't been updated yet.#[serde(default, skip_serializing_if = "Option::is_none")]expires_at: Option<String>,- /// The embedded agent whose turn parked this call, if any.- #[serde(default, skip_serializing_if = "Option::is_none")]- agent_id: Option<String>,},/// User decided a pending approval. Published by `approval_decide`/// RPC handler after the gate's parked future resolves.@@ -598,16 +600,17 @@ pub enum DomainEvent {/// decision (approve or a deliberate deny).#[serde(default, skip_serializing_if = "Option::is_none")]resolution: Option<String>,- /// Mirrored from `ApprovalRequested::agent_id`.- #[serde(default, skip_serializing_if = "Option::is_none")]- agent_id: Option<String>,},- /// A `Workflow`-origin tool call parked in the `ApprovalGate`. It carries- /// no `thread_id`/`client_id` (a flow run has neither), so the chat-routed- /// `web_chat::event_bus::ApprovalSurfaceSubscriber` ignores it. Published- /// by `ApprovalGate::intercept_audited` alongside `ApprovalRequested` and- /// bridged by `openhuman_rpc::server::socketio` to a broadcast- /// `flow_approval_request` Socket.IO event for the Workflows UI.+ /// A `Workflow`-origin tool call parked in the `ApprovalGate` (issue+ /// flow-approval-surface, PR2/PR3). Unlike `ApprovalRequested`, this+ /// event carries no `thread_id`/`client_id` — a flow run has neither, so+ /// the generic chat-routed socket bridge+ /// (`web_chat::event_bus::ApprovalSurfaceSubscriber`)+ /// silently drops it (that gap was the original silent-deadlock bug).+ /// Published by `ApprovalGate::intercept_audited` alongside the existing+ /// `ApprovalRequested`, bridged by `openhuman_rpc::server::socketio` directly to a+ /// broadcast (not per-room) `flow_approval_request` Socket.IO event so+ /// the Workflows UI can surface and resolve the park without polling.FlowApprovalRequested {/// Unique id used to correlate the decision back to the parked/// future — pass to `approval_decide` unchanged.@@ -622,9 +625,6 @@ pub enum DomainEvent {/// Short human-readable summary of the action (redacted, same as/// `ApprovalRequested::action_summary`).summary: String,- /// The embedded agent whose flow run parked this call.- #[serde(default, skip_serializing_if = "Option::is_none")]- agent_id: Option<String>,},// ── Egress (privacy spine) ──────────────────────────────────────────diff --git a/crates/openhuman-core/src/core/events_tests.rs b/crates/openhuman-core/src/core/events_tests.rsindex 87845498e3..6237de5c80 100644--- a/crates/openhuman-core/src/core/events_tests.rs+++ b/crates/openhuman-core/src/core/events_tests.rs@@ -535,8 +535,15 @@ fn all_variants_have_correct_domain() {}}-/// [`DomainEvent::ApprovalRequested`] must never carry a `session_id`, which-/// could hold the JSON-RPC bearer and leak through any Debug print.+/// Regression guard. An earlier revision of+/// [`DomainEvent::ApprovalRequested`] published a `session_id`+/// field that historically carried the verbatim JSON-RPC bearer.+/// Any downstream subscriber that Debug-printed the event (audit+/// pipeline, `tracing` instrumentation, panic backtrace) leaked+/// the credential. The field has been removed from the variant;+/// this test fails loudly if it ever comes back, by name, via+/// Debug — the bus does not derive `Serialize` so the audit-side+/// risk lives entirely in the Debug surface.#[test]fn approval_requested_does_not_surface_session_id() {let event = DomainEvent::ApprovalRequested {@@ -548,7 +555,6 @@ fn approval_requested_does_not_surface_session_id() {client_id: Some("c-1".to_string()),tool_call_id: None,expires_at: None,- agent_id: None,};let dbg = format!("{event:?}");assert!(diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rsindex 422d513ee9..ddf07b1612 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -107,8 +107,66 @@ pub struct CoreContext {/// ([`crate::agent::session_store`]) hands out to work under this/// context. `None` for booted contexts, which use the shared default.session_agent: Option<String>,- /// What the agent this context was derived for owns.- agent: agent_parts::AgentParts,+}++/// Per-agent overrides layered onto a booted context by+/// [`CoreContext::derive_with`].+///+/// This is the seam a library host uses to run many independently configured+/// agents on one booted core: each agent gets its own `Config` (provider+/// routes, MCP servers, autonomy tier, `action_dir`), its own+/// [`DomainSet`](crate::core::runtime::DomainSet), its own+/// [`ToolGroups`](crate::tools::toolpacks::ToolGroups) and its own skill-root+/// policy, while sharing the host identity, keyring, bus and RPC bearer of the+/// context it derives from.+#[derive(Debug, Clone)]+pub struct ContextOverlay {+ /// The config every handler dispatched under the derived context reads+ /// through `config::ops::load_config_with_timeout()`. Keep `config_path`+ /// equal to the parent's: credentials, auth profiles and the keyring file+ /// backend all resolve against its parent directory.+ pub config: crate::config::Config,+ /// Domain families live for the derived context. Only narrowing the parent+ /// is meaningful: controllers a booted core never registered stay absent+ /// no matter what this says.+ pub domains: crate::core::runtime::DomainSet,+ /// Tool-group disclosure for the derived context.+ pub tool_groups: crate::tools::toolpacks::ToolGroups,+ /// Scan the operator's user-scope skill roots (`true` = today's behaviour).+ pub user_skill_roots: bool,+ /// The agent a host session store scopes this context's transcripts,+ /// journal, goals and todos to. `None` keeps the parent's.+ pub session_agent: Option<String>,+}++impl ContextOverlay {+ /// An overlay that keeps user-scope skill roots visible.+ pub fn new(+ config: crate::config::Config,+ domains: crate::core::runtime::DomainSet,+ tool_groups: crate::tools::toolpacks::ToolGroups,+ ) -> Self {+ Self {+ config,+ domains,+ tool_groups,+ user_skill_roots: true,+ session_agent: None,+ }+ }++ /// Hide the operator's `~/.openhuman/skills` / `~/.agents/skills` from+ /// skill discovery under the derived context.+ pub fn without_user_skill_roots(mut self) -> Self {+ self.user_skill_roots = false;+ self+ }++ /// Scope a host session store to `agent_id` under the derived context.+ pub fn session_agent(mut self, agent_id: impl Into<String>) -> Self {+ self.session_agent = Some(agent_id.into());+ self+ }}/// The workspace a context is bound to.@@ -265,7 +323,6 @@ impl CoreContext {backend_transport,turn_origin: None,session_agent: None,- agent: Default::default(),});let _ = DEFAULT_CONTEXT.set(ctx.clone());@@ -324,7 +381,7 @@ impl CoreContext {/// The workspace binding is anchored to `overlay.config.workspace_dir`, so/// an agent with its own workspace subdirectory resolves its own memory/// binding lazily, exactly as an embedder-supplied config does at boot.- pub fn derive_with(&self, mut overlay: ContextOverlay) -> Arc<CoreContext> {+ pub fn derive_with(&self, overlay: ContextOverlay) -> Arc<CoreContext> {// Clamped to what this context can already dispatch. A derived// overlay may only narrow: callers outside this crate (embed's// `Runtime::agent`, for one) already refuse a spec that names a@@ -371,7 +428,6 @@ impl CoreContext {})),}};- let agent = self.agent.derive(&mut overlay);Arc::new(CoreContext {host_kind: self.host_kind,workspace_binding: RwLock::new(shared_binding),@@ -382,7 +438,6 @@ impl CoreContext {backend_transport: self.backend_transport.clone(),turn_origin: self.turn_origin.clone(),session_agent: overlay.session_agent.or_else(|| self.session_agent.clone()),- agent,})}@@ -533,7 +588,6 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,- agent: Default::default(),})}@@ -564,7 +618,6 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,- agent: Default::default(),})}}@@ -688,13 +741,6 @@ pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runt#[path = "context_turn_origin.rs"]mod turn_origin_scope;-#[path = "context_agent.rs"]-mod agent_parts;--#[path = "context_overlay.rs"]-mod overlay;-pub use overlay::ContextOverlay;-#[cfg(test)]#[path = "context_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rsindex 8014605a47..dfaef14494 100644--- a/crates/openhuman-core/src/core/runtime/context_tests.rs+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -14,7 +14,6 @@ fn ctx(dir: &str) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,- agent: Default::default(),})}@@ -46,7 +45,6 @@ fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,- agent: Default::default(),})}@@ -368,7 +366,6 @@ fn degraded_context_rejects_workspace_bound_stores() {backend_transport: None,turn_origin: None,session_agent: None,- agent: Default::default(),};// `workspace_dir()` is the gate every workspace-bound store goesdiff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rsindex fe41e579fa..6e1ba81782 100644--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs@@ -50,7 +50,6 @@ impl CoreContext {backend_transport: ctx.backend_transport.clone(),turn_origin: origin.or_else(|| ctx.turn_origin.clone()),session_agent: ctx.session_agent.clone(),- agent: ctx.agent.clone(),});CURRENT_CONTEXT.scope(context, fut).await}diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rsindex 992f7df98a..b9d55dfc7a 100644--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@ -43,7 +43,6 @@ pub const AGENT_WORKER_STACK_BYTES: usize = 20 * 1024 * 1024;/// `.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;@@ -55,7 +54,6 @@ pub mod services;pub mod spawn;pub(crate) mod subscribers;-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};diff --git a/crates/openhuman-core/src/cron/mod.rs b/crates/openhuman-core/src/cron/mod.rsindex 639e5fe035..572864689b 100644--- a/crates/openhuman-core/src/cron/mod.rs+++ b/crates/openhuman-core/src/cron/mod.rs@@ -16,7 +16,7 @@ pub mod ops;pub mod origin;mod schemas;pub mod seed;-pub(crate) mod store;+mod store;pub mod system_jobs;pub mod tools;diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rsindex dbf6ce99af..8e87f3fa2f 100644--- a/crates/openhuman-core/src/cron/scheduler.rs+++ b/crates/openhuman-core/src/cron/scheduler.rs@@ -75,46 +75,6 @@ pub async fn run(config: Config) -> Result<()> {loop {interval.tick().await;tick_once(&config, &security, &mut last_emitted_health).await;- tick_live_agents().await;- }-}--/// Runs the due jobs of every live embedded agent, each under that agent's-/// own context: its config, provider route, policy and job database. An-/// agent that is not live has no context to run under, so its jobs stay-/// dormant until it is instantiated again.-pub(crate) async fn tick_live_agents() {- for (agent_id, ctx) in crate::core::runtime::AgentContextRegistry::live() {- let agent = agent_id.clone();- crate::core::runtime::CoreContext::scope(ctx, async move {- let config = match crate::config::ops::load_current_or_init().await {- Ok(config) => config,- Err(error) => {- tracing::debug!(agent = %agent, %error, "[cron:scheduler] agent config unavailable");- return;- }- };- if !crate::cron::store::db_path(&config).exists() {- return;- }- let jobs = match due_jobs(&config, Utc::now()) {- Ok(jobs) => jobs,- Err(error) => {- tracing::warn!(agent = %agent, "[cron:scheduler] agent poll db_error: {error}");- return;- }- };- if jobs.is_empty() {- return;- }- let Some(security) = crate::security::live_policy::effective() else {- tracing::warn!(agent = %agent, "[cron:scheduler] agent has no policy; jobs skipped");- return;- };- tracing::debug!(agent = %agent, due_count = jobs.len(), "[cron:scheduler] running agent jobs");- process_due_jobs(&config, &security, jobs).await;- })- .await;}}diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rsindex cbae4fb0ea..bf91eeb13a 100644--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs@@ -48,8 +48,7 @@ pub(super) async fn run_agent_job_for_run(let selected_agent_id = job.agent_id.as_deref().unwrap_or("orchestrator");{let agent_id = selected_agent_id;- if let Some(registry) =- crate::agent::harness::definition::AgentDefinitionRegistry::current()+ if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::global(){if let Some(def) = registry.get(agent_id) {tracing::debug!(diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rsindex b143b03f2b..b370831a1f 100644--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs@@ -69,14 +69,8 @@ pub(crate) async fn append_to_origin_transcript(append_background_message, BackgroundAppend, BackgroundAppendOutcome,FileTranscriptLocator, SessionRef, TranscriptMessage,};+ let locator = FileTranscriptLocator::new(workspace_dir.to_path_buf());let session = SessionRef::scoped(append.thread_id.to_string(), append.agent_id.to_string());- if let Some(agent) = crate::core::runtime::agent_scope::current_agent_id() {- use tinyagents_session::transcript::TranscriptLocator;- crate::agent::session_store::AgentTranscriptFiles::new(workspace_dir, &agent)- .session_exists(&session);- }- let locator =- FileTranscriptLocator::new(crate::agent::session_store::transcript_root(workspace_dir));let options = BackgroundAppend::new(append.idempotency_key,serde_json::json!({diff --git a/crates/openhuman-core/src/cron/store.rs b/crates/openhuman-core/src/cron/store.rsindex fccd5629f4..8956f165f3 100644--- a/crates/openhuman-core/src/cron/store.rs+++ b/crates/openhuman-core/src/cron/store.rs@@ -17,20 +17,11 @@ use tinyflows_schedule::DeliveryStatus;use tinyflows_schedule::{CronJob, CronJobPatch, CronRun, DeliveryConfig, Schedule, SessionTarget};use tinyflows_sqlite::schedule::{self as upstream, AgentJobSpec, CronStoreOptions};-/// The job database for `config`: `<workspace>/cron/jobs.db`, or the agent's-/// own `<workspace>/agents/<id>/cron/jobs.db` under an embedded agent's-/// context, so an agent lists, edits and runs only the jobs it created.-pub fn db_path(config: &Config) -> std::path::PathBuf {- crate::core::runtime::agent_scope_dir(config)- .join("cron")- .join("jobs.db")-}--/// Builds the store options from the host config: [`db_path`],+/// Builds the store options from the host config: `<workspace>/cron/jobs.db`,/// `cron.max_run_history`, `scheduler.max_tasks`.fn opts(config: &Config) -> CronStoreOptions {CronStoreOptions {- db_path: db_path(config),+ db_path: config.workspace_dir.join("cron").join("jobs.db"),max_run_history: config.cron.max_run_history,max_tasks: config.scheduler.max_tasks,}diff --git a/crates/openhuman-core/src/cron/store_tests.rs b/crates/openhuman-core/src/cron/store_tests.rsindex 9bb577eecc..4e241a19e5 100644--- a/crates/openhuman-core/src/cron/store_tests.rs+++ b/crates/openhuman-core/src/cron/store_tests.rs@@ -48,77 +48,3 @@ fn run_history_cap_follows_cron_max_run_history() {}assert_eq!(list_runs(&config, &job.id, 10).unwrap().len(), 2);}--fn agent_context(- config: &Config,- agent: &str,-) -> std::sync::Arc<crate::core::runtime::CoreContext> {- use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};- CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(- ContextOverlay::new(- config.clone(),- DomainSet::full(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent(agent),- )-}--#[tokio::test]-async fn an_agents_jobs_live_in_its_own_database() {- use crate::core::runtime::CoreContext;- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = CoreContext::scope(agent_context(&config, "alpha"), async {- add_job(&config, "*/5 * * * *", "echo alpha").unwrap()- })- .await;-- assert!(tmp- .path()- .join("workspace/agents/alpha/cron/jobs.db")- .is_file());- let alpha_ids = CoreContext::scope(agent_context(&config, "alpha"), async {- list_jobs(&config)- .unwrap()- .into_iter()- .map(|job| job.id)- .collect::<Vec<_>>()- })- .await;- assert_eq!(alpha_ids, std::slice::from_ref(&job.id));- let beta_jobs = CoreContext::scope(agent_context(&config, "beta"), async {- list_jobs(&config).unwrap()- })- .await;- assert!(beta_jobs.is_empty());- assert!(- list_jobs(&config).unwrap().is_empty(),- "the workspace store stays empty"- );-}--#[tokio::test]-async fn a_job_whose_agent_is_not_live_stays_dormant() {- use crate::core::runtime::CoreContext;- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let ctx = agent_context(&config, "dormant-agent");- let job = CoreContext::scope(std::sync::Arc::clone(&ctx), async {- add_job(&config, "* * * * *", "echo dormant").unwrap()- })- .await;- drop(ctx);-- crate::cron::scheduler::tick_live_agents().await;-- let after = CoreContext::scope(agent_context(&config, "dormant-agent"), async {- get_job(&config, &job.id).unwrap()- })- .await;- assert!(- after.last_run.is_none(),- "nothing ran the dormant agent's job"- );-}diff --git a/crates/openhuman-core/src/flows/ops/inference_readiness.rs b/crates/openhuman-core/src/flows/ops/inference_readiness.rsindex 424a932b3a..c94bceba26 100644--- a/crates/openhuman-core/src/flows/ops/inference_readiness.rs+++ b/crates/openhuman-core/src/flows/ops/inference_readiness.rs@@ -177,7 +177,7 @@ pub(super) fn agent_node_role(config: &Config, node: &tinyflows::model::Node) ->tracing::debug!(target: "flows", %error,"[flows] readiness: agent definition registry unavailable; using registry fallback");}- let definition = AgentDefinitionRegistry::current().and_then(|r| r.get(agent_ref).cloned());+ let definition = AgentDefinitionRegistry::global().and_then(|r| r.get(agent_ref));let custom = crate::agent::registry::find_custom_in_config(config, agent_ref);if definition.is_some() || custom.is_some() {let entry_model = if definition.is_some() {@@ -193,7 +193,7 @@ pub(super) fn agent_node_role(config: &Config, node: &tinyflows::model::Node) ->override_model.as_deref().or(config.default_model.as_deref()),- definition.as_ref(),+ definition,);}}diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rsindex 8ec8484795..693f0dacb3 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs@@ -127,7 +127,7 @@ pub(crate) enum AgentRoute {/// custom-registry fallback. Pure over the global registry so the selection is/// unit-testable with `init_global_builtins`.pub(crate) fn route_for_agent_ref(agent_ref: &str) -> AgentRoute {- let has_definition = crate::agent::harness::definition::AgentDefinitionRegistry::current()+ let has_definition = crate::agent::harness::definition::AgentDefinitionRegistry::global().map(|reg| reg.get(agent_ref).is_some()).unwrap_or(false);if has_definition {diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rsindex 47bcea804e..4ff2054537 100644--- a/crates/openhuman-core/src/mcp/host.rs+++ b/crates/openhuman-core/src/mcp/host.rs@@ -116,7 +116,7 @@ impl McpHost {/// client cannot be built.pub fn open(config: &Config) -> anyhow::Result<Self> {let client = client_config(config);- Self::from_client_config(&host_key(config), &client)+ Self::from_client_config(config.workspace_dir.as_path(), &client)}/// Builds a host over `workspace` from an already-converted client@@ -126,9 +126,6 @@ impl McpHost {/// conversion: a host and the entry stored beside it can never disagree/// about which identity and proxy they were built with.fn from_client_config(workspace: &Path, client: &McpClientConfig) -> anyhow::Result<Self> {- std::fs::create_dir_all(workspace).map_err(|error| {- anyhow::anyhow!("failed to create the mcp store directory: {error}")- })?;Ok(Self {dynamic: McpRegistry::new(Store::open(workspace)@@ -183,7 +180,7 @@ impl McpHost {/// race; if one did, its service is returned and the freshly-built one is/// dropped.pub fn for_config(config: &Config) -> anyhow::Result<Arc<McpHost>> {- let workspace = host_key(config);+ let workspace = config.workspace_dir.clone();// A host already under this workspace needs no re-opening: it would be// wasteful (and, on the common path, a plain Mutex of the shared map held@@ -214,7 +211,6 @@ pub fn for_config(config: &Config) -> anyhow::Result<Arc<McpHost>> {return Ok(Arc::clone(&existing.host));}- tracing::debug!(key = ?workspace, "[mcp] opened host");hosts.insert(workspace,HostEntry {@@ -227,36 +223,6 @@ pub fn for_config(config: &Config) -> anyhow::Result<Arc<McpHost>> {Ok(service)}-/// The service for `config` when one exists, without creating an agent's.-///-/// Outside an agent context this is [`for_config`]. Under one, an agent that-/// never installed a server has no store on disk, and a read (listing-/// connections or tools) must not create one: it answers with an error the-/// read paths already treat as "nothing connected".-///-/// # Errors-///-/// When the agent has no host yet, or [`for_config`] fails.-pub fn lookup(config: &Config) -> anyhow::Result<Arc<McpHost>> {- let key = host_key(config);- if key != config.workspace_dir {- let open = HOSTS.get().and_then(|hosts| {- hosts- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .get(&key)- .map(|entry| Arc::clone(&entry.host))- });- if let Some(host) = open {- return Ok(host);- }- if !Store::path_for(&key).exists() {- anyhow::bail!("the agent has no mcp host yet");- }- }- for_config(config)-}-/// Opens the service for `config` and marks its workspace the default.////// Called once, from the core startup path. A second call opens nothing new and@@ -297,9 +263,6 @@ pub fn init(config: &Config) -> anyhow::Result<()> {/// [`for_config`] would still report nothing connected.#[must_use]pub fn try_service() -> Option<Arc<McpHost>> {- if let Some(agent_host) = current_agent_host() {- return agent_host;- }let hosts = HOSTS.get()?.lock()@@ -308,42 +271,6 @@ pub fn try_service() -> Option<Arc<McpHost>> {resolve(DEFAULT_WORKSPACE.get().map(PathBuf::as_path), &hosts)}-/// Removes the host of agent `agent_id` on `workspace_dir` from the open set-/// and hands it back, so the caller can close its connections. `None` when-/// the agent never opened one.-pub fn take_agent_host(workspace_dir: &Path, agent_id: &str) -> Option<Arc<McpHost>> {- let key = workspace_dir.join("agents").join(agent_id);- let entry = HOSTS- .get()?- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .remove(&key)?;- tracing::debug!(agent = %agent_id, "[mcp] agent host evicted");- Some(entry.host)-}--/// Where the host for `config` keeps its stores: the workspace, or the-/// agent's own directory beneath it when an agent context is current.-fn host_key(config: &Config) -> PathBuf {- crate::core::runtime::agent_scope_dir(config)-}--/// The current agent's host, when a turn runs under an agent context.-///-/// `None` outside an agent context; `Some(None)` when the agent's host cannot-/// be opened, which must not fall back to another agent's or the default one.-fn current_agent_host() -> Option<Option<Arc<McpHost>>> {- let agent = crate::core::runtime::agent_scope::current_agent_id()?;- let opened = crate::core::runtime::CoreContext::with_current_embedder_config(lookup)?;- Some(match opened {- Ok(host) => Some(host),- Err(error) => {- tracing::debug!(agent = %agent, ?error, "[mcp] agent host unavailable");- None- }- })-}-/// The rule [`try_service`] applies, as a function of its inputs.////// Separated from the process state so it can be tested. The state it reads is@@ -564,7 +491,3 @@ pub fn proxy_for_mcp() -> Option<McpProxyConfig> {#[cfg(test)]#[path = "host_tests.rs"]mod tests;--#[cfg(test)]-#[path = "host_agent_tests.rs"]-mod agent_tests;diff --git a/crates/openhuman-core/src/mcp/registry/mod.rs b/crates/openhuman-core/src/mcp/registry/mod.rsindex 6ccfb450b3..d6b164db77 100644--- a/crates/openhuman-core/src/mcp/registry/mod.rs+++ b/crates/openhuman-core/src/mcp/registry/mod.rs@@ -108,7 +108,7 @@ pub mod connections {/// [`disconnect_for_config`] exist: the ambient form resolves through the/// process default, which stops answering once a second workspace is open.pub async fn connected_overview_for_config(config: &Config) -> Vec<ConnectedServerOverview> {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => service.dynamic().connected_overview().await,Err(error) => {tracing::debug!(@@ -129,7 +129,7 @@ pub mod connections {/// its connect finishes. Listing is not authorization — a call still/// needs a live connection.pub async fn cached_overview_for_config(config: &Config) -> Vec<ConnectedServerOverview> {- let service = match host::lookup(config) {+ let service = match host::for_config(config) {Ok(service) => service,Err(error) => {tracing::debug!(?error, "[mcp] no host for workspace; no cached tools");@@ -165,7 +165,7 @@ pub mod connections {pub async fn all_connected_tools_for_config(config: &Config,) -> Vec<(String, String, tinymcp_bus::McpTool)> {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => service.dynamic().connections().all_connected_tools().await,Err(error) => {tracing::debug!(?error, "[mcp] no host for workspace; reporting no tools");@@ -206,7 +206,7 @@ pub mod connections {config: &Config,server_id: &str,) -> Option<Vec<tinymcp_bus::McpTool>> {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => service.dynamic().connections().tools_for(server_id).await,Err(error) => {tracing::debug!(?error, server_id, "[mcp] no host for workspace; no tools");@@ -231,7 +231,7 @@ pub mod connections {/// Whether a server has a live entry in `config`'s workspace.pub async fn is_connected_for_config(config: &Config, server_id: &str) -> bool {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => {service.dynamic()@@ -252,7 +252,7 @@ pub mod connections {/// Why a server's most recent attempt in `config`'s workspace hit a 401.pub async fn auth_hint_for_config(config: &Config, server_id: &str) -> Option<&'static str> {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => Some(service.dynamic()@@ -320,7 +320,7 @@ pub mod connections {/// through [`connect`] already named a workspace and should close over the/// same one.pub async fn disconnect_for_config(config: &Config, server_id: &str) -> bool {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => service.dynamic().connections().disconnect(server_id).await,Err(error) => {tracing::debug!(?error, "[mcp] no host for workspace; nothing to disconnect");@@ -331,7 +331,7 @@ pub mod connections {/// The most recent failure message for a server in `config`'s workspace.pub async fn last_error_for_config(config: &Config, server_id: &str) -> Option<String> {- match host::lookup(config) {+ match host::for_config(config) {Ok(service) => service.dynamic().connections().last_error(server_id).await,Err(error) => {tracing::debug!(@@ -356,7 +356,7 @@ pub mod boot {/// Never fails: a server that cannot connect is logged and skipped, because/// one broken third-party integration must not stop the core coming up.pub async fn spawn_installed_servers(config: &Config) {- let service = match host::lookup(config) {+ let service = match host::for_config(config) {Ok(service) => service,Err(error) => {tracing::warn!("[mcp] the service could not be opened: {error}");diff --git a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs b/crates/openhuman-core/src/mcp/server/tools/dispatch.rsindex 889731f61a..f04611c11a 100644--- a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs+++ b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs@@ -268,7 +268,7 @@ async fn core_tool_instructions() -> Result<Value, ToolCallError> {async fn list_subagents() -> Result<Value, ToolCallError> {let config = load_config_and_init_registry().await?;- let registry = AgentDefinitionRegistry::current().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::global().ok_or_else(|| {ToolCallError::Internal("AgentDefinitionRegistry missing after init".to_string())})?;diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rsindex 2adcb3b6ab..da7668f3e0 100644--- a/crates/openhuman-core/src/memory/bus.rs+++ b/crates/openhuman-core/src/memory/bus.rs@@ -103,28 +103,6 @@ impl EventHandler<DomainEvent> for SystemJobsSubscriber {}};run_system_job(&config, job).await;- if job == SOURCES_SYNC_JOB {- sync_live_agent_sources().await;- }- }-}--/// Starts the due source syncs of every live embedded agent, each under its-/// own context so its memory binding and sources apply.-async fn sync_live_agent_sources() {- for (agent_id, ctx) in crate::core::runtime::AgentContextRegistry::live() {- crate::core::runtime::CoreContext::scope(ctx, async {- match crate::config::ops::load_current_or_init().await {- Ok(config) => {- tracing::debug!(agent = %agent_id, "[memory:bus] agent source sync");- run_system_job(&config, SOURCES_SYNC_JOB).await;- }- Err(error) => {- tracing::debug!(agent = %agent_id, %error, "[memory:bus] agent config unavailable");- }- }- })- .await;}}diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex 06c2afcae1..c773ddccc0 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -180,7 +180,7 @@ pub fn start_sync(config: &Config, id: Option<&str>) -> MemoryResult<Vec<String>});started.push(source.id.clone());let config = config.clone();- crate::core::runtime::spawn_scoped(async move {+ tokio::spawn(async move {run_and_record(&config, &source).await;RUNNING.lock()diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rsindex f742d798ad..6e8dddc280 100644--- a/crates/openhuman-core/src/memory/tools.rs+++ b/crates/openhuman-core/src/memory/tools.rs@@ -19,7 +19,7 @@use crate::tools::schema_cache::static_schema;use std::collections::HashMap;-use std::sync::{Arc, Mutex};+use std::sync::{Arc, LazyLock, Mutex};use async_trait::async_trait;use serde_json::{json, Value};@@ -37,20 +37,16 @@ use super::types::{FetchParams, ForgetParams, LearnParams, RecallParams, TurnCit/// Most citations kept per thread between two drains.const MAX_TURN_CITATIONS: usize = 20;-type TurnCitations = Mutex<HashMap<String, Vec<TurnCitation>>>;-/// Citations `recall` produced during a thread's in-flight turn, drained by/// the chat surface once the turn returns ([`take_turn_citations`]).-fn turn_citations() -> Arc<TurnCitations> {- crate::core::runtime::current_slot::<TurnCitations>()-}+static TURN_CITATIONS: LazyLock<Mutex<HashMap<String, Vec<TurnCitation>>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));fn record_turn_citations(thread_id: &str, citations: &[tinymemory_api::Citation]) {if citations.is_empty() {return;}- let citations_by_thread = turn_citations();- let mut all = citations_by_thread+ let mut all = TURN_CITATIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let entry = all.entry(thread_id.to_string()).or_default();@@ -71,8 +67,7 @@ pub fn record_pack_citations(thread_id: &str, citations: Vec<TurnCitation>) {if citations.is_empty() {return;}- let citations_by_thread = turn_citations();- let mut all = citations_by_thread+ let mut all = TURN_CITATIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let entry = all.entry(thread_id.to_string()).or_default();@@ -90,7 +85,7 @@ pub fn record_pack_citations(thread_id: &str, citations: Vec<TurnCitation>) {/// `thread_id` since the last drain.#[must_use]pub fn take_turn_citations(thread_id: &str) -> Vec<TurnCitation> {- turn_citations()+ TURN_CITATIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(thread_id)@@ -359,10 +354,6 @@ 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 --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rsindex 5ce2fc4b04..d6abbb42b4 100644--- a/crates/openhuman-core/src/security/approval/gate.rs+++ b/crates/openhuman-core/src/security/approval/gate.rs@@ -60,23 +60,6 @@ pub enum DecideMiss {NeverRegistered,}-/// A decision refused by the gate before it reached the store.-#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]-pub enum ApprovalError {- /// The request was parked by a different agent than the one deciding it.- #[error("approval request {request_id} belongs to another agent")]- WrongAgent { request_id: String },-}--/// The key `thread_to_request` files a parked chat thread under: the thread-/// id alone for the process's own sessions, else the agent and thread.-pub(crate) fn thread_route_key(agent_id: Option<&str>, thread_id: &str) -> String {- match agent_id {- Some(agent) => format!("{agent}\u{1f}{thread_id}"),- None => thread_id.to_string(),- }-}-/// How long the gate will park a future before timing out and/// returning `Deny`. 10 minutes matches the default `expires_at`/// written into the persisted row.@@ -221,7 +204,6 @@ pub(crate) struct RequestRoute {pub(crate) client_id: Option<String>,pub(crate) tool_call_id: Option<String>,pub(crate) forced: bool,- pub(crate) agent_id: Option<String>,}/// Coordinator for pending approvals.@@ -230,9 +212,8 @@ pub struct ApprovalGate {session_id: String,ttl: Duration,waiters: Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>,- /// [`thread_route_key`] → request_id for the approval currently parked on- /// that chat thread, so the web channel can route a yes/no reply to- /// `approval_decide`.+ /// thread_id → request_id for the approval currently parked on that chat+ /// thread, so the web channel can route a yes/no reply to `approval_decide`./// In-memory only (session-scoped — a parked approval doesn't survive a/// restart, and the oneshot waiter is in-memory anyway).thread_to_request: Mutex<HashMap<String, String>>,@@ -264,7 +245,7 @@ pub struct ApprovalGate {struct WaiterGuard<'a> {gate: &'a ApprovalGate,request_id: String,- thread_key: Option<String>,+ thread_id: 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>,@@ -295,9 +276,9 @@ 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_key) = &self.thread_key {+ if let Some(thread_id) = &self.thread_id {self.gate- .clear_thread_route_if_owned(thread_key, &self.request_id);+ .clear_thread_route_if_owned(thread_id, &self.request_id);}let decided = store::decide_captured(&self.gate.config,@@ -315,7 +296,6 @@ impl Drop for WaiterGuard<'_> {client_id: route.as_ref().and_then(|r| r.client_id.clone()),tool_call_id: route.and_then(|r| r.tool_call_id),resolution: Some("cancelled".to_string()),- agent_id: row.agent_id,});}tracing::warn!(diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rsindex a4500bd213..3c30be9f7f 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -198,20 +198,6 @@ impl ApprovalGate {return (GateOutcome::Allow, None);}- if !forced- && !matches!(&origin, AgentTurnOrigin::Unknown)- && crate::core::runtime::CoreContext::current_approvals_disabled()- {- tracing::info!(- tool = tool_name,- origin_class = %origin.class(),- agent_id = crate::core::runtime::agent_scope::current_agent_id().as_deref().unwrap_or(""),- auto_approved = true,- "[approval::gate] approval gate off for this agent — allowing without prompt"- );- return (GateOutcome::Allow, None);- }-// "Always allow" allowlist shortcut — the user's persisted// `autonomy.auto_approve` set. Read from the live policy first so a// grant made earlier in this session (which writes config + reloads the@@ -405,10 +391,6 @@ impl ApprovalGate {let request_id = uuid::Uuid::new_v4().to_string();let now = chrono::Utc::now();- let agent_id = crate::core::runtime::agent_scope::current_agent_id();- let thread_key = chat_thread_id- .as_deref()- .map(|thread_id| thread_route_key(agent_id.as_deref(), thread_id));// Resolve the clamped park TTL up front so the persisted `expires_at`// and the actual wait below (see `resolve_park_ttl` further down)// use the same value — see `Self::resolve_park_ttl` and the@@ -453,7 +435,6 @@ impl ApprovalGate {expires_at,source_context: source_context.clone(),tool_call_id: tool_call_id.map(str::to_string),- agent_id: agent_id.clone(),};// Register the waiter BEFORE persisting the row so a fast@@ -468,10 +449,10 @@ impl ApprovalGate {}// Record the thread → request mapping so an inbound chat reply on this// thread can be routed to `approval_decide` (see web channel ingress).- if let Some(thread_key) = thread_key.as_ref() {+ if let Some(thread_id) = chat_thread_id.as_ref() {self.thread_to_request.lock()- .insert(thread_key.clone(), request_id.clone());+ .insert(thread_id.clone(), request_id.clone());}// Record the full routing correlation (thread/client/tool_call_id) so// whichever path resolves this request's decision — `decide()`, the@@ -485,12 +466,11 @@ impl ApprovalGate {client_id: chat_client_id.clone(),tool_call_id: tool_call_id.map(str::to_string),forced,- agent_id: agent_id.clone(),},);if let Err(err) = store::insert_pending(&self.config, &pending, &self.session_id) {self.evict_waiter(&request_id);- self.clear_thread(&thread_key, &request_id);+ self.clear_thread(&chat_thread_id, &request_id);self.take_request_route(&request_id);tracing::error!(error = %err,@@ -513,7 +493,6 @@ impl ApprovalGate {tool = tool_name,thread_id = chat_thread_id.as_deref().unwrap_or("<none>"),client_id = chat_client_id.as_deref().unwrap_or("<none>"),- agent_id = agent_id.as_deref().unwrap_or("<none>"),"[approval::gate] publishing ApprovalRequested (surface fires only if thread_id+client_id are both set)");BUS.publish(DomainEvent::ApprovalRequested {@@ -525,7 +504,6 @@ impl ApprovalGate {client_id: chat_client_id.clone(),tool_call_id: tool_call_id.map(str::to_string),expires_at: expires_at.map(|t| t.to_rfc3339()),- agent_id: agent_id.clone(),});// Flow-origin surface bridge (flow-approval-surface, PR3): a flow run@@ -555,7 +533,6 @@ impl ApprovalGate {run_id: run_id.clone(),tool_name: tool_name.to_string(),summary: action_summary.to_string(),- agent_id: agent_id.clone(),});// The workspace the flow parked in, so the approval banner is// dropped by a client that has since switched away rather than@@ -624,7 +601,7 @@ impl ApprovalGate {let mut waiter_guard = WaiterGuard {gate: self,request_id: request_id.clone(),- thread_key: thread_key.clone(),+ thread_id: chat_thread_id.clone(),docs: store::capture_docs(),armed: true,};@@ -649,7 +626,7 @@ impl ApprovalGate {waiter_guard.disarm();// The routing mappings are only needed while parked; clear them on// every exit (decision, channel drop, or timeout).- self.clear_thread(&thread_key, &request_id);+ self.clear_thread(&chat_thread_id, &request_id);outcome}}diff --git a/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs b/crates/openhuman-core/src/security/approval/gate_intercept_decision.rsindex 737d15cdb7..23a6682e23 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs@@ -65,7 +65,6 @@ impl ApprovalGate {client_id: route.as_ref().and_then(|r| r.client_id.clone()),tool_call_id: route.and_then(|r| r.tool_call_id),resolution: Some("cancelled".to_string()),- agent_id: row.agent_id.clone(),});}(@@ -165,7 +164,6 @@ impl ApprovalGate {client_id: route.as_ref().and_then(|r| r.client_id.clone()),tool_call_id: route.and_then(|r| r.tool_call_id),resolution: Some("expired".to_string()),- agent_id: row.agent_id.clone(),});}(diff --git a/crates/openhuman-core/src/security/approval/gate_setup.rs b/crates/openhuman-core/src/security/approval/gate_setup.rsindex 39e994a578..0de0391d55 100644--- a/crates/openhuman-core/src/security/approval/gate_setup.rs+++ b/crates/openhuman-core/src/security/approval/gate_setup.rs@@ -87,11 +87,11 @@ impl ApprovalGate {ttl}- /// Whether `tool_name` is on the user's "Always allow" list. Prefers the agent or+ /// Whether `tool_name` is on the user's "Always allow" list. Prefers the/// process-global live policy (so a grant made this session is seen/// immediately) and falls back to the gate's boot-time config snapshot.fn tool_is_auto_approved(&self, tool_name: &str) -> bool {- if let Some(policy) = crate::security::live_policy::effective() {+ if let Some(policy) = crate::security::live_policy::current() {return policy.auto_approve.iter().any(|t| t == tool_name);}self.config@@ -111,7 +111,7 @@ impl ApprovalGate {/// this flag — see the `matches!` guard at the call site below. This method only reports the/// user's setting; it does not know about origin.fn is_auto_approve_all_enabled(&self) -> bool {- if let Some(policy) = crate::security::live_policy::effective() {+ if let Some(policy) = crate::security::live_policy::current() {return policy.auto_approve_all;}self.config.autonomy.auto_approve_alldiff --git a/crates/openhuman-core/src/security/approval/gate_state.rs b/crates/openhuman-core/src/security/approval/gate_state.rsindex b89655d2e5..344169859a 100644--- a/crates/openhuman-core/src/security/approval/gate_state.rs+++ b/crates/openhuman-core/src/security/approval/gate_state.rs@@ -72,92 +72,11 @@ impl ApprovalGate {client_id: route.as_ref().and_then(|r| r.client_id.clone()),tool_call_id: route.and_then(|r| r.tool_call_id),resolution: None,- agent_id: row.agent_id.clone(),});}Ok(decided)}- /// [`Self::decide`] on behalf of `agent`: refuses with- /// [`ApprovalError::WrongAgent`] when the request was parked by any other- /// agent (or by the process itself), so one agent cannot answer another's- /// approval.- pub fn decide_for_agent(- &self,- agent: &str,- request_id: &str,- decision: ApprovalDecision,- ) -> anyhow::Result<Option<PendingApproval>> {- let owner = match self- .request_routes- .lock()- .get(request_id)- .map(|route| route.agent_id.clone())- {- Some(owner) => Some(owner),- None => store::pending_agent(&self.config, request_id)?,- };- if let Some(owner) = owner {- if owner.as_deref() != Some(agent) {- tracing::warn!(- request_id = %request_id,- agent_id = %agent,- owner = owner.as_deref().unwrap_or("<process>"),- "[approval::gate] decision refused: request belongs to another agent"- );- return Err(ApprovalError::WrongAgent {- request_id: request_id.to_string(),- }- .into());- }- }- self.decide(request_id, decision)- }-- /// Deny every undecided request `agent` parked, resolving its waiters.- /// Returns how many rows were denied.- pub fn deny_all_for_agent(&self, agent: &str, resolution: &str) -> anyhow::Result<usize> {- if !store::exists(&self.config) {- return Ok(0);- }- let rows = store::list_pending_for_agent(&self.config, Some(agent))?;- let mut denied = 0;- for row in rows {- let Some(decided) = store::decide(&self.config, &row.request_id, ApprovalDecision::Deny)?- else {- continue;- };- denied += 1;- if let Some(tx) = self.take_waiter(&decided.request_id) {- let _ = tx.send(ApprovalDecision::Deny);- }- let route = self.take_request_route(&decided.request_id);- if let Some(thread_id) = route.as_ref().and_then(|r| r.thread_id.as_deref()) {- self.clear_thread_route_if_owned(- &thread_route_key(Some(agent), thread_id),- &decided.request_id,- );- }- BUS.publish(DomainEvent::ApprovalDecided {- request_id: decided.request_id.clone(),- tool_name: decided.tool_name.clone(),- decision: ApprovalDecision::Deny.as_str().to_string(),- thread_id: route.as_ref().and_then(|r| r.thread_id.clone()),- client_id: route.as_ref().and_then(|r| r.client_id.clone()),- tool_call_id: route.and_then(|r| r.tool_call_id),- resolution: Some(resolution.to_string()),- agent_id: Some(agent.to_string()),- });- }- tracing::info!(- agent_id = %agent,- denied,- resolution,- "[approval::gate] denied every pending request of the agent"- );- Ok(denied)- }-/// Classify a [`Self::decide`] miss — i.e. when `decide` returned/// `Ok(None)` because its conditional `UPDATE ... WHERE decided_at IS NULL`/// matched 0 rows. Two very different states collapse into that `None`:@@ -199,15 +118,6 @@ impl ApprovalGate {store::list_pending(&self.config)}- /// [`Self::list_pending`] narrowed to `agent`'s rows; `None` lists the- /// process's own rows.- pub fn list_pending_for_agent(- &self,- agent: Option<&str>,- ) -> anyhow::Result<Vec<PendingApproval>> {- store::list_pending_for_agent(&self.config, agent)- }-/// List recently decided rows for durable audit views.pub fn list_recent_decisions(&self,@@ -303,21 +213,10 @@ impl ApprovalGate {waiters.remove(request_id);}- /// The request_id of the approval currently parked on `thread_id` by the- /// ambient context's agent, if any. Used by the web channel to route an- /// inbound yes/no reply to a decision.+ /// The request_id of the approval currently parked on `thread_id`, if any.+ /// Used by the web channel to route an inbound yes/no reply to a decision.pub fn pending_for_thread(&self, thread_id: &str) -> Option<String> {- let agent = crate::core::runtime::agent_scope::current_agent_id();- self.pending_for_agent_thread(agent.as_deref(), thread_id)- }-- /// The request_id `agent` (`None`: the process) has parked on- /// `thread_id`, if any.- pub fn pending_for_agent_thread(&self, agent: Option<&str>, thread_id: &str) -> Option<String> {- self.thread_to_request- .lock()- .get(&thread_route_key(agent, thread_id))- .cloned()+ self.thread_to_request.lock().get(thread_id).cloned()}/// The full pending row parked on `thread_id`, if any.@@ -365,9 +264,9 @@ impl ApprovalGate {}/// Drop the thread → request mapping when it still belongs to this request.- fn clear_thread(&self, thread_key: &Option<String>, request_id: &str) {- if let Some(key) = thread_key {- self.clear_thread_route_if_owned(key, request_id);+ fn clear_thread(&self, thread_id: &Option<String>, request_id: &str) {+ if let Some(t) = thread_id {+ self.clear_thread_route_if_owned(t, request_id);}}@@ -376,10 +275,10 @@ impl ApprovalGate {/// replacement turn may have already parked a new approval on the same/// thread and overwritten the entry; clearing unconditionally would delete/// the *new* request's routing (#4774).- fn clear_thread_route_if_owned(&self, thread_key: &str, request_id: &str) {+ fn clear_thread_route_if_owned(&self, thread_id: &str, request_id: &str) {let mut map = self.thread_to_request.lock();- if map.get(thread_key).is_some_and(|rid| rid == request_id) {- map.remove(thread_key);+ if map.get(thread_id).is_some_and(|rid| rid == request_id) {+ map.remove(thread_id);}}}diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rsindex 3704352a6d..5f3cbaa109 100644--- a/crates/openhuman-core/src/security/approval/gate_tests.rs+++ b/crates/openhuman-core/src/security/approval/gate_tests.rs@@ -198,8 +198,6 @@ async fn find_approval_decided(}}-#[path = "gate_agent_tests.rs"]-mod agent_tests;#[path = "gate_core_flow_tests.rs"]mod core_flow_tests;#[path = "gate_forced_tests.rs"]diff --git a/crates/openhuman-core/src/security/approval/mod.rs b/crates/openhuman-core/src/security/approval/mod.rsindex 6fbb54fff2..4acf392c89 100644--- a/crates/openhuman-core/src/security/approval/mod.rs+++ b/crates/openhuman-core/src/security/approval/mod.rs@@ -22,8 +22,8 @@ mod store_documents;pub mod types;pub use gate::{- parse_approval_reply, ApprovalChatContext, ApprovalError, ApprovalGate, FlowRunContext,- APPROVAL_CHAT_CONTEXT, APPROVAL_COPILOT_STREAM_CONTEXT, APPROVAL_FLOW_RUN_CONTEXT,+ parse_approval_reply, ApprovalChatContext, ApprovalGate, FlowRunContext, APPROVAL_CHAT_CONTEXT,+ APPROVAL_COPILOT_STREAM_CONTEXT, APPROVAL_FLOW_RUN_CONTEXT,};pub use redact::{redact_args, summarize_action};pub use schemas::all_controller_schemas as all_approval_controller_schemas;diff --git a/crates/openhuman-core/src/security/approval/rpc.rs b/crates/openhuman-core/src/security/approval/rpc.rsindex 401674d190..f5f50a65e2 100644--- a/crates/openhuman-core/src/security/approval/rpc.rs+++ b/crates/openhuman-core/src/security/approval/rpc.rs@@ -48,24 +48,13 @@ pub async fn approval_get_gate_state() -> anyhow::Result<Outcome<ApprovalGateBoo/// Returns an empty list (not an error) when the gate is not/// installed — supervised mode may be disabled, in which case there/// is nothing pending by definition.-///-/// `agent_id` narrows the list to the rows one embedded agent parked.-pub async fn approval_list_pending(- agent_id: Option<&str>,-) -> anyhow::Result<Outcome<Vec<PendingApproval>>> {- tracing::debug!(- agent_id = agent_id.unwrap_or("<all>"),- "[rpc:approval_list_pending] entry"- );+pub async fn approval_list_pending() -> anyhow::Result<Outcome<Vec<PendingApproval>>> {+ tracing::debug!("[rpc:approval_list_pending] entry");let Some(gate) = ApprovalGate::try_global() else {tracing::debug!("[rpc:approval_list_pending] gate not installed, returning empty");return Ok(Outcome::new(Vec::new(), vec![]));};- let listed = match agent_id {- Some(agent) => gate.list_pending_for_agent(Some(agent)),- None => gate.list_pending(),- };- let rows = match listed {+ let rows = match gate.list_pending() {Ok(rows) => rows,Err(err) => {tracing::error!(error = %err, "[rpc:approval_list_pending] store error");@@ -199,17 +188,14 @@ pub async fn approval_preauthorize_flow(}/// Apply a decision to a pending row. Errors when the request id is-/// unknown / already decided / belongs to a different session. With-/// `agent_id`, also errors when the request belongs to another agent.+/// unknown / already decided / belongs to a different session.pub async fn approval_decide(request_id: &str,decision: ApprovalDecision,- agent_id: Option<&str>,) -> anyhow::Result<Outcome<PendingApproval>> {tracing::debug!(request_id = request_id,decision = decision.as_str(),- agent_id = agent_id.unwrap_or("<any>"),"[rpc:approval_decide] entry");let gate = ApprovalGate::try_global().ok_or_else(|| {@@ -219,11 +205,7 @@ pub async fn approval_decide();anyhow!("approval gate is not installed; supervised mode disabled")})?;- let decided = match agent_id {- Some(agent) => gate.decide_for_agent(agent, request_id, decision),- None => gate.decide(request_id, decision),- };- let decided = match decided {+ let decided = match gate.decide(request_id, decision) {Ok(row) => row,Err(err) => {tracing::error!(@@ -281,17 +263,7 @@ pub async fn approval_decide(// `gate.decide` already resolved the current call, so a persistence failure// must not fail the RPC. It degrades safely — the tool simply prompts again// next time rather than being silently auto-approved.- if decision == ApprovalDecision::ApproveAlwaysForTool && row.agent_id.is_some() {- tracing::info!(- tool = row.tool_name.as_str(),- agent_id = row.agent_id.as_deref().unwrap_or(""),- "[rpc:approval_decide] agent request approved once; the process allowlist is not widened"- );- logs.push(format!(- "[approval] '{}' approved; an agent's 'Always allow' comes from its own access",- row.tool_name- ));- } else if decision == ApprovalDecision::ApproveAlwaysForTool {+ if decision == ApprovalDecision::ApproveAlwaysForTool {match crate::config::ops::add_auto_approve_tool(&row.tool_name).await {Ok(()) => {tracing::info!(diff --git a/crates/openhuman-core/src/security/approval/schemas.rs b/crates/openhuman-core/src/security/approval/schemas.rsindex b040ecafc5..d300611c03 100644--- a/crates/openhuman-core/src/security/approval/schemas.rs+++ b/crates/openhuman-core/src/security/approval/schemas.rs@@ -54,12 +54,7 @@ pub fn schemas(function: &str) -> ControllerSchema {function: "list_pending",description:"List pending approval requests awaiting a user decision in the current session.",- inputs: vec![FieldSchema {- name: "agent_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Only the requests this embedded agent parked. Omit to list every request.",- required: false,- }],+ inputs: vec![],outputs: vec![FieldSchema {name: "pending",ty: TypeSchema::Array(Box::new(TypeSchema::Ref("PendingApproval"))),@@ -118,13 +113,6 @@ pub fn schemas(function: &str) -> ControllerSchema {source_context names a flow), or \"deny\".",required: true,},- FieldSchema {- name: "agent_id",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Decide as this embedded agent; refused when the request belongs to \- another agent.",- required: false,- },],outputs: vec![FieldSchema {name: "decided",@@ -179,10 +167,9 @@ pub fn schemas(function: &str) -> ControllerSchema {}}-fn handle_list_pending(params: Map<String, Value>) -> ControllerFuture {+fn handle_list_pending(_params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {- let agent_id = read_optional_string(¶ms, "agent_id")?;- let outcome = approval_rpc::approval_list_pending(agent_id.as_deref())+ let outcome = approval_rpc::approval_list_pending().await.map_err(|e| e.to_string())?;to_json(outcome)@@ -218,11 +205,9 @@ fn handle_decide(params: Map<String, Value>) -> ControllerFuture {approve_once|approve_always_for_tool|approve_always_for_flow|deny, got '{decision_str}'")})?;- let agent_id = read_optional_string(¶ms, "agent_id")?;- let outcome =- approval_rpc::approval_decide(request_id.trim(), decision, agent_id.as_deref())- .await- .map_err(|e| e.to_string())?;+ let outcome = approval_rpc::approval_decide(request_id.trim(), decision)+ .await+ .map_err(|e| e.to_string())?;to_json(outcome)})}@@ -270,17 +255,6 @@ fn read_optional_u64(params: &Map<String, Value>, key: &str) -> Result<Option<u6}}-fn read_optional_string(params: &Map<String, Value>, key: &str) -> Result<Option<String>, String> {- match params.get(key) {- Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(s.trim().to_string())),- Some(Value::String(_)) | Some(Value::Null) | None => Ok(None),- Some(other) => Err(format!(- "invalid '{key}': expected string, got {}",- type_name(other)- )),- }-}-fn read_required_string(params: &Map<String, Value>, key: &str) -> Result<String, String> {match params.get(key) {Some(Value::String(s)) => Ok(s.clone()),diff --git a/crates/openhuman-core/src/security/approval/schemas_tests.rs b/crates/openhuman-core/src/security/approval/schemas_tests.rsindex c8942e90f0..8b1686ec95 100644--- a/crates/openhuman-core/src/security/approval/schemas_tests.rs+++ b/crates/openhuman-core/src/security/approval/schemas_tests.rs@@ -2,13 +2,11 @@ use super::*;use serde_json::json;#[test]-fn schemas_list_pending_takes_only_an_optional_agent() {+fn schemas_list_pending_has_no_inputs() {let s = schemas("list_pending");assert_eq!(s.namespace, "approval");assert_eq!(s.function, "list_pending");- assert_eq!(s.inputs.len(), 1);- assert_eq!(s.inputs[0].name, "agent_id");- assert!(!s.inputs[0].required);+ assert!(s.inputs.is_empty());}#[test]@@ -17,11 +15,7 @@ fn schemas_decide_requires_request_id_and_decision() {let names: Vec<_> = s.inputs.iter().map(|f| f.name).collect();assert!(names.contains(&"request_id"));assert!(names.contains(&"decision"));- assert!(s- .inputs- .iter()- .all(|f| f.required == (f.name != "agent_id")));- assert!(names.contains(&"agent_id"));+ assert!(s.inputs.iter().all(|f| f.required));}#[test]diff --git a/crates/openhuman-core/src/security/approval/store.rs b/crates/openhuman-core/src/security/approval/store.rsindex 81e467a169..e952d5f6bb 100644--- a/crates/openhuman-core/src/security/approval/store.rs+++ b/crates/openhuman-core/src/security/approval/store.rs@@ -135,10 +135,6 @@ fn migrate_columns(conn: &Connection) -> Result<()> {"tool_call_id","ALTER TABLE pending_approvals ADD COLUMN tool_call_id TEXT",),- (- "agent_id",- "ALTER TABLE pending_approvals ADD COLUMN agent_id TEXT",- ),] {if !have.contains(col) {// Two cores can open the same workspace during startup (for@@ -154,12 +150,6 @@ fn migrate_columns(conn: &Connection) -> Result<()> {tracing::info!(column = col, "[approval::store] migrated v1 schema");}}- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_pending_approvals_agent- ON pending_approvals(agent_id, decided_at)",- params![],- )- .context("[approval::store] create agent index")?;Ok(())}@@ -202,14 +192,10 @@ fn migrate_session_id_scrub(conn: &Connection) -> Result<()> {Ok(())}-fn db_path(config: &Config) -> std::path::PathBuf {- config.workspace_dir.join("approval").join("approval.db")-}-/// 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 = db_path(config);+ let db_path = config.workspace_dir.join("approval").join("approval.db");tracing::trace!(path = %db_path.display(),@@ -262,8 +248,8 @@ pub fn insert_pending(config: &Config, pending: &PendingApproval, session_id: &sconn.execute("INSERT INTO pending_approvals(request_id, tool_name, action_summary, args_redacted,- session_id, created_at, expires_at, source_context, tool_call_id, agent_id)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",+ session_id, created_at, expires_at, source_context, tool_call_id)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",params![pending.request_id,pending.tool_name,@@ -274,7 +260,6 @@ pub fn insert_pending(config: &Config, pending: &PendingApproval, session_id: &sexpires,source_context,pending.tool_call_id,- pending.agent_id,],).context("[approval::store] insert pending row")?;@@ -315,7 +300,7 @@ pub fn list_pending(config: &Config) -> Result<Vec<PendingApproval>> {let mut stmt = conn.prepare("SELECT request_id, tool_name, action_summary, args_redacted,- session_id, created_at, expires_at, source_context, tool_call_id, agent_id+ session_id, created_at, expires_at, source_context, tool_call_idFROM pending_approvalsWHERE decided_at IS NULLORDER BY created_at ASC",@@ -420,7 +405,7 @@ pub fn decide(let mut stmt = conn.prepare("SELECT request_id, tool_name, action_summary, args_redacted,- session_id, created_at, expires_at, source_context, tool_call_id, agent_id+ session_id, created_at, expires_at, source_context, tool_call_idFROM pending_approvals WHERE request_id = ?1",).context("[approval::store] prepare select decided")?;@@ -590,7 +575,7 @@ fn expire_stale_with_now(conn: &Connection, now: DateTime<Utc>) -> Result<Vec<Pelet mut stmt = conn.prepare("SELECT request_id, tool_name, action_summary, args_redacted,- session_id, created_at, expires_at, source_context, tool_call_id, agent_id+ session_id, created_at, expires_at, source_context, tool_call_idFROM pending_approvalsWHERE decided_at IS NULLAND expires_at IS NOT NULL@@ -640,7 +625,6 @@ fn publish_expired(expired: &[PendingApproval]) {client_id: None,tool_call_id: row.tool_call_id.clone(),resolution: Some("expired".to_string()),- agent_id: row.agent_id.clone(),});}}@@ -715,7 +699,6 @@ fn row_to_pending(row: &rusqlite::Row<'_>) -> rusqlite::Result<PendingApproval>// Column 8 (`tool_call_id`) is likewise absent on rows written before// this field existed — tolerate a missing-column read error as `None`.let tool_call_id: Option<String> = row.get(8).unwrap_or(None);- let agent_id: Option<String> = row.get(9).unwrap_or(None);// Note: column index 4 (`session_id`) is read on the SELECT but// intentionally not surfaced — see `PendingApproval` doc-comment.@@ -728,7 +711,6 @@ fn row_to_pending(row: &rusqlite::Row<'_>) -> rusqlite::Result<PendingApproval>expires_at: expires_opt.as_deref().map(parse_rfc3339),source_context,tool_call_id,- agent_id,})}@@ -738,10 +720,6 @@ fn parse_rfc3339(input: &str) -> DateTime<Utc> {.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 --git a/crates/openhuman-core/src/security/approval/store_documents.rs b/crates/openhuman-core/src/security/approval/store_documents.rsindex 0f423d9f0c..a5a2e2b7fa 100644--- a/crates/openhuman-core/src/security/approval/store_documents.rs+++ b/crates/openhuman-core/src/security/approval/store_documents.rs@@ -110,7 +110,6 @@ fn to_pending(stored: &Versioned<Value>) -> PendingApproval {.ok()}),tool_call_id: text(doc, "tool_call_id").map(str::to_string),- agent_id: text(doc, "agent_id").map(str::to_string),}}@@ -186,7 +185,6 @@ impl Docs {.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();@@ -272,18 +270,6 @@ impl Docs {})}- /// 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 {diff --git a/crates/openhuman-core/src/security/approval/store_documents_tests.rs b/crates/openhuman-core/src/security/approval/store_documents_tests.rsindex e8b3758249..d1732b8493 100644--- a/crates/openhuman-core/src/security/approval/store_documents_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_documents_tests.rs@@ -25,7 +25,6 @@ fn pending(id: &str, created_secs_ago: i64, expires_in: Option<i64>) -> PendingAnode_id: None,}),tool_call_id: Some(format!("call-{id}")),- agent_id: None,}}@@ -373,27 +372,3 @@ fn expiry_is_compared_below_a_millisecond() {.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 --git a/crates/openhuman-core/src/security/approval/store_persistence_tests.rs b/crates/openhuman-core/src/security/approval/store_persistence_tests.rsindex a81c6e3bb0..96f251e990 100644--- a/crates/openhuman-core/src/security/approval/store_persistence_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_persistence_tests.rs@@ -664,84 +664,3 @@ fn list_recent_decisions_marks_unparseable_args_instead_of_failing() {json!({ "_error": "args_redacted not valid JSON" }));}--#[test]-fn agent_id_round_trips_and_older_rows_read_as_the_process() {- let (config, _dir) = test_config();- let mut owned = PendingApproval::new("owned", "shell", "run it", json!({}), None);- owned.agent_id = Some("alpha".into());- insert_pending(&config, &owned, "session-x").unwrap();- insert_pending(- &config,- &PendingApproval::new("process", "shell", "run it", json!({}), None),- "session-x",- )- .unwrap();-- let alpha = list_pending_for_agent(&config, Some("alpha")).unwrap();- assert_eq!(alpha.len(), 1);- assert_eq!(alpha[0].request_id, "owned");- assert_eq!(alpha[0].agent_id.as_deref(), Some("alpha"));- let process = list_pending_for_agent(&config, None).unwrap();- assert_eq!(process.len(), 1);- assert_eq!(process[0].request_id, "process");-- assert_eq!(- pending_agent(&config, "owned").unwrap(),- Some(Some("alpha".into()))- );- assert_eq!(pending_agent(&config, "process").unwrap(), Some(None));- assert_eq!(pending_agent(&config, "missing").unwrap(), None);- decide(&config, "owned", ApprovalDecision::Deny).unwrap();- assert_eq!(pending_agent(&config, "owned").unwrap(), None);-}--#[test]-fn migration_adds_the_agent_column_and_index_to_an_existing_table() {- let (config, _dir) = test_config();- let db_path = config.workspace_dir.join("approval").join("approval.db");- std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();- Connection::open(&db_path)- .unwrap()- .execute_batch(- "CREATE TABLE pending_approvals (- request_id TEXT PRIMARY KEY,- tool_name TEXT NOT NULL,- action_summary TEXT NOT NULL,- args_redacted TEXT NOT NULL,- session_id TEXT NOT NULL,- created_at TEXT NOT NULL,- expires_at TEXT,- decided_at TEXT,- decision TEXT- );- INSERT INTO pending_approvals- (request_id, tool_name, action_summary, args_redacted, session_id, created_at)- VALUES ('legacy', 'shell', 'legacy row', '{}', 'sess-X', '2030-01-01T00:00:00Z');",- )- .unwrap();-- let rows = list_pending(&config).unwrap();- assert_eq!(rows.len(), 1);- assert!(- rows[0].agent_id.is_none(),- "a legacy row is the process's own"- );- let conn = Connection::open(&db_path).unwrap();- let columns: Vec<String> = conn- .prepare("PRAGMA table_info(pending_approvals)")- .unwrap()- .query_map(params![], |row| row.get::<_, String>(1))- .unwrap()- .map(Result::unwrap)- .collect();- assert!(columns.iter().any(|c| c == "agent_id"));- let indexes: Vec<String> = conn- .prepare("PRAGMA index_list(pending_approvals)")- .unwrap()- .query_map(params![], |row| row.get::<_, String>(1))- .unwrap()- .map(Result::unwrap)- .collect();- assert!(indexes.iter().any(|i| i == "idx_pending_approvals_agent"));-}diff --git a/crates/openhuman-core/src/security/approval/store_tests.rs b/crates/openhuman-core/src/security/approval/store_tests.rsindex e9194ccc5c..8293a64bd4 100644--- a/crates/openhuman-core/src/security/approval/store_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_tests.rs@@ -49,7 +49,6 @@ fn sample_with_expiry(expires_at,source_context: None,tool_call_id: None,- agent_id: None,}}diff --git a/crates/openhuman-core/src/security/approval/types.rs b/crates/openhuman-core/src/security/approval/types.rsindex 2bdc77a847..367617b5be 100644--- a/crates/openhuman-core/src/security/approval/types.rs+++ b/crates/openhuman-core/src/security/approval/types.rs@@ -42,10 +42,6 @@ pub struct PendingApproval {/// workflows) and for rows persisted before this field existed.#[serde(default, skip_serializing_if = "Option::is_none")]pub tool_call_id: Option<String>,- /// The embedded agent whose turn parked this call. `None` for the- /// process's own sessions and for rows persisted before this field.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub agent_id: Option<String>,}impl PendingApproval {@@ -67,7 +63,6 @@ impl PendingApproval {expires_at,source_context: None,tool_call_id: None,- agent_id: None,}}@@ -79,12 +74,6 @@ impl PendingApproval {self.source_context = Some(ctx);self}-- /// Whether this row is visible to `agent`: `None` sees the process's own- /// rows, `Some(id)` sees only that agent's.- pub fn belongs_to(&self, agent: Option<&str>) -> bool {- self.agent_id.as_deref() == agent- }}/// Correlation context for a [`PendingApproval`] raised from a source otherdiff --git a/crates/openhuman-core/src/security/approval/types_tests.rs b/crates/openhuman-core/src/security/approval/types_tests.rsindex 08f5e26129..d6192174d2 100644--- a/crates/openhuman-core/src/security/approval/types_tests.rs+++ b/crates/openhuman-core/src/security/approval/types_tests.rs@@ -142,7 +142,6 @@ fn pending_approval_debug_and_serialize_do_not_carry_session_id() {expires_at: None,source_context: None,tool_call_id: None,- agent_id: None,};let dbg = format!("{p:?}");assert!(diff --git a/crates/openhuman-core/src/security/live_policy.rs b/crates/openhuman-core/src/security/live_policy.rsindex f2b4d52f49..7b0c76d3a8 100644--- a/crates/openhuman-core/src/security/live_policy.rs+++ b/crates/openhuman-core/src/security/live_policy.rs@@ -175,21 +175,6 @@ pub fn current() -> Option<Arc<SecurityPolicy>> {.and_then(|s| s.policy.read().ok().map(|g| Arc::clone(&g)))}-/// The policy a call should be answered against: the ambient agent context's-/// own policy when it carries one, else the process-global [`current`] policy.-pub fn effective() -> Option<Arc<SecurityPolicy>> {- if let Some(policy) = crate::core::runtime::CoreContext::current_agent_policy() {- return Some(policy);- }- if let Some(agent) = crate::core::runtime::agent_scope::current_agent_id() {- tracing::trace!(- agent_id = %agent,- "[security:live_policy] agent context carries no policy; using the process policy"- );- }- current()-}-/// Reload counter — incremented on every [`reload_from`]. Observability/tests.pub fn generation() -> u64 {STATEdiff --git a/crates/openhuman-core/src/security/live_policy_tests.rs b/crates/openhuman-core/src/security/live_policy_tests.rsindex 436cc9edbd..b4cb45fd81 100644--- a/crates/openhuman-core/src/security/live_policy_tests.rs+++ b/crates/openhuman-core/src/security/live_policy_tests.rs@@ -178,57 +178,3 @@ fn set_action_dir_swaps_root_and_bumps_generation() {"reload after set_action_dir must keep the swapped root");}--fn agent_context(policy: Option<Arc<SecurityPolicy>>) -> Arc<crate::core::runtime::CoreContext> {- use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};- let parent = CoreContext::for_test(DomainSet::full(), Some(std::env::temp_dir()));- let mut config = crate::config::Config::default();- config.workspace_dir = std::env::temp_dir().join("openhuman_effective_policy_test");- let mut overlay = ContextOverlay::new(- config,- DomainSet::kernel(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent("effective-agent");- overlay.agent_policy = policy;- parent.derive_with(overlay)-}--#[tokio::test]-async fn effective_prefers_the_agent_policy_over_the_process_policy() {- let workspace = std::env::temp_dir().join("openhuman_effective_policy_test");- let process = Arc::new(SecurityPolicy {- auto_approve_all: true,- autonomy: AutonomyLevel::Full,- ..SecurityPolicy::default()- });- let _guard = install_scoped(Arc::clone(&process), workspace.clone(), workspace);- let agent = Arc::new(SecurityPolicy {- auto_approve_all: false,- autonomy: AutonomyLevel::ReadOnly,- auto_approve: vec!["agent_only_tool".into()],- ..SecurityPolicy::default()- });-- let seen =- crate::core::runtime::CoreContext::scope(agent_context(Some(Arc::clone(&agent))), async {- effective().expect("agent policy")- })- .await;- assert!(Arc::ptr_eq(&seen, &agent));- assert!(!seen.auto_approve_all);- assert_eq!(seen.autonomy, AutonomyLevel::ReadOnly);-- assert!(Arc::ptr_eq(&effective().expect("process policy"), &process));-}--#[tokio::test]-async fn effective_falls_back_to_the_process_policy_for_an_agent_without_one() {- let workspace = std::env::temp_dir().join("openhuman_effective_policy_test");- let process = Arc::new(SecurityPolicy::default());- let _guard = install_scoped(Arc::clone(&process), workspace.clone(), workspace);-- let seen =- crate::core::runtime::CoreContext::scope(agent_context(None), async { effective() }).await;- assert!(Arc::ptr_eq(&seen.expect("process policy"), &process));-}diff --git a/crates/openhuman-core/src/skills/mod.rs b/crates/openhuman-core/src/skills/mod.rsindex 35e5594d66..b6a443c49e 100644--- a/crates/openhuman-core/src/skills/mod.rs+++ b/crates/openhuman-core/src/skills/mod.rs@@ -73,8 +73,6 @@ pub mod schemas;pub mod search;#[cfg(feature = "skills")]pub mod tools;-#[cfg(feature = "skills")]-pub mod write_root;#[cfg(all(test, feature = "skills"))]#[path = "e2e_plumbing_tests.rs"]diff --git a/crates/openhuman-core/src/skills/ops_create.rs b/crates/openhuman-core/src/skills/ops_create.rsindex c6c212ee53..d93834a525 100644--- a/crates/openhuman-core/src/skills/ops_create.rs+++ b/crates/openhuman-core/src/skills/ops_create.rs@@ -172,8 +172,9 @@ pub(crate) fn create_workflow_inner(let scope_root = match params.scope {WorkflowScope::User => {- crate::skills::write_root::user_workflow_root(workspace_dir, home_dir)- .ok_or_else(|| "could not resolve user home directory".to_string())?+ let home =+ home_dir.ok_or_else(|| "could not resolve user home directory".to_string())?;+ home.join(".openhuman").join("workflows")}WorkflowScope::Project => {if !is_workspace_trusted(workspace_dir) {diff --git a/crates/openhuman-core/src/skills/ops_discover/api.rs b/crates/openhuman-core/src/skills/ops_discover/api.rsindex 8a7cc4002c..b3553f2a30 100644--- a/crates/openhuman-core/src/skills/ops_discover/api.rs+++ b/crates/openhuman-core/src/skills/ops_discover/api.rs@@ -11,7 +11,7 @@ use crate::skills::ops_types::{Workflow, TRUST_MARKER};use super::scan::{discover_filtered, ALL_ROOT_KINDS, WORKFLOW_ROOT_KINDS};-type MetadataCacheKey = (PathBuf, Option<PathBuf>, bool, Option<String>);+type MetadataCacheKey = (PathBuf, Option<PathBuf>, bool);static METADATA_CACHE: LazyLock<RwLock<HashMap<MetadataCacheKey, Vec<Workflow>>>> =LazyLock::new(|| RwLock::new(HashMap::new()));static METADATA_GENERATION: AtomicU64 = AtomicU64::new(0);@@ -83,12 +83,7 @@ pub fn discovery_home_dir() -> Option<PathBuf> {pub fn load_workflow_metadata(workspace_dir: &Path) -> Vec<Workflow> {let trusted = is_workspace_trusted(workspace_dir);let home = discovery_home_dir();- let key = (- workspace_dir.to_path_buf(),- home.clone(),- trusted,- crate::core::runtime::agent_scope::current_agent_id(),- );+ let key = (workspace_dir.to_path_buf(), home.clone(), trusted);if let Ok(cache) = METADATA_CACHE.read() {if let Some(workflows) = cache.get(&key) {return workflows.clone();diff --git a/crates/openhuman-core/src/skills/ops_discover/scan.rs b/crates/openhuman-core/src/skills/ops_discover/scan.rsindex f9e8ddfeed..647519880a 100644--- a/crates/openhuman-core/src/skills/ops_discover/scan.rs+++ b/crates/openhuman-core/src/skills/ops_discover/scan.rs@@ -81,21 +81,6 @@ pub(super) fn discover_filtered(}}- if let Some(agent_home) = workspace_dir.and_then(crate::skills::write_root::agent_skill_home) {- let [skills, workflows] = crate::skills::write_root::agent_user_roots(&agent_home);- for (root, kind) in [(skills, RootKind::Skill), (workflows, RootKind::Workflow)] {- if kinds.contains(&kind) {- tracing::trace!(- root = %root.display(),- ?kind,- scope = ?WorkflowScope::User,- "[workflows] discover:branch:agent"- );- discovered.extend(scan_root(&root, WorkflowScope::User));- }- }- }-if let Some(ws) = workspace_dir {if trusted {for (root, kind) in project_roots(ws) {diff --git a/crates/openhuman-core/src/skills/ops_install/fetch.rs b/crates/openhuman-core/src/skills/ops_install/fetch.rsindex 347e590cab..0de2363420 100644--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs@@ -271,8 +271,10 @@ pub(crate) fn install_validated_document(.map(|s| s.name).collect();- 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 skills_root = home+ .ok_or_else(|| "write failed: unable to resolve home directory".to_string())?+ .join(".openhuman")+ .join("skills");let target_file =match write_installed_document(&skills_root, &slug, &content).map_err(|e| e.to_string())? {diff --git a/crates/openhuman-core/src/skills/ops_install/uninstall.rs b/crates/openhuman-core/src/skills/ops_install/uninstall.rsindex 4416884cdf..d4239a9b4f 100644--- a/crates/openhuman-core/src/skills/ops_install/uninstall.rs+++ b/crates/openhuman-core/src/skills/ops_install/uninstall.rs@@ -54,17 +54,11 @@ pub fn uninstall_workflow(// uninstalled). Slug validation and the symlink/containment/bundle checks// are owned by `tinyskills::remove_bundle`.let openhuman_dir = home.join(".openhuman");- let roots: Vec<_> = match crate::skills::write_root::current_agent_skill_home() {- Some(agent_home) => crate::skills::write_root::agent_user_roots(&agent_home)- .into_iter()- .rev()- .collect(),- None => vec![- openhuman_dir.join("workflows"),- openhuman_dir.join("skills"),- home.join(".agents").join("skills"),- ],- };+ let roots = [+ openhuman_dir.join("workflows"),+ openhuman_dir.join("skills"),+ home.join(".agents").join("skills"),+ ];let removed = tinyskills::remove_bundle(&roots, &trimmed).map_err(|e| {log::warn!("[skills] uninstall_workflow: refused name={trimmed:?} error={e}");diff --git a/crates/openhuman-core/src/tools/impl/browser/browser.rs b/crates/openhuman-core/src/tools/impl/browser/browser.rsindex f7e75d3e7a..b6394460fb 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs@@ -543,8 +543,10 @@ impl Tool for BrowserTool {context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {if let Some(thread_id) = context.and_then(ToolRunContext::thread_id) {- let scope = crate::core::runtime::agent_scope_dir(self.client.config());- let key = format!("{}:{thread_id}", scope.display());+ let key = format!(+ "{}:{thread_id}",+ self.client.config().workspace_dir.display()+ );if let Ok(mut held) = self.thread_key.lock() {*held = Some(key);}diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs b/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rsindex fca3451070..2a10850e9d 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser_computer_tests.rs@@ -437,46 +437,3 @@ fn a_task_that_found_no_chrome_tells_the_agent_to_ask_for_its_path() {None);}--struct ThreadOnly(&'static str);--impl tinytools::ToolRunContext for ThreadOnly {- fn thread_id(&self) -> Option<&str> {- Some(self.0)- }-}--#[tokio::test]-async fn two_agents_on_one_thread_get_distinct_browser_session_keys() {- use crate::core::runtime::agent_scope::test_agent_context;- use crate::core::runtime::{context::CoreContext, DomainSet};- let root = CoreContext::for_test(DomainSet::full(), None);- let client = Arc::new(BrowserClient::new(Arc::new(- crate::config::Config::default(),- )));- let key_under = |ctx: Arc<CoreContext>| {- let client = client.clone();- async move {- CoreContext::scope(ctx, async move {- let tool = BrowserTool::new(Arc::new(SecurityPolicy::default()), client, 3);- let _ = tool- .execute_with_context(- json!({}),- ToolCallOptions::default(),- Some(&ThreadOnly("browser-shared-thread")),- )- .await;- let key = tool.thread_key.lock().unwrap().clone();- drop(tool);- key- })- .await- }- };-- let alpha = key_under(test_agent_context(&root, "alpha")).await;- let beta = key_under(test_agent_context(&root, "beta")).await;-- assert!(alpha.is_some() && beta.is_some());- assert_ne!(alpha, beta);-}diff --git a/crates/openhuman-core/src/tools/orchestrator_tools_tests.rs b/crates/openhuman-core/src/tools/orchestrator_tools_tests.rsindex a860256ce3..50f7930dd1 100644--- a/crates/openhuman-core/src/tools/orchestrator_tools_tests.rs+++ b/crates/openhuman-core/src/tools/orchestrator_tools_tests.rs@@ -31,7 +31,6 @@ fn def(id: &str, when_to_use: &str, delegate_name: Option<&str>) -> AgentDefinitsubagents: vec![],delegate_name: delegate_name.map(String::from),agent_tier: crate::agent::harness::definition::AgentTier::Worker,- searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}diff --git a/crates/openhuman-core/src/web_chat/README.md b/crates/openhuman-core/src/web_chat/README.mdindex deb6aba4da..ced93a3c70 100644--- a/crates/openhuman-core/src/web_chat/README.md+++ b/crates/openhuman-core/src/web_chat/README.md@@ -72,10 +72,10 @@ subscriber all listen to.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` tablekeyed 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@@ -85,7 +85,7 @@ subscriber all listen to.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 neverdrive one agent. It is reused when its `SessionCacheFingerprint` stillmatches; otherwise a new agent is built. A new agent needs no historyseeding: `set_thread_id` binds the session's durable identity@@ -143,7 +143,7 @@ events (they become the turn's reply text), so they carry no key.Background-delivery notices (`agent::orchestration::background_delivery`) andgoal 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 returnthe reply text for the caller to deliver. They still go through the samesession checkout, so the model sees the conversation and the turn lands in the@@ -226,9 +226,9 @@ and artifact bridges itself (`openhuman-tui/src/runner.rs`).| [`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`. 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/state.rs`](./ops/state.rs) | `THREAD_SESSIONS`, `IN_FLIGHT`, `PARALLEL_IN_FLIGHT`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`. || [`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. |@@ -317,7 +317,7 @@ because the in-app chat is core product surface (#5002).- Attachment staging must stay ahead of prompt scanning and persistence.- A reply persistence error is non-fatal: the reply is announced anyway, sincethe 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 norget 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`,diff --git a/crates/openhuman-core/src/web_chat/event_bus.rs b/crates/openhuman-core/src/web_chat/event_bus.rsindex 1479e9b50d..6004d6b3f1 100644--- a/crates/openhuman-core/src/web_chat/event_bus.rs+++ b/crates/openhuman-core/src/web_chat/event_bus.rs@@ -618,7 +618,6 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {client_id,tool_call_id,expires_at,- agent_id: _,} => match (thread_id, client_id) {(Some(thread_id), Some(client_id)) => {log::info!(@@ -651,7 +650,6 @@ impl EventHandler<DomainEvent> for ApprovalSurfaceSubscriber {client_id,tool_call_id,resolution,- agent_id: _,} => match (thread_id, client_id) {(Some(thread_id), Some(client_id)) => {log::info!(diff --git a/crates/openhuman-core/src/web_chat/event_bus_tests.rs b/crates/openhuman-core/src/web_chat/event_bus_tests.rsindex 5dacc98e92..db165ab3fe 100644--- a/crates/openhuman-core/src/web_chat/event_bus_tests.rs+++ b/crates/openhuman-core/src/web_chat/event_bus_tests.rs@@ -443,7 +443,6 @@ async fn approval_surface_bridges_approval_decided_with_resolution() {client_id: Some("client-decided-1".to_string()),tool_call_id: Some("call-decided-1".to_string()),resolution: Some("expired".to_string()),- agent_id: None,});let ev = find_agent_web_event(&mut web_rx, "approval_decided", "thread-decided-1").await;@@ -470,7 +469,6 @@ async fn approval_surface_drops_approval_decided_without_chat_routing() {client_id: None,tool_call_id: None,resolution: Some("expired".to_string()),- agent_id: None,});// A sibling event we know fires, so we don't just race an empty channel.crate::core::bus::BUS.publish(DomainEvent::ThreadGoalCleared {diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rsindex 572e6e48d9..1157ab33df 100644--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@ -28,13 +28,13 @@ pub use system_turn::{run_system_turn_on_thread, SESSION_CHECKOUT_FAILURE, SYSTE#[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;-pub(super) use state::thread_sessions;+#[cfg(test)]+pub(crate) use state::IN_FLIGHT;+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 --git a/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs b/crates/openhuman-core/src/web_chat/ops/budget_correlation.rsindex 3de3895fa9..c965fdf2e4 100644--- a/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs+++ b/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs@@ -6,9 +6,9 @@//! actionable out-of-credits copy.use std::collections::HashMap;-use std::sync::Arc;use std::time::{Duration, Instant};+use once_cell::sync::Lazy;use tokio::sync::Mutex;use super::state::key_for;@@ -40,11 +40,8 @@ struct BudgetSignal {/// Kept in a sibling map rather than on `SessionEntry` so the signal survives/// the de-poison session drop (an empty turn is not poisoned, but cold-boot/// reseeds would otherwise be the wrong lifetime to hang this on).-fn thread_budget_signals() -> Arc<ThreadBudgetSignals> {- crate::core::runtime::current_slot::<ThreadBudgetSignals>()-}--type ThreadBudgetSignals = Mutex<HashMap<String, BudgetSignal>>;+static THREAD_BUDGET_SIGNALS: Lazy<Mutex<HashMap<String, BudgetSignal>>> =+ Lazy::new(|| Mutex::new(HashMap::new()));/// How long a recorded budget-exhausted signal stays eligible to reclassify a/// later empty turn on the same thread. Five minutes: long enough to bridge a@@ -69,7 +66,7 @@ fn prune_stale_budget_signals(signals: &mut HashMap<String, BudgetSignal>) {/// Record that this thread just hit an inference budget-exhausted error on the/// given provider binding.pub(crate) async fn record_budget_signal(thread_id: &str, provider_binding: &str) {- let mut signals = thread_budget_signals().lock_owned().await;+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;prune_stale_budget_signals(&mut signals);signals.insert(key_for(thread_id),@@ -83,7 +80,7 @@ pub(crate) async fn record_budget_signal(thread_id: &str, provider_binding: &str/// Clear any recorded budget signal for this thread — called on a successful/// turn, where the balance is evidently usable again.pub(crate) async fn clear_budget_signal(thread_id: &str) {- let mut signals = thread_budget_signals().lock_owned().await;+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;signals.remove(&key_for(thread_id));}@@ -92,7 +89,7 @@ pub(crate) async fn clear_budget_signal(thread_id: &str) {/// an expired entry evicts it and reads as not-fresh, so a re-routed turn never/// inherits the prior provider's exhaustion.pub(crate) async fn has_fresh_budget_signal(thread_id: &str, provider_binding: &str) -> bool {- let mut signals = thread_budget_signals().lock_owned().await;+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;let key = key_for(thread_id);match signals.get(&key) {Some(sig)@@ -113,7 +110,7 @@ pub(crate) async fn has_fresh_budget_signal(thread_id: &str, provider_binding: &/// into the past so expiry can be exercised without sleeping.#[cfg(test)]async fn record_budget_signal_aged(thread_id: &str, provider_binding: &str, age: Duration) {- let mut signals = thread_budget_signals().lock_owned().await;+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;let when = Instant::now().checked_sub(age).unwrap_or_else(Instant::now);signals.insert(key_for(thread_id),diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rsindex c2fc900dd7..875361cd05 100644--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs@@ -11,7 +11,7 @@ use super::super::event_bus::publish_web_channel_event;use super::super::types::ChatRequestMetadata;use super::parallel_turn::{cancel_parallel_turn_by_request_id, cancel_parallel_turns_for_thread};use super::start_chat::start_chat;-use super::state::{cancel_in_flight_gracefully, cancel_should_target, in_flight, key_for};+use super::state::{cancel_in_flight_gracefully, cancel_should_target, key_for, IN_FLIGHT};/// Cancel whatever turn is currently running on a thread (unscoped stop).///@@ -68,7 +68,7 @@ async fn cancel_chat_inner(let mut removed_request_id: Option<String> = None;{- let mut in_flight = in_flight().lock_owned().await;+ let mut in_flight = IN_FLIGHT.lock().await;// #4760: only tear down the primary turn when the cancel is unscoped OR// targets exactly the request that is running. A stale cancel for an// already-superseded request must be a no-op so the newer turn lives.@@ -185,10 +185,10 @@ async fn cancel_chat_inner(/// Is a primary or parallel turn still running on `thread_id`?async fn thread_has_live_turn(thread_id: &str, map_key: &str) -> bool {- if super::state::in_flight().lock().await.contains_key(map_key) {+ if IN_FLIGHT.lock().await.contains_key(map_key) {return true;}- super::state::parallel_in_flight()+ super::state::PARALLEL_IN_FLIGHT.lock().await.values()@@ -268,7 +268,7 @@ fn queue_item_json(pub async fn channel_web_queue_status(thread_id: &str) -> Result<Outcome<Value>, String> {let map_key = key_for(thread_id);- let in_flight = in_flight().lock_owned().await;+ let in_flight = IN_FLIGHT.lock().await;if let Some(entry) = in_flight.get(&map_key) {let status = entry.run_queue.status().await;let items: Vec<Value> = entry@@ -324,7 +324,7 @@ pub async fn channel_web_queue_remove(return Err("item_id is required".to_string());}let map_key = key_for(thread_id);- let in_flight = in_flight().lock_owned().await;+ let in_flight = IN_FLIGHT.lock().await;let Some(entry) = in_flight.get(&map_key) else {return Ok(Outcome::single_log(json!({@@ -366,7 +366,7 @@ pub async fn channel_web_queue_remove(pub async fn channel_web_queue_clear(thread_id: &str) -> Result<Outcome<Value>, String> {let map_key = key_for(thread_id);- let in_flight = in_flight().lock_owned().await;+ let in_flight = IN_FLIGHT.lock().await;if let Some(entry) = in_flight.get(&map_key) {let dropped = entry.run_queue.clear().await;log::info!(diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rsindex 3d126632d0..c6eab6c57c 100644--- 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 @@ use super::super::event_bus::publish_web_channel_event;use super::super::run_task::run_chat_task;use super::super::types::{ChatRequestMetadata, ParallelEntry};use super::super::web_errors::classify_inference_error;-use super::state::{key_for, parallel_in_flight, unscope};+use super::state::{key_for, unscope, PARALLEL_IN_FLIGHT};use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@ -22,7 +22,7 @@ use super::turn_guards::{/// 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)]@@ -197,14 +197,11 @@ pub(crate) async fn spawn_parallel_turn(}}- parallel_in_flight()- .lock_owned()- .await- .remove(&map_key_task);+ PARALLEL_IN_FLIGHT.lock().await.remove(&map_key_task);},));- parallel_in_flight().lock_owned().await.insert(+ PARALLEL_IN_FLIGHT.lock().await.insert(map_key,ParallelEntry {thread_id: key_for(thread_id),@@ -220,7 +217,7 @@ pub(crate) async fn spawn_parallel_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_owned().await;+ let mut parallel = PARALLEL_IN_FLIGHT.lock().await;let request_ids: Vec<String> = parallel.iter().filter(|(_, entry)| entry.thread_id == scoped_thread)@@ -254,7 +251,7 @@ pub(crate) async fn cancel_parallel_turn_by_request_id() -> Vec<String> {let map_key = key_for(request_id);let scoped_thread = key_for(thread_id);- let mut parallel = parallel_in_flight().lock_owned().await;+ let mut parallel = PARALLEL_IN_FLIGHT.lock().await;let matches = parallel.get(&map_key).map(|entry| entry.thread_id == scoped_thread)diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rsindex bf221dd111..f5ce3088a8 100644--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs@@ -20,7 +20,7 @@ use super::super::run_task::run_chat_task;use super::super::types::{ChatRequestMetadata, InFlightEntry, QueueMode};use super::super::web_errors::classify_inference_error;use super::parallel_turn::spawn_parallel_turn;-use super::state::{cancel_in_flight_gracefully, in_flight, key_for};+use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@ -371,7 +371,7 @@ async fn start_chat_inner(// Non-interrupt modes: push into the running turn's queue and return.if !matches!(parsed_mode, QueueMode::Interrupt) {- let in_flight = in_flight().lock_owned().await;+ let in_flight = IN_FLIGHT.lock().await;if let Some(existing) = in_flight.get(&map_key) {let item_id = uuid::Uuid::new_v4().to_string();let text_preview = crate::agent::queued_turn::text_preview(&message);@@ -425,7 +425,7 @@ async fn start_chat_inner(}{- let mut in_flight = in_flight().lock_owned().await;+ let mut in_flight = IN_FLIGHT.lock().await;if let Some(existing) = in_flight.remove(&map_key) {let cancelled_id = cancel_in_flight_gracefully(existing);@@ -526,7 +526,7 @@ async fn start_chat_inner(// Release any in-flight slot we still own and stop. The// `request_id` guard below prevents clobbering a newer turn that// replaced us on the interrupt path.- let mut in_flight = in_flight().lock_owned().await;+ let mut in_flight = IN_FLIGHT.lock().await;if let Some(current) = in_flight.get(&map_key_task) {if current.request_id == request_id_task {in_flight.remove(&map_key_task);@@ -622,7 +622,7 @@ async fn start_chat_inner(// Drain followup messages queued during this turn.let followups = {- let mut in_flight = in_flight().lock_owned().await;+ let mut in_flight = IN_FLIGHT.lock().await;let followups = if let Some(current) = in_flight.get(&map_key_task) {if current.request_id == request_id_task {let fups = current.run_queue.drain(QueueLane::Followup).await;@@ -683,7 +683,7 @@ async fn start_chat_inner());{- let mut in_flight = in_flight().lock_owned().await;+ let mut in_flight = IN_FLIGHT.lock().await;in_flight.insert(map_key,InFlightEntry {diff --git a/crates/openhuman-core/src/web_chat/ops/state.rs b/crates/openhuman-core/src/web_chat/ops/state.rsindex 5013f782e8..445e96e1b0 100644--- a/crates/openhuman-core/src/web_chat/ops/state.rs+++ b/crates/openhuman-core/src/web_chat/ops/state.rs@@ -3,35 +3,26 @@//! and mutate them.use std::collections::HashMap;-use std::sync::Arc;use std::time::Duration;+use once_cell::sync::Lazy;use serde_json::json;use tokio::sync::Mutex;use super::super::types::{InFlightEntry, ParallelEntry, SessionEntry};-type ThreadSessions = Mutex<HashMap<String, SessionEntry>>;-type InFlight = Mutex<HashMap<String, InFlightEntry>>;-type ParallelInFlight = Mutex<HashMap<String, ParallelEntry>>;+pub(crate) static THREAD_SESSIONS: Lazy<Mutex<HashMap<String, SessionEntry>>> =+ 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>()-}+pub(crate) static IN_FLIGHT: Lazy<Mutex<HashMap<String, InFlightEntry>>> =+ Lazy::new(|| Mutex::new(HashMap::new()));/// 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.-pub(crate) fn parallel_in_flight() -> Arc<ParallelInFlight> {- crate::core::runtime::current_slot::<ParallelInFlight>()-}+/// `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()));/// The map key for `thread_id` in the calling scope.///@@ -123,11 +114,12 @@ pub(crate) fn cancel_in_flight_gracefully(entry: InFlightEntry) -> String {}pub async fn invalidate_thread_sessions(thread_id: &str) {- // Under an embedded agent only that agent's entry goes. Outside an agent- // scope every entry for the thread in the current table goes.+ // 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.let active_agent = crate::core::runtime::CoreContext::current().and_then(|context| context.session_agent().map(str::to_owned));- let mut sessions = thread_sessions().lock_owned().await;+ let mut sessions = THREAD_SESSIONS.lock().await;let keys_to_remove: Vec<String> = match active_agent {Some(_) => {let key = key_for(thread_id);@@ -156,7 +148,7 @@ pub async fn invalidate_thread_sessions(thread_id: &str) {}pub async fn in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = in_flight().lock_owned().await;+ let guard = IN_FLIGHT.lock().await;guard.iter().map(|(k, v)| (k.clone(), v.request_id.clone()))@@ -172,7 +164,7 @@ pub async fn drain_queued_turns_for_test(thread_id: &str,lane: tinyagents_harness::run_queue::QueueLane,) -> Vec<crate::agent::queued_turn::QueuedTurn> {- let guard = in_flight().lock_owned().await;+ let guard = IN_FLIGHT.lock().await;match guard.get(&key_for(thread_id)) {Some(entry) => entry.run_queue.drain(lane).await,None => Vec::new(),@@ -182,7 +174,7 @@ pub async fn drain_queued_turns_for_test(/// Test accessor: `(request_id, thread_id)` for every in-flight parallel turn.#[cfg(any(test, debug_assertions))]pub async fn parallel_in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = parallel_in_flight().lock_owned().await;+ let guard = PARALLEL_IN_FLIGHT.lock().await;guard.iter().map(|(request_id, entry)| (request_id.clone(), entry.thread_id.clone()))@@ -208,7 +200,3 @@ pub fn cancel_should_target(requested: Option<&str>, in_flight: &str) -> bool {None => true,}}--#[cfg(test)]-#[path = "state_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web_chat/ops_budget_correlation_tests_tests.rs b/crates/openhuman-core/src/web_chat/ops_budget_correlation_tests_tests.rsindex 858b4aec69..bed138fb86 100644--- a/crates/openhuman-core/src/web_chat/ops_budget_correlation_tests_tests.rs+++ b/crates/openhuman-core/src/web_chat/ops_budget_correlation_tests_tests.rs@@ -101,7 +101,7 @@ async fn record_prunes_other_threads_stale_entries() {// ...which a later budget event on a DIFFERENT thread sweeps away.record_budget_signal(active, BINDING).await;{- let signals = thread_budget_signals().lock_owned().await;+ let signals = THREAD_BUDGET_SIGNALS.lock().await;assert!(!signals.contains_key(abandoned),"stale entry should be pruned"@@ -110,40 +110,3 @@ async fn record_prunes_other_threads_stale_entries() {}clear_budget_signal(active).await;}--#[tokio::test]-async fn budget_signals_stay_with_the_agent_that_recorded_them() {- use crate::core::runtime::{context::CoreContext, ContextOverlay, DomainSet};- let root = CoreContext::for_test(DomainSet::full(), None);- let agent = |id: &str| {- root.derive_with(- ContextOverlay::new(- crate::config::Config::default(),- DomainSet::kernel(),- crate::tools::toolpacks::ToolGroups::none(),- )- .session_agent(id),- )- };- let alpha = agent("alpha");- let beta = agent("beta");- let thread = "budget-shared-thread";-- CoreContext::scope(std::sync::Arc::clone(&alpha), async {- record_budget_signal(thread, "managed").await;- })- .await;-- assert!(- CoreContext::scope(alpha, async {- has_fresh_budget_signal(thread, "managed").await- })- .await- );- assert!(- !CoreContext::scope(beta, async {- has_fresh_budget_signal(thread, "managed").await- })- .await- );-}diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rsindex 7c594907e2..16ca30789d 100644--- a/crates/openhuman-core/src/web_chat/session.rs+++ b/crates/openhuman-core/src/web_chat/session.rs@@ -399,7 +399,7 @@ pub(crate) async fn checkout_session_agent(let prior = if policy == CheckoutPolicy::Fork {None} else {- let mut sessions = super::ops::thread_sessions().lock_owned().await;+ let mut sessions = super::ops::THREAD_SESSIONS.lock().await;sessions.remove(&map_key)};@@ -514,7 +514,7 @@ pub(crate) async fn checkin_session_agent(agent: OpenHumanSessionHost,fingerprint: SessionCacheFingerprint,) {- let mut sessions = super::ops::thread_sessions().lock_owned().await;+ let mut sessions = super::ops::THREAD_SESSIONS.lock().await;sessions.insert(super::ops::key_for(thread_id),SessionEntry { agent, fingerprint },@@ -531,7 +531,7 @@ pub(crate) async fn checkin_session_agent_if_vacant(agent: OpenHumanSessionHost,fingerprint: SessionCacheFingerprint,) -> bool {- let mut sessions = super::ops::thread_sessions().lock_owned().await;+ let mut sessions = super::ops::THREAD_SESSIONS.lock().await;match sessions.entry(super::ops::key_for(thread_id)) {std::collections::hash_map::Entry::Occupied(_) => {log::info!(@@ -552,10 +552,6 @@ pub(crate) async fn checkin_session_agent_if_vacant(#[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 --git a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs b/crates/openhuman-core/src/web_chat/session_checkout_tests.rsindex b897a0081f..0e9bb9adc0 100644--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs@@ -16,12 +16,12 @@ use super::{};use crate::agent::OpenHumanSessionHost;use crate::config::Config;-use crate::web_chat::ops::{key_for, thread_sessions};+use crate::web_chat::ops::{key_for, THREAD_SESSIONS};use crate::web_chat::types::SessionCacheFingerprint;use tinyagents_session::transcript::TranscriptMessage;use tinytools_agent::dialect::TranscriptEntry;-pub(super) fn test_config(tmp: &tempfile::TempDir) -> Config {+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 @@ pub(super) fn test_config(tmp: &tempfile::TempDir) -> Config {config}-pub(super) fn unique_thread(tag: &str) -> String {+fn unique_thread(tag: &str) -> String {format!("thread-checkout-{tag}-{}", uuid::Uuid::new_v4())}@@ -86,7 +86,7 @@ fn prose(history: &[TranscriptEntry]) -> Vec<String> {.collect()}-pub(super) fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {+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![@@ -100,10 +100,7 @@ pub(super) fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessio}async fn evict(thread_id: &str) {- thread_sessions()- .lock_owned()- .await- .remove(&key_for(thread_id));+ THREAD_SESSIONS.lock().await.remove(&key_for(thread_id));}#[tokio::test]@@ -152,7 +149,7 @@ async fn checkout_cold_boots_from_the_thread_transcript_and_checkin_keeps_it_war);checkin_session_agent(&thread_id, agent, fingerprint).await;- assert!(thread_sessions()+ assert!(THREAD_SESSIONS.lock().await.contains_key(&key_for(&thread_id)));@@ -176,7 +173,7 @@ async fn checkout_cold_boots_from_the_thread_transcript_and_checkin_keeps_it_war"warm checkout must carry the same history");// Checked out means removed: nobody else can drive this agent meanwhile.- assert!(!thread_sessions()+ assert!(!THREAD_SESSIONS.lock().await.contains_key(&key_for(&thread_id)));@@ -262,7 +259,7 @@ async fn a_fork_never_takes_or_returns_the_cached_agent() {// Built fresh: no transcript on disk for this thread, so an empty history.assert!(prose(&agent.history()).is_empty());// The primary's cached agent was left in place.- assert!(thread_sessions()+ assert!(THREAD_SESSIONS.lock().await.contains_key(&key_for(&thread_id)));@@ -551,6 +548,67 @@ fn chat_agent_id_selects_the_web_chat_agent_and_defaults_to_the_orchestrator() {);}+/// 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.@@ -637,7 +695,7 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {// Reused cached agent, the user switched the UI to English: the Spanish// directives already in the history are superseded explicitly.assert!(- thread_sessions()+ THREAD_SESSIONS.lock().await.contains_key(&key_for(&thread_id)),@@ -651,7 +709,7 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {checkin_session_agent(&thread_id, agent, fingerprint).await;// Reused again, now Hindi: re-armed with the new language.- assert!(thread_sessions()+ assert!(THREAD_SESSIONS.lock().await.contains_key(&key_for(&thread_id)));diff --git a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rsindex fe2d4f256a..6c8a95250e 100644--- a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs@@ -430,7 +430,7 @@ async fn chat_done_is_published_only_after_the_in_flight_slot_is_released() {event.event == "chat_done" && event.request_id == request_id};- let held = crate::web_chat::ops::in_flight().lock_owned().await;+ let held = crate::web_chat::ops::IN_FLIGHT.lock().await;block.release.notify_one();let early = timeout(Duration::from_millis(500), async {loop {diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.mdindex 5ac88622a0..e5566d8c6b 100644--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@ -250,9 +250,8 @@ The on-disk layout under a runtime-owned root:config.toml, auth-profiles.json, core.token runtime-wideworkspace/session_db/sessions.db runtime-wide run ledger- 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+ session_raw/ transcripts (thread + agent)+ agents/<id>/skills/ each agent's skills rootagents/<id>/action/ default action_dir per agent```@@ -260,74 +259,33 @@ The default `action_dir` sits beside the workspace, never inside it, becausethe core refuses agent writes beneath the workspace. An inherited workspaceuses `<action_dir>/agents/<id>` instead.-### 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.-- 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.+### 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.## Authentication and the backenddiff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 9f8cd616c4..71f1370c1c 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -7,9 +7,6 @@use std::path::Path;-use openhuman_core::agent::harness::definition::{- AgentDefinition, AgentDefinitionRegistry, SubagentEntry,-};use openhuman_core::core::all::DomainGroup;use openhuman_core::core::runtime::{ContextOverlay, DomainSet};use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};@@ -25,10 +22,6 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnid: 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.@@ -167,6 +160,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn}// ── definition ───────────────────────────────────────────────────────+ #[cfg_attr(not(feature = "mcp"), allow(unused_mut))]let mut definition = parts.definition.into_core(&id)?;// Every declared server's tools are registered as their own// `mcp_<server>_<tool>`, deferred by default. A wildcard belt reaches them@@ -177,8 +171,6 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnopt_named_belt_into_discovery(&mut definition.tools);}- let definitions = own_catalogue(&catalogue, &id, &mut definition, parts.subagents)?;-// ── narrowing ────────────────────────────────────────────────────────let domains = match parts.domains {Some(requested) => {@@ -196,43 +188,23 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn};// ── context ──────────────────────────────────────────────────────────- let mut context_config = config.clone();- context_config.ephemeral_route = provider.route().and_then(|route| {- openhuman_core::config::schema::EphemeralRoute::from_params(- Some(route.base_url.clone()),- Some(route.api_key.clone()),- )- });let overlay = ContextOverlay {- config: context_config,+ config: config.clone(),domains,tool_groups,user_skill_roots: parts.include_user_skills,// A host session store keeps each agent's conversations apart by id.session_agent: Some(id.to_string()),- agent_policy: Some(std::sync::Arc::new(- openhuman_core::security::SecurityPolicy::from_config(- &config.autonomy,- &config.workspace_dir,- &config.action_dir,- )- .with_privacy_mode(config.privacy.mode),- )),- approvals_disabled: !access.approval_gate_enabled(),- definitions,};let ctx = runtime.core_runtime().context().derive_with(overlay);- openhuman_core::core::runtime::AgentContextRegistry::register(&id, &ctx);log::debug!("[embed][agent] instantiated id={id} action_dir={} routed={} access_origin={} \- user_skills={} tier={:?} approval_gate={}",+ user_skills={}",config.action_dir.display(),provider.is_routed(),access.turn_origin().is_some(),- parts.include_user_skills,- config.autonomy.level,- access.approval_gate_enabled()+ parts.include_user_skills);Ok(AgentInner {@@ -248,56 +220,10 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnaccess,layout,host_tools: parts.host_tools,- lifecycle: super::lifecycle::Lifecycle::new(),host_only,})}-/// The process catalogue: the booted registry, or the built-ins when none-/// was initialised.-fn process_catalogue() -> std::sync::Arc<AgentDefinitionRegistry> {- AgentDefinitionRegistry::global_arc()- .unwrap_or_else(|| std::sync::Arc::new(AgentDefinitionRegistry::builtins_only()))-}--/// The catalogue an agent with its own sub-agents delegates through: the-/// process catalogue plus the agent and its sub-agents. `None` (resolve-/// through the process catalogue) for an agent without sub-agents.-fn own_catalogue(- catalogue: &AgentDefinitionRegistry,- id: &str,- definition: &mut AgentDefinition,- subagents: Vec<(String, super::AgentDefinitionSpec)>,-) -> Result<Option<std::sync::Arc<AgentDefinitionRegistry>>, AgentError> {- if subagents.is_empty() {- return Ok(None);- }- let mut own = Vec::with_capacity(subagents.len() + 1);- let mut seen = std::collections::HashSet::new();- for (sub_id, spec) in subagents {- validate_agent_id(&sub_id).map_err(|reason| AgentError::InvalidId {- id: sub_id.clone(),- reason,- })?;- if catalogue.get(&sub_id).is_some() {- return Err(AgentError::ReservedId(sub_id));- }- if sub_id == id || !seen.insert(sub_id.clone()) {- return Err(AgentError::DuplicateId(sub_id));- }- definition- .subagents- .push(SubagentEntry::AgentId(sub_id.clone()));- own.push(spec.into_subagent_core(&sub_id)?);- }- own.push(definition.clone());- log::debug!(- "[embed][agent] id={id} owns a catalogue with {} sub-agent(s)",- own.len() - 1- );- Ok(Some(std::sync::Arc::new(catalogue.with_definitions(own))))-}-/// Adds `tool_search` to a named belt that lacks it. A wildcard belt already/// has discovery.#[cfg(feature = "mcp")]diff --git a/crates/openhuman-embed/src/agent/build_tests.rs b/crates/openhuman-embed/src/agent/build_tests.rsindex b8c000feef..af41498775 100644--- a/crates/openhuman-embed/src/agent/build_tests.rs+++ b/crates/openhuman-embed/src/agent/build_tests.rs@@ -23,92 +23,3 @@ fn agent_ids_must_be_plain_names() {assert!(validate_agent_id("ok-agent_1").is_ok());assert!(validate_agent_id("../escape").is_err());}--#[test]-fn an_agent_without_sub_agents_resolves_through_the_process_catalogue() {- let catalogue = process_catalogue();- let mut definition = super::super::AgentDefinitionSpec::new()- .into_core("solo")- .unwrap();- assert!(- own_catalogue(&catalogue, "solo", &mut definition, Vec::new())- .unwrap()- .is_none()- );-}--#[test]-fn sub_agents_become_workers_in_a_catalogue_of_the_agents_own() {- use openhuman_core::agent::harness::definition::AgentTier;-- let catalogue = process_catalogue();- let mut definition = super::super::AgentDefinitionSpec::new()- .into_core("lead")- .unwrap();- let own = own_catalogue(- &catalogue,- "lead",- &mut definition,- vec![(- "lead-helper".to_string(),- super::super::AgentDefinitionSpec::new().when_to_use("helps the lead"),- )],- )- .unwrap()- .expect("an own catalogue");-- let helper = own.get("lead-helper").expect("the helper is listed");- assert_eq!(helper.agent_tier, AgentTier::Worker);- assert!(helper.subagents.is_empty());- assert!(!helper.searches_connected_mcp);- assert_eq!(helper.when_to_use, "helps the lead");- assert!(own.get("lead").is_some(), "the agent itself is listed");- assert!(- own.get("orchestrator").is_some(),- "built-ins stay reachable"- );- assert!(definition- .subagents- .iter()- .any(|entry| matches!(entry, SubagentEntry::AgentId(id) if id == "lead-helper")));- assert!(catalogue.get("lead-helper").is_none());-}--#[test]-fn sub_agent_ids_are_checked_like_agent_ids() {- let catalogue = process_catalogue();- let spec = super::super::AgentDefinitionSpec::new;- let mut definition = spec().into_core("lead").unwrap();-- let reserved = own_catalogue(- &catalogue,- "lead",- &mut definition,- vec![("planner".to_string(), spec())],- );- assert!(matches!(reserved, Err(AgentError::ReservedId(id)) if id == "planner"));-- let invalid = own_catalogue(- &catalogue,- "lead",- &mut definition,- vec![("Not Valid".to_string(), spec())],- );- assert!(matches!(invalid, Err(AgentError::InvalidId { .. })));-- let duplicate = own_catalogue(- &catalogue,- "lead",- &mut definition,- vec![("twin".to_string(), spec()), ("twin".to_string(), spec())],- );- assert!(matches!(duplicate, Err(AgentError::DuplicateId(id)) if id == "twin"));-- let itself = own_catalogue(- &catalogue,- "lead",- &mut definition,- vec![("lead".to_string(), spec())],- );- assert!(matches!(itself, Err(AgentError::DuplicateId(_))));-}diff --git a/crates/openhuman-embed/src/agent/definition.rs b/crates/openhuman-embed/src/agent/definition.rsindex dd820d6f83..fb3f7442a6 100644--- a/crates/openhuman-embed/src/agent/definition.rs+++ b/crates/openhuman-embed/src/agent/definition.rs@@ -230,19 +230,6 @@ impl AgentDefinitionSpec {}}-impl AgentDefinitionSpec {- /// Materialize this spec as a worker sub-agent named `id`: it executes- /// and delegates nothing further.- pub(crate) fn into_subagent_core(self, id: &str) -> Result<AgentDefinition, AgentError> {- let mut def = self.into_core(id)?;- def.agent_tier = openhuman_core::agent::harness::definition::AgentTier::Worker;- def.subagents.clear();- def.delegate_name = None;- def.searches_connected_mcp = false;- Ok(def)- }-}-/// The built-in definition every embedded agent starts from.const ORCHESTRATOR_ID: &str = "orchestrator";diff --git a/crates/openhuman-embed/src/agent/layout.rs b/crates/openhuman-embed/src/agent/layout.rsindex 2f03d49949..cae19b97ac 100644--- a/crates/openhuman-embed/src/agent/layout.rs+++ b/crates/openhuman-embed/src/agent/layout.rs@@ -8,17 +8,10 @@//! config.toml, auth-profiles.json, core.token runtime-wide//! workspace///! session_db/sessions.db runtime-wide run ledger-//! agents/<id>/{SOUL.md, skills/, workflows/} the agent's home-//! agents/<id>/session_raw/<stem>.jsonl its transcripts-//! agents/<id>/cron/jobs.db its cron jobs+//! agents/<id>/{SOUL.md, skills/} the agent's home+//! session_raw/<ts>_<id>.jsonl its transcripts//! agents/<id>/action/ its default action_dir//! ```-//!-//! Its MCP host keeps its store in the agent home too.-//!-//! Transcripts an agent wrote to the shared `workspace/session_raw/` before-//! this layout are still read, and are copied into the agent's directory-//! before they are written to again.use std::path::{Path, PathBuf};@@ -43,11 +36,7 @@ impl AgentLayout {Self {home: workspace_dir.join("agents").join(id),skills: workspace_dir.join("agents").join(id).join("skills"),- transcripts: openhuman_core::agent::session_store::agent_transcript_root(- workspace_dir,- id,- )- .join("session_raw"),+ transcripts: workspace_dir.join("session_raw"),action_dir,}}diff --git a/crates/openhuman-embed/src/agent/layout_tests.rs b/crates/openhuman-embed/src/agent/layout_tests.rsindex 2534ecb790..bdd50d425e 100644--- a/crates/openhuman-embed/src/agent/layout_tests.rs+++ b/crates/openhuman-embed/src/agent/layout_tests.rs@@ -6,10 +6,7 @@ fn layout_uses_agent_id_paths() {let layout = AgentLayout::resolve(ws, "alpha", PathBuf::from("/r/a"));assert_eq!(layout.home, Path::new("/r/workspace/agents/alpha"));assert_eq!(layout.skills, Path::new("/r/workspace/agents/alpha/skills"));- assert_eq!(- layout.transcripts,- Path::new("/r/workspace/agents/alpha/session_raw")- );+ assert_eq!(layout.transcripts, Path::new("/r/workspace/session_raw"));assert_eq!(layout.action_dir, Path::new("/r/a"));}diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 94ac25e200..dd79db6077 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -14,10 +14,7 @@//! loader, DomainSet gate, tool-group filter and skill discovery all read//! the ambient context.-mod approvals;mod attachments;-pub(crate) mod lifecycle;-pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval};pub use attachments::ToolAttachmentError;pub(crate) mod build;mod definition;@@ -77,23 +74,6 @@ pub enum AgentError {/// A spec input could not be honoured.#[error("{0}")]Invalid(String),-- /// The id names a built-in agent definition (`orchestrator`, `planner`,- /// …), which the delegation catalogue would resolve instead of this agent.- #[error("agent id {0:?} is reserved for a built-in agent definition")]- ReservedId(String),-- /// The runtime already hosts its configured maximum of live agents- /// ([`RuntimeBuilder::max_agents`](crate::RuntimeBuilder::max_agents)).- #[error("the runtime already hosts its limit of {limit} agents")]- AgentLimit {- /// The configured maximum.- limit: usize,- },-- /// No live agent with this id is registered on the runtime.- #[error("no agent {0:?} is registered on this runtime")]- UnknownId(String),}/// The assembled state behind an [`Agent`], shared by every clone of it and@@ -117,58 +97,11 @@ 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 for@@ -219,12 +152,6 @@ impl Agent {turn}- /// This agent's pending approvals: the requests its turns parked, and- /// only those.- pub fn approvals(&self) -> Approvals {- Approvals::new(&self.inner.id)- }-/// The agent's read/write root for acting tools.pub fn action_dir(&self) -> &Path {&self.inner.config.action_dir@@ -246,9 +173,9 @@ impl Agent {&self.inner.layout.skills}- /// `<workspace>/agents/<id>/session_raw/` — where this agent's transcripts- /// are written. Conversations it wrote earlier into the workspace's shared- /// `session_raw/` stay readable and are copied here when resumed.+ /// Where this agent's transcripts are written: the workspace's shared+ /// `session_raw/` (files are keyed by agent name), or+ /// `session_raw/`, keyed by agent id.pub fn transcripts_dir(&self) -> &Path {&self.inner.layout.transcripts}diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rsindex edc1d3c512..7c2db70fa3 100644--- a/crates/openhuman-embed/src/agent/spec.rs+++ b/crates/openhuman-embed/src/agent/spec.rs@@ -52,7 +52,6 @@ pub struct AgentSpec {config_fn: Option<ConfigEdit>,host_tools: Option<openhuman_core::agent::HostTools>,memory: Option<MemoryBinding>,- subagents: Vec<(String, AgentDefinitionSpec)>,}/// Whose memory an agent reads and writes: the memory agent id its turns are@@ -102,9 +101,9 @@ impl AgentSpec {////// The id must match `^[a-z0-9][a-z0-9_-]{0,63}$` (checked at/// [`Runtime::agent`](crate::Runtime::agent)); it names the agent's- /// directories and transcripts. The built-in ids (`orchestrator`,- /// `summarizer`, …) are reserved for the shipped definitions and refused- /// with [`AgentError::ReservedId`](crate::AgentError::ReservedId).+ /// directories and transcripts. Avoid the built-in ids (`orchestrator`,+ /// `summarizer`, …): the runtime-wide delegation catalog resolves those+ /// to the shipped definitions.pub fn new(id: impl Into<String>) -> Self {Self {id: id.into(),@@ -126,7 +125,6 @@ impl AgentSpec {config_fn: None,host_tools: None,memory: None,- subagents: Vec::new(),}}@@ -256,21 +254,6 @@ impl AgentSpec {self}- /// Sub-agents only this agent can delegate to, each under its own id.- ///- /// Each becomes a `delegate_<id>` tool on this agent and a worker in this- /// agent's own catalogue; other agents on the runtime never see it. Ids- /// follow the agent-id rules and must not name a built-in definition.- pub fn subagents<I, S>(mut self, subagents: I) -> Self- where- I: IntoIterator<Item = (S, AgentDefinitionSpec)>,- S: Into<String>,- {- self.subagents- .extend(subagents.into_iter().map(|(id, spec)| (id.into(), spec)));- self- }-/// Arbitrary edits to the agent's config, applied last.////// The escape hatch for the config fields the spec does not model — not@@ -376,7 +359,6 @@ impl AgentSpec {config_fn: self.config_fn,host_tools: self.host_tools,memory: self.memory,- subagents: self.subagents,}}}@@ -402,7 +384,6 @@ pub(crate) struct AgentSpecParts {pub(crate) config_fn: Option<ConfigEdit>,pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,pub(crate) memory: Option<MemoryBinding>,- pub(crate) subagents: Vec<(String, AgentDefinitionSpec)>,}impl std::fmt::Debug for AgentSpec {diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex ad42eb1e55..7aa15f9fc7 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -106,16 +106,6 @@ pub enum CoreError {/// RPC method the invalid route was attached to.method: &'static str,},-- /// The agent was removed from its runtime: a turn sent afterwards is- /// refused, and one in flight when it was removed ends with this.- #[error("{method}: agent {agent_id:?} was removed")]- AgentRemoved {- /// RPC method the turn was dispatching.- method: &'static str,- /// The removed agent.- agent_id: String,- },}impl CoreError {@@ -166,8 +156,7 @@ impl CoreError {| CoreError::Encode { method, .. }| CoreError::Decode { method, .. }| CoreError::InsecureRoute { method, .. }- | CoreError::InvalidRoute { method }- | CoreError::AgentRemoved { method, .. } => method,+ | CoreError::InvalidRoute { method } => method,}}diff --git a/crates/openhuman-embed/src/harness/access.rs b/crates/openhuman-embed/src/harness/access.rsindex dd97707de4..5141b68b11 100644--- a/crates/openhuman-embed/src/harness/access.rs+++ b/crates/openhuman-embed/src/harness/access.rs@@ -33,8 +33,6 @@ pub struct Access {trusted_roots: Vec<TrustedRoot>,allow_tool_install: bool,approval_gate: bool,- auto_approve: Option<Vec<String>>,- auto_approve_all: Option<bool>,}impl Default for Access {@@ -57,8 +55,6 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: true,- auto_approve: None,- auto_approve_all: None,}}@@ -74,8 +70,6 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: true,- auto_approve: None,- auto_approve_all: None,}}@@ -100,8 +94,6 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: false,- auto_approve: None,- auto_approve_all: None,}}@@ -128,36 +120,6 @@ impl Access {self}- /// Tools this agent runs without asking, replacing the runtime's- /// "Always allow" list for this agent only.- pub fn auto_approve<I, S>(mut self, tools: I) -> Self- where- I: IntoIterator<Item = S>,- S: Into<String>,- {- self.auto_approve = Some(tools.into_iter().map(Into::into).collect());- self- }-- /// Approve every gated call for this agent without asking, or (`false`)- /// withdraw a blanket approval the runtime config carries.- ///- /// An unlabelled turn origin is still denied.- pub fn auto_approve_all(mut self, enabled: bool) -> Self {- self.auto_approve_all = Some(enabled);- self- }-- /// Turn the interactive approval gate on or off for this agent.- ///- /// Off, gated calls run without parking at this agent's tier, while- /// other agents on the runtime keep parking. Forced approvals and an- /// unlabelled origin are still refused.- pub fn approval_gate(mut self, enabled: bool) -> Self {- self.approval_gate = enabled;- self- }-/// Override the turn origin.////// The presets pick one for you. Reach for this when the harness is driving@@ -202,12 +164,6 @@ impl Access {}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 --git a/crates/openhuman-embed/src/harness/access_tests.rs b/crates/openhuman-embed/src/harness/access_tests.rsindex f6071a5e7c..a8ed8cdeb4 100644--- a/crates/openhuman-embed/src/harness/access_tests.rs+++ b/crates/openhuman-embed/src/harness/access_tests.rs@@ -141,36 +141,6 @@ fn an_explicit_origin_overrides_the_preset() {));}-#[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.diff --git a/crates/openhuman-embed/src/harness/error.rs b/crates/openhuman-embed/src/harness/error.rsindex 09df94e90d..0eefb76112 100644--- a/crates/openhuman-embed/src/harness/error.rs+++ b/crates/openhuman-embed/src/harness/error.rs@@ -88,12 +88,9 @@ impl From<crate::AgentError> for HarnessError {match err {A::Call(e) => Self::Call(e),A::Workspace { what, source } => Self::Workspace { what, source },- A::DuplicateId(_)- | A::InvalidId { .. }- | A::WidensRuntime(_)- | A::ReservedId(_)- | A::AgentLimit { .. }- | A::UnknownId(_) => Self::Invalid(err_text(&err)),+ A::DuplicateId(_) | A::InvalidId { .. } | A::WidensRuntime(_) => {+ Self::Invalid(err_text(&err))+ }A::Invalid(msg) => Self::Invalid(msg),}}diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 87de273d79..f0f4b68e2e 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -132,8 +132,8 @@ pub use openhuman_core::voice::VOICE_COMPILED_IN;pub use agent::ToolAttachmentError;pub use agent::{- Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals,- ApprovalsError, MemoryBinding, PendingApproval, SandboxModeSpec, ToolScopeSpec,+ Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, MemoryBinding, SandboxModeSpec,+ ToolScopeSpec,};pub use auth::{Auth, AuthState, Session};pub use config::{Config, RuntimeFlags};@@ -144,13 +144,10 @@ pub use harness::{};#[cfg(feature = "mcp")]pub use harness::{HttpHeader, McpAuthConfig, McpServer};-pub use runtime::builder::DEFAULT_MAX_AGENTS;/// 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, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError,-};+pub use runtime::{run_from_args, ApiKey, ConfigSource, Runtime, RuntimeBuilder, RuntimeError};/// The types the [`RuntimeBuilder`] seam options take: controller/// extensions, embedder hooks, the CLI server launcher and the live securitydiff --git a/crates/openhuman-embed/src/runtime/README.md b/crates/openhuman-embed/src/runtime/README.mdindex edf3205eb8..2fc29e9885 100644--- a/crates/openhuman-embed/src/runtime/README.md+++ b/crates/openhuman-embed/src/runtime/README.md@@ -98,11 +98,12 @@ keyring and credential store, the RPC bearer, the background `ServiceSet`,the registered `DomainSet`, and the API key. An agent owns everything thecore 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, 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`.+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.## Boundariesdiff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rsindex 6d041e2717..b15bd509e3 100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@ -257,7 +257,6 @@ impl RuntimeBuilder {tool_groups,self.provider,self.access,- self.max_agents,))}diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rsindex cf204415ce..e8d2c34d86 100644--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@ -86,13 +86,8 @@ pub struct RuntimeBuilder {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()@@ -127,7 +122,6 @@ impl RuntimeBuilder {memory_engine: None,session_store: None,seams: HostSeams::default(),- max_agents: DEFAULT_MAX_AGENTS,}}@@ -174,15 +168,6 @@ impl RuntimeBuilder {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.///diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 8ba949bf94..c3b8ed7dcc 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -44,10 +44,11 @@//! `action_dir`), its [`AgentDefinition`](openhuman_core::agent::harness::definition::AgentDefinition)//! (system prompt, tool scope, sandbox mode), its profile (allowlists,//! dedicated memory and transcripts), its skills root, its narrowed-//! `DomainSet` and [`ToolGroups`], its approval settings, sub-agents, MCP-//! host, cron jobs and per-turn state.+//! `DomainSet` and [`ToolGroups`].//!-//! The crate README's "Still process-owned" list names what agents share.+//! Some settings are still read from the runtime's boot config by every+//! agent; see the crate README's "still runtime-wide" list. They are+//! documented rather than hidden.//!//! # One runtime per process//!@@ -69,7 +70,6 @@mod api_key;mod build;pub(crate) mod builder;-mod lifecycle;mod presets;mod run;mod seams;@@ -77,7 +77,6 @@ mod summary;pub use api_key::ApiKey;pub use builder::{ConfigSource, RuntimeBuilder};-pub use lifecycle::RemoveAgent;pub use run::run_from_args;#[doc(hidden)]pub use summary::BuilderSummary;@@ -235,7 +234,6 @@ pub struct Runtime {provider: Provider,access: Access,agents: Mutex<HashMap<String, Weak<AgentInner>>>,- max_agents: usize,}impl Runtime {@@ -276,15 +274,6 @@ impl Runtime {if agents.contains_key(&id) {return Err(AgentError::DuplicateId(id));}- if agents.len() >= self.max_agents {- log::warn!(- "[embed][runtime] agent refused id={id}: {} live agents is the limit",- self.max_agents- );- return Err(AgentError::AgentLimit {- limit: self.max_agents,- });- }let inner = Arc::new(crate::agent::build::instantiate(self, spec)?);agents.insert(id.clone(), Arc::downgrade(&inner));drop(agents);@@ -434,7 +423,6 @@ impl Runtime {tool_groups: ToolGroups,provider: Provider,access: Access,- max_agents: usize,) -> Self {Self {id: uuid::Uuid::new_v4().to_string(),@@ -453,7 +441,6 @@ impl Runtime {provider,access,agents: Mutex::new(HashMap::new()),- max_agents,}}}diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 0f453a9b69..c4137c248c 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -572,7 +572,6 @@ impl Turn {crate::error::CoreError::Decode { .. } => "decode",crate::error::CoreError::InsecureRoute { .. } => "insecure_route",crate::error::CoreError::InvalidRoute { .. } => "invalid_route",- crate::error::CoreError::AgentRemoved { .. } => "agent_removed",};log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");});@@ -771,10 +770,7 @@ async fn dispatch(.map(|outcome| (outcome.value, Some(report))).map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))});- agent- .lifecycle- .admit(&agent.id, AGENT_CHAT, runtime.run_in(ctx, turn))- .await+ runtime.run_in(ctx, turn).await}}}diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rsindex 4e7ceede55..c127ce2d86 100644--- a/crates/openhuman-embed/tests/common/mod.rs+++ b/crates/openhuman-embed/tests/common/mod.rs@@ -177,45 +177,3 @@ pub fn tool_names(request: &wiremock::Request) -> Vec<String> {}).unwrap_or_default()}--/// A provider that answers its first chat requests with `steps`, in order,-/// then every later one with `fallback`.-pub async fn scripted_provider(- steps: Vec<serde_json::Value>,- fallback: &str,-) -> wiremock::MockServer {- let server = wiremock::MockServer::start().await;- for (index, step) in steps.into_iter().enumerate() {- wiremock::Mock::given(wiremock::matchers::method("POST"))- .and(wiremock::matchers::path("/v1/chat/completions"))- .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(step))- .up_to_n_times(1)- .with_priority(u8::try_from(index + 1).unwrap_or(u8::MAX))- .mount(&server)- .await;- }- wiremock::Mock::given(wiremock::matchers::method("POST"))- .and(wiremock::matchers::path("/v1/chat/completions"))- .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(chat_completion(fallback)))- .with_priority(u8::MAX)- .mount(&server)- .await;- server-}--/// A routed provider on `server` with a fixed model.-pub fn route(server: &wiremock::MockServer, model: &str) -> openhuman_embed::Provider {- openhuman_embed::Provider::openai_compatible(format!("{}/v1", server.uri()), "sk-test")- .model(model)-}--/// Polls `check` until it yields `Some` or about ten seconds pass.-pub async fn eventually<T>(what: &str, mut check: impl FnMut() -> Option<T>) -> T {- for _ in 0..1000 {- if let Some(value) = check() {- return value;- }- tokio::time::sleep(std::time::Duration::from_millis(10)).await;- }- panic!("timed out waiting for {what}");-}diff --git a/crates/openhuman-embed/tests/public_api.rs b/crates/openhuman-embed/tests/public_api.rsindex dcb19c5f48..de78933097 100644--- a/crates/openhuman-embed/tests/public_api.rs+++ b/crates/openhuman-embed/tests/public_api.rs@@ -1,11 +1,10 @@use std::sync::Arc;use openhuman_embed::{- Access, Agent, AgentDefinitionSpec, AgentError, AgentSpec, AgentTurnOrigin, ApiKey,- ApprovalDecision, Approvals, ApprovalsError, Core, CoreBuilder, CoreError, CoreRuntime,- DomainSet, GroupMode, Harness, HostKind, PendingApproval, Provider, RemoveAgent, Runtime,- RuntimeBuilder, RuntimeConfig, SandboxModeSpec, ServiceSet, ToolGroups, ToolScopeSpec,- TrustedAccess, TrustedAutomationSource, Workspace, DEFAULT_MAX_AGENTS,+ Access, Agent, AgentDefinitionSpec, AgentSpec, AgentTurnOrigin, ApiKey, Core, CoreBuilder,+ CoreRuntime, DomainSet, GroupMode, Harness, HostKind, Provider, Runtime, RuntimeBuilder,+ RuntimeConfig, SandboxModeSpec, ServiceSet, ToolGroups, ToolScopeSpec, TrustedAccess,+ TrustedAutomationSource, Workspace,};#[test]@@ -28,23 +27,6 @@ fn exposes_the_host_facing_embedding_contract() {fn accepts_agent(_: Agent) {}fn accepts_agent_spec(_: AgentSpec) {}fn accepts_api_key(_: ApiKey) {}- fn agent_approvals(agent: &Agent) -> Approvals {- agent.approvals()- }- fn lists_pending(approvals: &Approvals) -> Result<Vec<PendingApproval>, ApprovalsError> {- approvals.pending()- }- fn removes_agent<'a>(runtime: &'a Runtime, id: &str) -> RemoveAgent<'a> {- runtime.remove_agent(id).purge()- }- fn lifecycle_errors(error: &AgentError) -> Option<usize> {- match error {- AgentError::AgentLimit { limit } => Some(*limit),- AgentError::UnknownId(_) => None,- AgentError::Call(CoreError::AgentRemoved { .. }) => None,- _ => None,- }- }let _ = accepts_core;let _ = accepts_builder;@@ -59,16 +41,9 @@ fn exposes_the_host_facing_embedding_contract() {let _ = accepts_agent;let _ = accepts_agent_spec;let _ = accepts_api_key;- let _ = agent_approvals;- let _ = lists_pending;- let _ = removes_agent;- let _ = lifecycle_errors;- let _ = ApprovalDecision::ApproveOnce;- assert_eq!(DEFAULT_MAX_AGENTS, 1024);let _ = Runtime::builder().api_key("th_public_api")- .backend_url("https://backend.example")- .max_agents(DEFAULT_MAX_AGENTS);+ .backend_url("https://backend.example");let _ = AgentSpec::new("public-api").system_prompt("You are a test.").definition(@@ -76,13 +51,7 @@ fn exposes_the_host_facing_embedding_contract() {.tools(ToolScopeSpec::Named(vec!["read_file".into()])).sandbox(SandboxModeSpec::ReadOnly),)- .subagents([("public-api-helper", AgentDefinitionSpec::new())])- .access(- Access::readonly()- .auto_approve(["read_file"])- .auto_approve_all(false)- .approval_gate(true),- )+ .access(Access::readonly()).action_dir("/tmp/embed-public-api").include_user_skills(false).config(|_config| {});diff --git a/crates/openhuman-embed/tests/runtime_agents.rs b/crates/openhuman-embed/tests/runtime_agents.rsindex 7cb49093db..1e81eb4080 100644--- a/crates/openhuman-embed/tests/runtime_agents.rs+++ b/crates/openhuman-embed/tests/runtime_agents.rs@@ -335,10 +335,7 @@ fn one_runtime_hosts_independently_configured_agents() {// Layout: every agent has its own home, transcripts and action dir.assert_eq!(alpha.home_dir(), workspace_dir.join("agents/alpha"));- assert_eq!(- alpha.transcripts_dir(),- workspace_dir.join("agents/alpha/session_raw")- );+ assert_eq!(alpha.transcripts_dir(), workspace_dir.join("session_raw"));assert_eq!(alpha.action_dir(), root_dir.join("agents/alpha/action"));assert!(alpha.action_dir().is_dir());assert_eq!(beta.action_dir(), beta_action.path());@@ -399,20 +396,12 @@ fn one_runtime_hosts_independently_configured_agents() {let b_body: serde_json::Value = serde_json::from_slice(&b_reqs[0].body).unwrap();assert_eq!(a_body["model"], "alpha-model");assert_eq!(b_body["model"], "beta-model");- // Transcripts are keyed by agent and live in the agent's own- // directory, and a thread resumes its own history.- let listing = |dir: &std::path::Path| -> Vec<String> {- std::fs::read_dir(dir)- .expect("transcript dir")- .flatten()- .map(|e| e.file_name().to_string_lossy().into_owned())- .collect()- };- assert!(- !workspace_dir.join("session_raw").exists()- || listing(&workspace_dir.join("session_raw")).is_empty(),- "no agent writes to the shared transcript directory"- );+ // Transcripts are keyed by agent, and a thread resumes its own history.+ let transcripts: Vec<String> = std::fs::read_dir(alpha.transcripts_dir())+ .expect("transcript dir")+ .flatten()+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .collect();// Asserted against names the writer itself produced, not a shape// of our own. A turn's `session_id` is the raw session key the// runtime minted; TinyAgents derives the transcript stem from it@@ -420,9 +409,7 @@ fn one_runtime_hosts_independently_configured_agents() {// component carrying a disambiguating digest). The previous// `_alpha.jsonl` expectation predates that encoding — hosts used// to mint `{unix_ts}_{agent}` stems — so it can no longer match.- for (agent, session_id) in [(&alpha, &a1.session_id), (&beta, &b0.session_id)] {- let agent_id = agent.id();- let transcripts = listing(agent.transcripts_dir());+ for (agent_id, session_id) in [("alpha", &a1.session_id), ("beta", &b0.session_id)] {let transcript = transcripts.iter().find(|f| f.starts_with(&format!("{session_id}-")))diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rsindex 0ef4b84e6a..fbc21b5d21 100644--- a/crates/openhuman-rpc/src/server/socketio.rs+++ b/crates/openhuman-rpc/src/server/socketio.rs@@ -997,7 +997,6 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {run_id,tool_name,summary,- agent_id: _,} => {let payload = serde_json::json!({"request_id": request_id,diff --git a/gitbooks/features/integrations/mcp-and-skills.md b/gitbooks/features/integrations/mcp-and-skills.mdindex 5d0948a03b..3a2b39636c 100644--- a/gitbooks/features/integrations/mcp-and-skills.md+++ b/gitbooks/features/integrations/mcp-and-skills.md@@ -28,9 +28,7 @@ It also works the other way. `openhuman-core mcp` exposes OpenHuman over stdio aSkills are a large, browsable catalog of `SKILL.md` capability bundles, gathered from several public sources such as HermesHub, ClawHub and LobeHub.- **One catalog.** It comes from HermesHub, and you can point to another source with `OPENHUMAN_SKILL_REGISTRY_CATALOG_URL`. It holds roughly 90,000 entries. Each entry has an id, name, description, source, author, version, tags, platforms, a download URL and a license.-- **Paged and cached.** The `tinyskills` skill registry serves the catalog. The app asks for one page at a time (25 rows, filtered and ranked by the core), and opening an entry loads its full detail. The catalog loads in the background at startup without blocking it, and is saved at `~/.openhuman/skill-registry/hermes.json` (`OPENHUMAN_SKILL_REGISTRY_CACHE_DIR` moves it). While a refresh runs, or when the registry cannot be reached, the tab keeps showing the saved catalog, says so, and offers Retry. After a failed refresh the registry waits 45 seconds (longer if the upstream asks) before trying again, so a Retry inside that window shows the saved catalog without a new download.-- **Guarded downloads.** Installs fetch `SKILL.md` over HTTPS only, refuse non-public addresses and re-check every redirect. Entries without a `SKILL.md` (LobeHub agents, portal pages) show "Not installable" with a link to their source page. `OPENHUMAN_SKILL_REGISTRY_DOWNLOAD_BASE_URL` serves every `SKILL.md` from a mirror, and `OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP=1` allows a loopback `http` mirror for local fixtures.-- **Security scan before install.** Every downloaded `SKILL.md`, from the catalog or a pasted URL, is scanned for supply-chain red flags such as invisible characters and hard-coded credentials. If the scan blocks it, or the download fails, OpenHuman fetches and scans it once more. If it still blocks, nothing is installed and the app shows the findings with two choices: **Block install** (the default) or **Install anyway**. Install anyway installs exactly the document you reviewed: if it changed in the meantime, it is scanned again and you are asked again. Only you can choose Install anyway. An agent that tries to install a blocked skill is told to ask you to do it from the Skills page.+- **Cached.** The catalog loads in the background at startup without blocking it. It is cached at `~/.openhuman/skill-registry/cache.json` for about an hour and refreshed while stale entries are still served. A single download runs at a time.- **Metadata first.** Skills are a catalog you browse and install from the **Connections > Skills** tab. They are not code running inside the app. Availability varies by entry: some offer a direct `SKILL.md` download, and others point to external hosting.## See alsodiff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjsindex e75700a10a..6a7549963d 100644--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@ -38,14 +38,14 @@ const LEGACY_LIMIT_ENTRIES = [// under the general 750 limit, so it needs no exception at all.// The session-todo integration added transcript metadata construction to// this already-exempt composition seam. Keep its allowance exact.- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1466],+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1465],// Session-host factory still assembles the product's deliberately coupled// 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", 977],- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1306],- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1145],+ ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1309],+ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1149],["crates/openhuman-core/src/tools/ops.rs", 1208],["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1304],// These established external test modules grew with upstream coverage. Pin@@ -55,7 +55,7 @@ const LEGACY_LIMIT_ENTRIES = [["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", 997],+ ["crates/openhuman-core/src/core/events_tests.rs", 1003],["crates/openhuman-core/src/core/observability.rs", 3502],];const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);