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
Revert "refactor(agent): replace registry current() with global() and drop searches_connected_mcp"
Steven Enamakel79b1ce5f6573
diff --git a/crates/openhuman-core/src/agent/bus.rs b/crates/openhuman-core/src/agent/bus.rsindex 000d4242f9..c18f3842ab 100644--- a/crates/openhuman-core/src/agent/bus.rs+++ b/crates/openhuman-core/src/agent/bus.rs@@ -272,8 +272,10 @@ 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::global().and_then(|reg| reg.get(id)))- .map(|def| def.sandbox_mode)+ .and_then(|id| {+ AgentDefinitionRegistry::current()+ .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 19df0b49f9..9e2e20eace 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::global()+ let registry = AgentDefinitionRegistry::current().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 1d68a69aff..5fc645ff06 100644--- a/crates/openhuman-core/src/agent/harness/builtin_definitions.rs+++ b/crates/openhuman-core/src/agent/harness/builtin_definitions.rs@@ -80,6 +80,7 @@ pub(crate) fn test_main_def() -> AgentDefinition {],delegate_name: None,agent_tier: AgentTier::Chat,+ searches_connected_mcp: false,source: DefinitionSource::Builtin,graph: Default::default(),}@@ -122,6 +123,7 @@ 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(),}@@ -160,6 +162,7 @@ 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 ca712b51b5..c3e27dbbf7 100644--- a/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs+++ b/crates/openhuman-core/src/agent/harness/definition/agent_definition.rs@@ -233,6 +233,12 @@ 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 460f2e4258..0355f88481 100644--- a/crates/openhuman-core/src/agent/harness/definition/registry.rs+++ b/crates/openhuman-core/src/agent/harness/definition/registry.rs@@ -151,4 +151,29 @@ 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 0ad1163d93..a28b3cae28 100644--- a/crates/openhuman-core/src/agent/harness/definition_tests.rs+++ b/crates/openhuman-core/src/agent/harness/definition_tests.rs@@ -28,6 +28,7 @@ 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 2879b7c5ba..92a89073d2 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::global()+ let registry = AgentDefinitionRegistry::current().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 76dcc628c2..62c7059d5e 100644--- a/crates/openhuman-core/src/agent/library/ops_tests.rs+++ b/crates/openhuman-core/src/agent/library/ops_tests.rs@@ -34,6 +34,7 @@ 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 19e5190401..877911a5f2 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::Config::load_or_init()+ let config = crate::config::ops::load_current_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 141049422b..f22182cc0a 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();- tokio::spawn(async move {+ crate::core::runtime::spawn_scoped(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 2b2b377b91..9b6c44d0c8 100644--- a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs+++ b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs@@ -147,9 +147,11 @@ 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::global()- .and_then(|registry| registry.get(agent_id))- .map(|definition| definition.display_name().to_string())+ AgentDefinitionRegistry::current().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 1d01d9f9e7..b4e34920da 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::global() else {+ let Some(registry) = AgentDefinitionRegistry::current() 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 4c77048854..bdff6d130e 100644--- a/crates/openhuman-core/src/agent/orchestration/ops.rs+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs@@ -338,9 +338,8 @@ impl AgentOrchestrationSession {let progress_sink = parent.on_progress.clone();if let Some(progress) = progress_sink.clone() {- let resolved_display_name = AgentDefinitionRegistry::global()- .and_then(|reg| reg.get(&agent_id))- .map(|def| def.display_name().to_string());+ let resolved_display_name = AgentDefinitionRegistry::current()+ .and_then(|reg| reg.get(&agent_id).map(|def| def.display_name().to_string()));let _ = progress.send(AgentProgress::SubagentSpawned {agent_id: agent_id.clone(),@@ -664,7 +663,7 @@ fn resolve_definition(request: &SpawnAgentRequest) -> Result<AgentDefinition, Orreturn Err(OrchestrationError::InvalidSpawnRequest);}let registry =- AgentDefinitionRegistry::global().ok_or(OrchestrationError::RegistryUnavailable)?;+ AgentDefinitionRegistry::current().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 63a5fd7390..8349ea765f 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::global() {+ let registry = match AgentDefinitionRegistry::current() {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(registry);+ let definitions = snapshot_agent_definitions(®istry);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 a14e87b74d..04255ca5c8 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::global() {+ let registry = match AgentDefinitionRegistry::current() {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 0208746795..d795c944c9 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs@@ -12,7 +12,6 @@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;@@ -111,7 +110,7 @@ impl Tool for DelegateGraphTool {}fn parameters_schema(&self) -> serde_json::Value {- let agent_ids: Vec<String> = AgentDefinitionRegistry::global()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::current().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();@@ -212,7 +211,7 @@ impl DelegateGraphTool {.map(|n| (n as usize).min(MAX_MAX_REVISIONS)).unwrap_or(DEFAULT_MAX_REVISIONS);- let registry = match AgentDefinitionRegistry::global() {+ let registry = match AgentDefinitionRegistry::current() {Some(reg) => reg,None => {return Ok(ToolResult::error(@@ -229,7 +228,7 @@ impl DelegateGraphTool {}};- let config = match Config::load_or_init().await {+ let config = match crate::config::ops::load_current_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 e1c09cac96..357e2d3744 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::global().is_some_and(|registry| {+ name if AgentDefinitionRegistry::current().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::global().and_then(|registry| {+ let Some(agent_id) = AgentDefinitionRegistry::current().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::global() {+ let registry = match AgentDefinitionRegistry::current() {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 5dde5cba7d..6c3cdc93de 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::global()+ AgentDefinitionRegistry::current().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 1418abf888..5006e5c60b 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::global() {+ let registry = match AgentDefinitionRegistry::current() {Some(registry) => registry,None => {return Ok(ToolResult::error(@@ -141,7 +141,7 @@ impl SpawnAsyncSubagentTool {workspace.root.clone()}).or_else(|| {- crate::security::live_policy::current().map(|policy| policy.action_dir.clone())+ crate::security::live_policy::effective().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 2b5e5fbcdb..17c7a79218 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::global()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::current().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 050ccd6cd7..16c98ada2f 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,6 +170,7 @@ 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 a8d9d59b15..9f0a1a6cac 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::global()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::current().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 f51aece529..3180ef9023 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::global() {+ let registry = match AgentDefinitionRegistry::current() {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 58f4a3eee7..7980043627 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::global()+ let agent_ids: Vec<String> = AgentDefinitionRegistry::current().map(|reg| reg.list().iter().map(|d| d.id.clone()).collect()).unwrap_or_default();@@ -269,7 +269,7 @@ impl SpawnWorkerThreadTool {}}- let registry = AgentDefinitionRegistry::global()+ let registry = AgentDefinitionRegistry::current().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 4ce684d3ba..d16a303246 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();- tokio::spawn(async move {- match Config::load_or_init().await {+ crate::core::runtime::spawn_scoped(async move {+ match crate::config::ops::load_current_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();- tokio::spawn(async move {- match Config::load_or_init().await {+ crate::core::runtime::spawn_scoped(async move {+ match crate::config::ops::load_current_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 c5e80a08e4..82e4361095 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::global().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::current().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 347d6c06b9..a55d436b70 100644--- a/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.toml+++ b/crates/openhuman-core/src/agent/registry/agents/orchestrator/agent.toml@@ -14,6 +14,8 @@ 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 db153a9621..56713425bf 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::global() else {+ let Some(registry) = AgentDefinitionRegistry::current() else {tracing::debug!("[orchestrator-prompt] no agent registry; withheld-specialist section omitted");return String::new();};- let Some(definition) = resolve_definition(registry, ctx.agent_id) else {+ let Some(definition) = resolve_definition(®istry, 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::global()?;- let definition = resolve_definition(registry, ctx.agent_id)?;+ let registry = AgentDefinitionRegistry::current()?;+ let definition = resolve_definition(®istry, 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::global() else {+ let Some(registry) = AgentDefinitionRegistry::current() else {return false;};- let Some(definition) = resolve_definition(registry, ctx.agent_id) else {+ let Some(definition) = resolve_definition(®istry, 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 a8c5dce3f2..27d71607e0 100644--- a/crates/openhuman-core/src/agent/registry/defaults.rs+++ b/crates/openhuman-core/src/agent/registry/defaults.rs@@ -113,6 +113,7 @@ 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 5a2c7b13e7..2d242c8085 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::global()+ let registry = crate::agent::harness::AgentDefinitionRegistry::current().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 86b8541323..d8cc248d40 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::global_arc().unwrap_or_else(|| {+ crate::agent::harness::AgentDefinitionRegistry::current().unwrap_or_else(|| {Arc::new(crate::agent::harness::AgentDefinitionRegistry::builtins_only())}),);#[cfg(not(test))]- let definitions = crate::agent::harness::AgentDefinitionRegistry::global_arc();+ let definitions = crate::agent::harness::AgentDefinitionRegistry::current();// 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 641dd53ed7..a50fd418eb 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::global()`+ /// rather than an id resolved through `AgentDefinitionRegistry::current()`/// 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::global(),+ crate::agent::harness::definition::AgentDefinitionRegistry::current(),) {// Host-only: no delegation; the host's names join an empty belt._ if host_only => (Vec::new(), Some(super::host_only::empty_belt())),@@ -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::global()`, see+ // ever consulting `AgentDefinitionRegistry::current()`, 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::global() {+ match crate::agent::harness::definition::AgentDefinitionRegistry::current() {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::global_arc().map(|definitions| {+ agent.hosted_base = AgentDefinitionRegistry::current().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::global();+ let registry = AgentDefinitionRegistry::current();- if let Some(reg) = registry {+ if let Some(reg) = registry.as_deref() {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 4aeae07382..da250aca38 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::global() else {+ let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::current() 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 0d5de02e76..a08264b002 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -10,6 +10,25 @@ 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.@@ -157,7 +176,15 @@ 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.agent_definition_id != "orchestrator" {+ 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"+ );return Vec::new();}let Some(config) = self.runtime_config.as_ref() else {@@ -191,7 +218,7 @@ impl OpenHumanTurnPrelude {}let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::Config::load_or_init()+ None => crate::config::ops::load_current_or_init().await.ok().map(Arc::new),@@ -240,7 +267,7 @@ impl OpenHumanTurnPrelude {let skills_changed = self.drain_host_events();let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::Config::load_or_init()+ None => crate::config::ops::load_current_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 7a2a7cac75..6c2a9e6363 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::global().get(..)` in+ /// Prefer this over a bare `AgentDefinitionRegistry::current().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,9 +149,8 @@ impl OpenHumanSessionHost {&self,) -> Option<Arc<crate::agent::harness::definition::AgentDefinition>> {self.definition.clone().or_else(|| {- crate::agent::harness::definition::AgentDefinitionRegistry::global()- .and_then(|registry| registry.get(&self.agent_definition_id))- .cloned()+ crate::agent::harness::definition::AgentDefinitionRegistry::current()+ .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 5afbd5828b..ced685c839 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -94,6 +94,7 @@ 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>,@@ -351,19 +352,18 @@ impl OpenHumanTurnPrelude {}/// Rebuild every delegation-dependent tool view from the current cached- /// 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.+ /// integration set, replacing rather than appending. 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::global() else {+ let Some(registry) = AgentDefinitionRegistry::current() else {return Ok(());};- let Some(definition) = registry.get(&self.agent_definition_id).cloned() else {+ let Some(definition) = self.session_definition(®istry) 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, registry, &integrations);+ let mut collected = collect_orchestrator_tools(&definition, ®istry, &integrations);#[cfg(feature = "mcp")]collected.extend(mcp_tools);let rebuilt = self.rebuilt_recorded_tools(@@ -1008,6 +1008,7 @@ 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 5bd6ae37cc..ce423d758b 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();- tokio::spawn(async move {+ crate::core::runtime::spawn_scoped(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 e55a00975e..5e3a0948b0 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::global() else {+ let Some(reg) = AgentDefinitionRegistry::current() 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, reg, &self.connected_integrations),+ collect_orchestrator_tools(&def, ®, &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 1dd6aca711..de4e3cfb21 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::Config::load_or_init().await {+ let cfg = match crate::config::ops::load_current_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 beea34f1f9..fddcdafd95 100644--- a/crates/openhuman-core/src/agent/session_store/mod.rs+++ b/crates/openhuman-core/src/agent/session_store/mod.rs@@ -16,8 +16,11 @@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));@@ -136,12 +139,30 @@ pub fn transcripts_or_files(workspace_dir: &std::path::Path,) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {transcripts_for(agent_id).unwrap_or_else(|| {- Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(- workspace_dir,- ))+ 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,+ )),+ }})}+/// 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 ed78d48610..09629d9ec3 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, OnceLock},+ sync::{Arc, Mutex},};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)]-struct HostLifecycleKey {+pub(super) struct HostLifecycleKey {checkpoint_dir: PathBuf,task_key: SubagentTaskKey,}@@ -212,11 +212,8 @@ fn host_observer_outcome(mut outcome: SubagentRunOutcome) -> SubagentRunOutcomeoutcome}-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()))+pub(super) fn host_in_flight() -> Arc<AsyncMutex<HashMap<HostLifecycleKey, Arc<HostInFlight>>>> {+ crate::core::runtime::current_slot()}fn absolute_checkpoint_dir(path: PathBuf) -> PathBuf {@@ -304,7 +301,7 @@ impl OpenHumanSubagentHost {task_key: task_key.clone(),};let (entry, is_leader) = {- let mut entries = host_in_flight().lock().await;+ let mut entries = host_in_flight().lock_owned().await;match entries.get(&lifecycle_key) {Some(entry) => (entry.clone(), false),None => {@@ -342,7 +339,7 @@ impl OpenHumanSubagentHost {)).await;entry.complete(result.as_ref().ok().cloned()).await;- let mut entries = host_in_flight().lock().await;+ let mut entries = host_in_flight().lock_owned().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 25bd69fc2e..e230176aaf 100644--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_tests.rs@@ -4,7 +4,8 @@ use tinyagents_orchestration::subagent::{};use super::lifecycle::{- load_subagent_checkpoint, merged_resume_history, HostInFlight, OpenHumanPersistence,+ host_in_flight, load_subagent_checkpoint, merged_resume_history, HostInFlight,+ OpenHumanPersistence,};use super::{SubagentMode, SubagentRunOutcome, SubagentRunStatus, SubagentUsage};@@ -319,3 +320,21 @@ 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 073f6002f3..8f267b6979 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,7 +56,8 @@ pub(super) fn persist_subagent_transcript() {use tinyagents_session::transcript;- let path = match transcript::resolve_keyed_transcript_path(workspace_dir, transcript_stem) {+ let root = crate::agent::session_store::transcript_root(workspace_dir);+ let path = match transcript::resolve_keyed_transcript_path(&root, 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 3296d45879..2eeb4a694c 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -280,8 +280,10 @@ 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_def =- AgentDefinitionRegistry::global().and_then(|reg| reg.get(&parent.agent_definition_id));+ let parent_registry = AgentDefinitionRegistry::current();+ let parent_def = parent_registry+ .as_deref()+ .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@@ -312,15 +314,9 @@ pub(crate) async fn run_subagent_direct(return Err(SubagentRunError::HookDenied(reason));}- // 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())+ // 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()).await.map(std::sync::Arc::new).map_err(|e| e.to_string());@@ -465,7 +461,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::current();+ let policy = crate::security::live_policy::effective();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 a29981f088..a2747625c1 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests.rs@@ -30,6 +30,7 @@ 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 f14d65e8c4..ff00780d38 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::global() {+ if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::current() {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 938fd73391..88351d45d9 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::global() {+ if let Some(runtime) = crate::agent::harness::definition::AgentDefinitionRegistry::current() {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 abcc191c54..80a31d9988 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::current`] so an autonomy+ /// [`crate::security::live_policy::effective`] 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 live process-global one when+ /// The policy to answer this call against: the agent's or the live one when/// installed, else the constructor snapshot.fn effective_policy(&self) -> Arc<SecurityPolicy> {- crate::security::live_policy::current().unwrap_or_else(|| self.policy.clone())+ crate::security::live_policy::effective().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 4b81b1187f..3e719fa573 100644--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs@@ -47,8 +47,6 @@ 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::{@@ -62,11 +60,14 @@ 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.-static REQUEST_JOURNAL_RUNS: Lazy<Mutex<HashMap<String, String>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+fn request_journal_runs() -> std::sync::Arc<RequestJournalRuns> {+ crate::core::runtime::current_slot::<RequestJournalRuns>()+}++type RequestJournalRuns = Mutex<HashMap<String, String>>;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!(@@ -85,7 +86,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))@@ -95,7 +96,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::Config::load_or_init()+ let config = crate::config::ops::load_current_or_init().await.map_err(|e| anyhow::anyhow!("[journal] load config for workspace: {e}"))?;Ok(config.workspace_dir)@@ -263,3 +264,7 @@ 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 f2977283ad..70b0ce4890 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::Config::load_or_init().await;+ let config_loaded = crate::config::ops::load_current_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 80401a1cdd..b2ef8ca627 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs@@ -34,6 +34,7 @@ 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 95cee0a6a1..81972de0fe 100644--- a/crates/openhuman-core/src/agent/tinyagents/reasoning.rs+++ b/crates/openhuman-core/src/agent/tinyagents/reasoning.rs@@ -14,16 +14,17 @@//! Nothing set means the provider keeps its own default.use std::collections::HashMap;-use std::sync::OnceLock;+use std::sync::Arc;use parking_lot::Mutex;use tinyinference_llm::model::{ReasoningConfig, ReasoningEffort};use crate::config::Config;-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()))+type ThreadEfforts = Mutex<HashMap<String, ReasoningEffort>>;++fn thread_efforts() -> Arc<ThreadEfforts> {+ crate::core::runtime::current_slot::<ThreadEfforts>()}/// The effort a thread's user picked, if any.@@ -33,7 +34,8 @@ 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 mut map = thread_efforts().lock();+ let efforts = thread_efforts();+ let mut map = 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 f45d6d9a14..5814d3f6c0 100644--- a/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/reasoning_tests.rs@@ -228,3 +228,27 @@ 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 a17edb970f..9393c5a9b9 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::Config::load_or_init()+ let config = crate::config::ops::load_current_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 a8e3438fa0..bb11a50a40 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::OnceLock;+use std::sync::Arc;use parking_lot::Mutex;use tinyagents_harness::middleware::{RunMode, RunModeHandle};@@ -24,9 +24,10 @@ use tinyagents_harness::middleware::{RunMode, RunModeHandle};use crate::core::bus::BUS;use crate::core::events::DomainEvent;-fn registry() -> &'static Mutex<HashMap<String, RunModeHandle>> {- static REGISTRY: OnceLock<Mutex<HashMap<String, RunModeHandle>>> = OnceLock::new();- REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))+type RunModeRegistry = Mutex<HashMap<String, RunModeHandle>>;++fn registry() -> Arc<RunModeRegistry> {+ crate::core::runtime::current_slot::<RunModeRegistry>()}/// Returns the [`RunModeHandle`] for `thread_id`, creating one (starting in@@ -34,7 +35,8 @@ fn registry() -> &'static Mutex<HashMap<String, RunModeHandle>> {/// 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 mut map = registry().lock();+ let registry = registry();+ 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 324e52f0e1..a91f77e9a1 100644--- a/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/run_mode_tests.rs@@ -31,3 +31,27 @@ 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 c7d9a6ec66..abbccd3645 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 process-lifetime spawn backstop,+//! Guardrails (see the `guard` module): a per-agent 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,55 +55,64 @@ const MAX_WAIT_SECONDS: u64 = 600;mod guard {use std::collections::HashSet;use std::sync::atomic::{AtomicU64, Ordering};- use std::sync::{LazyLock, Mutex};+ use std::sync::{Arc, Mutex};- /// Process-lifetime backstop against a runaway spawn loop.+ /// Per-agent 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;- 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()));+ /// 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>()+ }/// 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) {- ACTIVE_AWAITS.fetch_sub(1, Ordering::SeqCst);- if let Ok(mut keys) = ACTIVE_KEYS.lock() {+ self.state.active_awaits.fetch_sub(1, Ordering::SeqCst);+ if let Ok(mut keys) = self.state.active_keys.lock() {keys.remove(&self.key);}}}- /// Account a spawn against the process-lifetime backstop. Returns `Err`+ /// Account a spawn against the agent's 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 = TOTAL_SPAWNS.fetch_add(1, Ordering::SeqCst) + 1;+ let n = state().total_spawns.fetch_add(1, Ordering::SeqCst) + 1;if n > TOTAL_SPAWN_BACKSTOP {return Err(format!(- "refused — process spawn backstop hit ({TOTAL_SPAWN_BACKSTOP} workflow runs \+ "refused — spawn backstop hit ({TOTAL_SPAWN_BACKSTOP} workflow runs \spawned this session). This guards against a runaway spawn loop."));}Ok(())}- /// Test-only reader for the process-lifetime spawn counter. Used by the+ /// Test-only reader for the agent's 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 {- TOTAL_SPAWNS.load(Ordering::SeqCst)+ state().total_spawns.load(Ordering::SeqCst)}/// Acquire an await slot + re-entrancy lock for `key` (a workflow-id +@@ -111,7 +120,9 @@ 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 mut keys = ACTIVE_KEYS+ let state = state();+ let mut keys = state+ .active_keys.lock().map_err(|_| "internal guard lock poisoned".to_string())?;if keys.contains(&key) {@@ -121,7 +132,7 @@ mod guard {.to_string(),);}- if ACTIVE_AWAITS.load(Ordering::SeqCst) >= MAX_ACTIVE_AWAITS {+ if state.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 \@@ -129,8 +140,9 @@ mod guard {));}keys.insert(key.clone());- ACTIVE_AWAITS.fetch_add(1, Ordering::SeqCst);- Ok(AwaitGuard { key })+ state.active_awaits.fetch_add(1, Ordering::SeqCst);+ drop(keys);+ Ok(AwaitGuard { key, state })}}@@ -326,7 +338,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 process backstop.+ // the 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 fd7c5892f5..5117fb54a8 100644--- a/crates/openhuman-core/src/agent/tools/run_workflow_tests.rs+++ b/crates/openhuman-core/src/agent/tools/run_workflow_tests.rs@@ -162,3 +162,26 @@ 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 59fb348e13..93e53bea7e 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::Config::load_or_init()+ None => crate::config::ops::load_current_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 3c995bb7f3..cf9b0336a0 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 = Config::load_or_init()+ let config = crate::config::ops::load_current_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::global()+ let registry = AgentDefinitionRegistry::current().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 a8b1e65b86..4d17e54cd1 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::global().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::current().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 36df152441..08f116b842 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/chain.rs@@ -7,7 +7,6 @@ use std::time::Duration;use anyhow::Context;-use crate::config::Config;use crate::cron::scheduler_gate::LlmPermit;use super::super::envelope::TriggerEnvelope;@@ -77,7 +76,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 = Config::load_or_init()+ let config = crate::config::ops::load_current_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 a8f37459ae..797e51138c 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 scoped **right now** into a future that will run on-/// another task.+/// Carry the origin and the [`CoreContext`](crate::core::runtime::CoreContext)+/// 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,10 +309,17 @@ 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 {- match captured {- Some(origin) => with_origin(origin, fut).await,- None => fut.await,+ 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,}}}diff --git a/crates/openhuman-core/src/channels/host/channel_events_tests.rs b/crates/openhuman-core/src/channels/host/channel_events_tests.rsindex cccf6ec3a6..f2f5ec1079 100644--- a/crates/openhuman-core/src/channels/host/channel_events_tests.rs+++ b/crates/openhuman-core/src/channels/host/channel_events_tests.rs@@ -81,6 +81,7 @@ 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 729a69cbf7..04f0763fdf 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,6 +73,7 @@ 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 d2f7f5afd0..7a41460140 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::global() {+ let registry = match AgentDefinitionRegistry::current() {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, registry, &connected)+ orchestrator_tools::collect_orchestrator_tools(definition, ®istry, &connected)} else {Vec::new()};diff --git a/crates/openhuman-core/src/config/ops/loader.rs b/crates/openhuman-core/src/config/ops/loader.rsindex fa25a8f0fa..b75f07965e 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, reload_config_from_paths,- reload_config_snapshot_with_timeout,+ load_config_for_workspace_with_timeout, load_config_with_timeout, load_current_or_init,+ reload_config_from_paths, reload_config_snapshot_with_timeout,};pub(crate) use paths::fallback_workspace_dir;#[cfg(test)]@@ -43,3 +43,7 @@ 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 eb72552e19..dc01179acd 100644--- a/crates/openhuman-core/src/config/ops/loader/load.rs+++ b/crates/openhuman-core/src/config/ops/loader/load.rs@@ -55,6 +55,30 @@ 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 d3718bddad..36a739dd29 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, 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, load_current_or_init,+ 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 bbb3efb305..efba0df950 100644--- a/crates/openhuman-core/src/core/bus.rs+++ b/crates/openhuman-core/src/core/bus.rs@@ -83,7 +83,9 @@ 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).-pub const EVENTS_VERSION: Version = Version::new(1, 8, 0);+/// `1.9.0` adds an optional `agent_id` to `ApprovalRequested`,+/// `ApprovalDecided` and `FlowApprovalRequested` (additive).+pub const EVENTS_VERSION: Version = Version::new(1, 9, 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 c38b5113f7..edfe2e3608 100644--- a/crates/openhuman-core/src/core/events.rs+++ b/crates/openhuman-core/src/core/events.rs@@ -531,15 +531,10 @@ 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. 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.+ /// 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.ApprovalRequested {/// Unique id used to correlate the decision back to the/// parked future.@@ -570,6 +565,9 @@ 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.@@ -600,17 +598,16 @@ 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` (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.+ /// 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.FlowApprovalRequested {/// Unique id used to correlate the decision back to the parked/// future — pass to `approval_decide` unchanged.@@ -625,6 +622,9 @@ 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 6237de5c80..87845498e3 100644--- a/crates/openhuman-core/src/core/events_tests.rs+++ b/crates/openhuman-core/src/core/events_tests.rs@@ -535,15 +535,8 @@ fn all_variants_have_correct_domain() {}}-/// 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.+/// [`DomainEvent::ApprovalRequested`] must never carry a `session_id`, which+/// could hold the JSON-RPC bearer and leak through any Debug print.#[test]fn approval_requested_does_not_surface_session_id() {let event = DomainEvent::ApprovalRequested {@@ -555,6 +548,7 @@ 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 ddf07b1612..422d513ee9 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -107,66 +107,8 @@ 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>,-}--/// 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- }+ /// What the agent this context was derived for owns.+ agent: agent_parts::AgentParts,}/// The workspace a context is bound to.@@ -323,6 +265,7 @@ impl CoreContext {backend_transport,turn_origin: None,session_agent: None,+ agent: Default::default(),});let _ = DEFAULT_CONTEXT.set(ctx.clone());@@ -381,7 +324,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, overlay: ContextOverlay) -> Arc<CoreContext> {+ pub fn derive_with(&self, mut 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@@ -428,6 +371,7 @@ impl CoreContext {})),}};+ let agent = self.agent.derive(&mut overlay);Arc::new(CoreContext {host_kind: self.host_kind,workspace_binding: RwLock::new(shared_binding),@@ -438,6 +382,7 @@ 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,})}@@ -588,6 +533,7 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,+ agent: Default::default(),})}@@ -618,6 +564,7 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,+ agent: Default::default(),})}}@@ -741,6 +688,13 @@ 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 dfaef14494..8014605a47 100644--- a/crates/openhuman-core/src/core/runtime/context_tests.rs+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -14,6 +14,7 @@ fn ctx(dir: &str) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,+ agent: Default::default(),})}@@ -45,6 +46,7 @@ fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,+ agent: Default::default(),})}@@ -366,6 +368,7 @@ 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 6e1ba81782..fe41e579fa 100644--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs@@ -50,6 +50,7 @@ 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 b9d55dfc7a..992f7df98a 100644--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@ -43,6 +43,7 @@ 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;@@ -54,6 +55,7 @@ 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 572864689b..639e5fe035 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;-mod store;+pub(crate) 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 8e87f3fa2f..dbf6ce99af 100644--- a/crates/openhuman-core/src/cron/scheduler.rs+++ b/crates/openhuman-core/src/cron/scheduler.rs@@ -75,6 +75,46 @@ 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 bf91eeb13a..cbae4fb0ea 100644--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs@@ -48,7 +48,8 @@ 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::global()+ if let Some(registry) =+ crate::agent::harness::definition::AgentDefinitionRegistry::current(){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 b370831a1f..b143b03f2b 100644--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs@@ -69,8 +69,14 @@ 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 8956f165f3..fccd5629f4 100644--- a/crates/openhuman-core/src/cron/store.rs+++ b/crates/openhuman-core/src/cron/store.rs@@ -17,11 +17,20 @@ use tinyflows_schedule::DeliveryStatus;use tinyflows_schedule::{CronJob, CronJobPatch, CronRun, DeliveryConfig, Schedule, SessionTarget};use tinyflows_sqlite::schedule::{self as upstream, AgentJobSpec, CronStoreOptions};-/// Builds the store options from the host config: `<workspace>/cron/jobs.db`,+/// 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`],/// `cron.max_run_history`, `scheduler.max_tasks`.fn opts(config: &Config) -> CronStoreOptions {CronStoreOptions {- db_path: config.workspace_dir.join("cron").join("jobs.db"),+ db_path: db_path(config),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 4e241a19e5..9bb577eecc 100644--- a/crates/openhuman-core/src/cron/store_tests.rs+++ b/crates/openhuman-core/src/cron/store_tests.rs@@ -48,3 +48,77 @@ 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 c94bceba26..424a932b3a 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::global().and_then(|r| r.get(agent_ref));+ let definition = AgentDefinitionRegistry::current().and_then(|r| r.get(agent_ref).cloned());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,+ definition.as_ref(),);}}diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rsindex 693f0dacb3..8ec8484795 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::global()+ let has_definition = crate::agent::harness::definition::AgentDefinitionRegistry::current().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 4ff2054537..47bcea804e 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(config.workspace_dir.as_path(), &client)+ Self::from_client_config(&host_key(config), &client)}/// Builds a host over `workspace` from an already-converted client@@ -126,6 +126,9 @@ 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)@@ -180,7 +183,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 = config.workspace_dir.clone();+ let workspace = host_key(config);// 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@@ -211,6 +214,7 @@ 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 {@@ -223,6 +227,36 @@ 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@@ -263,6 +297,9 @@ 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()@@ -271,6 +308,42 @@ 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@@ -491,3 +564,7 @@ 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 d6b164db77..6ccfb450b3 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::for_config(config) {+ match host::lookup(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::for_config(config) {+ let service = match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ match host::lookup(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::for_config(config) {+ let service = match host::lookup(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 f04611c11a..889731f61a 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::global().ok_or_else(|| {+ let registry = AgentDefinitionRegistry::current().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 da7668f3e0..2adcb3b6ab 100644--- a/crates/openhuman-core/src/memory/bus.rs+++ b/crates/openhuman-core/src/memory/bus.rs@@ -103,6 +103,28 @@ 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 c773ddccc0..06c2afcae1 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();- tokio::spawn(async move {+ crate::core::runtime::spawn_scoped(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 6e8dddc280..f742d798ad 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, LazyLock, Mutex};+use std::sync::{Arc, Mutex};use async_trait::async_trait;use serde_json::{json, Value};@@ -37,16 +37,20 @@ 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`]).-static TURN_CITATIONS: LazyLock<Mutex<HashMap<String, Vec<TurnCitation>>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));+fn turn_citations() -> Arc<TurnCitations> {+ crate::core::runtime::current_slot::<TurnCitations>()+}fn record_turn_citations(thread_id: &str, citations: &[tinymemory_api::Citation]) {if citations.is_empty() {return;}- let mut all = TURN_CITATIONS+ let citations_by_thread = turn_citations();+ let mut all = citations_by_thread.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let entry = all.entry(thread_id.to_string()).or_default();@@ -67,7 +71,8 @@ pub fn record_pack_citations(thread_id: &str, citations: Vec<TurnCitation>) {if citations.is_empty() {return;}- let mut all = TURN_CITATIONS+ let citations_by_thread = turn_citations();+ let mut all = citations_by_thread.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let entry = all.entry(thread_id.to_string()).or_default();@@ -85,7 +90,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)@@ -354,6 +359,10 @@ impl Tool for MemoryTool {#[path = "tools_tests.rs"]mod tests;+#[cfg(test)]+#[path = "tools_agent_tests.rs"]+mod agent_tests;+#[cfg(test)]#[path = "tools_schema_tests.rs"]mod schema_tests;diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rsindex d6abbb42b4..5ce2fc4b04 100644--- a/crates/openhuman-core/src/security/approval/gate.rs+++ b/crates/openhuman-core/src/security/approval/gate.rs@@ -60,6 +60,23 @@ 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.@@ -204,6 +221,7 @@ 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.@@ -212,8 +230,9 @@ pub struct ApprovalGate {session_id: String,ttl: Duration,waiters: Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>,- /// 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`.+ /// [`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`./// 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>>,@@ -245,7 +264,7 @@ pub struct ApprovalGate {struct WaiterGuard<'a> {gate: &'a ApprovalGate,request_id: String,- thread_id: Option<String>,+ thread_key: Option<String>,/// Storage scope of the parking call, kept for `Drop`: the acting agent's/// task-local is gone by then.docs: Result<Option<super::store_documents::Docs>, String>,@@ -276,9 +295,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_id) = &self.thread_id {+ if let Some(thread_key) = &self.thread_key {self.gate- .clear_thread_route_if_owned(thread_id, &self.request_id);+ .clear_thread_route_if_owned(thread_key, &self.request_id);}let decided = store::decide_captured(&self.gate.config,@@ -296,6 +315,7 @@ 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 3c30be9f7f..a4500bd213 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -198,6 +198,20 @@ 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@@ -391,6 +405,10 @@ 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@@ -435,6 +453,7 @@ 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@@ -449,10 +468,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_id) = chat_thread_id.as_ref() {+ if let Some(thread_key) = thread_key.as_ref() {self.thread_to_request.lock()- .insert(thread_id.clone(), request_id.clone());+ .insert(thread_key.clone(), request_id.clone());}// Record the full routing correlation (thread/client/tool_call_id) so// whichever path resolves this request's decision — `decide()`, the@@ -466,11 +485,12 @@ 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(&chat_thread_id, &request_id);+ self.clear_thread(&thread_key, &request_id);self.take_request_route(&request_id);tracing::error!(error = %err,@@ -493,6 +513,7 @@ 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 {@@ -504,6 +525,7 @@ 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@@ -533,6 +555,7 @@ 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@@ -601,7 +624,7 @@ impl ApprovalGate {let mut waiter_guard = WaiterGuard {gate: self,request_id: request_id.clone(),- thread_id: chat_thread_id.clone(),+ thread_key: thread_key.clone(),docs: store::capture_docs(),armed: true,};@@ -626,7 +649,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(&chat_thread_id, &request_id);+ self.clear_thread(&thread_key, &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 23a6682e23..737d15cdb7 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept_decision.rs@@ -65,6 +65,7 @@ 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(),});}(@@ -164,6 +165,7 @@ 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 0de0391d55..39e994a578 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+ /// Whether `tool_name` is on the user's "Always allow" list. Prefers the agent or/// 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::current() {+ if let Some(policy) = crate::security::live_policy::effective() {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::current() {+ if let Some(policy) = crate::security::live_policy::effective() {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 344169859a..b89655d2e5 100644--- a/crates/openhuman-core/src/security/approval/gate_state.rs+++ b/crates/openhuman-core/src/security/approval/gate_state.rs@@ -72,11 +72,92 @@ 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`:@@ -118,6 +199,15 @@ 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,@@ -213,10 +303,21 @@ impl ApprovalGate {waiters.remove(request_id);}- /// 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.+ /// 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.pub fn pending_for_thread(&self, thread_id: &str) -> Option<String> {- self.thread_to_request.lock().get(thread_id).cloned()+ 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()}/// The full pending row parked on `thread_id`, if any.@@ -264,9 +365,9 @@ impl ApprovalGate {}/// Drop the thread → request mapping when it still belongs to this request.- 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);+ 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);}}@@ -275,10 +376,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_id: &str, request_id: &str) {+ fn clear_thread_route_if_owned(&self, thread_key: &str, request_id: &str) {let mut map = self.thread_to_request.lock();- if map.get(thread_id).is_some_and(|rid| rid == request_id) {- map.remove(thread_id);+ if map.get(thread_key).is_some_and(|rid| rid == request_id) {+ map.remove(thread_key);}}}diff --git a/crates/openhuman-core/src/security/approval/gate_tests.rs b/crates/openhuman-core/src/security/approval/gate_tests.rsindex 5f3cbaa109..3704352a6d 100644--- a/crates/openhuman-core/src/security/approval/gate_tests.rs+++ b/crates/openhuman-core/src/security/approval/gate_tests.rs@@ -198,6 +198,8 @@ 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 4acf392c89..6fbb54fff2 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, ApprovalGate, FlowRunContext, APPROVAL_CHAT_CONTEXT,- APPROVAL_COPILOT_STREAM_CONTEXT, APPROVAL_FLOW_RUN_CONTEXT,+ parse_approval_reply, ApprovalChatContext, ApprovalError, 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 f5f50a65e2..401674d190 100644--- a/crates/openhuman-core/src/security/approval/rpc.rs+++ b/crates/openhuman-core/src/security/approval/rpc.rs@@ -48,13 +48,24 @@ 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.-pub async fn approval_list_pending() -> anyhow::Result<Outcome<Vec<PendingApproval>>> {- tracing::debug!("[rpc:approval_list_pending] entry");+///+/// `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"+ );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 rows = match gate.list_pending() {+ let listed = match agent_id {+ Some(agent) => gate.list_pending_for_agent(Some(agent)),+ None => gate.list_pending(),+ };+ let rows = match listed {Ok(rows) => rows,Err(err) => {tracing::error!(error = %err, "[rpc:approval_list_pending] store error");@@ -188,14 +199,17 @@ 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.+/// unknown / already decided / belongs to a different session. With+/// `agent_id`, also errors when the request belongs to another agent.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(|| {@@ -205,7 +219,11 @@ pub async fn approval_decide();anyhow!("approval gate is not installed; supervised mode disabled")})?;- let decided = match gate.decide(request_id, decision) {+ 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 {Ok(row) => row,Err(err) => {tracing::error!(@@ -263,7 +281,17 @@ 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 {+ 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 {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 d300611c03..b040ecafc5 100644--- a/crates/openhuman-core/src/security/approval/schemas.rs+++ b/crates/openhuman-core/src/security/approval/schemas.rs@@ -54,7 +54,12 @@ pub fn schemas(function: &str) -> ControllerSchema {function: "list_pending",description:"List pending approval requests awaiting a user decision in the current session.",- inputs: vec![],+ 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,+ }],outputs: vec![FieldSchema {name: "pending",ty: TypeSchema::Array(Box::new(TypeSchema::Ref("PendingApproval"))),@@ -113,6 +118,13 @@ 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",@@ -167,9 +179,10 @@ 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 outcome = approval_rpc::approval_list_pending()+ let agent_id = read_optional_string(¶ms, "agent_id")?;+ let outcome = approval_rpc::approval_list_pending(agent_id.as_deref()).await.map_err(|e| e.to_string())?;to_json(outcome)@@ -205,9 +218,11 @@ fn handle_decide(params: Map<String, Value>) -> ControllerFuture {approve_once|approve_always_for_tool|approve_always_for_flow|deny, got '{decision_str}'")})?;- let outcome = approval_rpc::approval_decide(request_id.trim(), decision)- .await- .map_err(|e| e.to_string())?;+ 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())?;to_json(outcome)})}@@ -255,6 +270,17 @@ 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 8b1686ec95..c8942e90f0 100644--- a/crates/openhuman-core/src/security/approval/schemas_tests.rs+++ b/crates/openhuman-core/src/security/approval/schemas_tests.rs@@ -2,11 +2,13 @@ use super::*;use serde_json::json;#[test]-fn schemas_list_pending_has_no_inputs() {+fn schemas_list_pending_takes_only_an_optional_agent() {let s = schemas("list_pending");assert_eq!(s.namespace, "approval");assert_eq!(s.function, "list_pending");- assert!(s.inputs.is_empty());+ assert_eq!(s.inputs.len(), 1);+ assert_eq!(s.inputs[0].name, "agent_id");+ assert!(!s.inputs[0].required);}#[test]@@ -15,7 +17,11 @@ 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));+ assert!(s+ .inputs+ .iter()+ .all(|f| f.required == (f.name != "agent_id")));+ assert!(names.contains(&"agent_id"));}#[test]diff --git a/crates/openhuman-core/src/security/approval/store.rs b/crates/openhuman-core/src/security/approval/store.rsindex e952d5f6bb..81e467a169 100644--- a/crates/openhuman-core/src/security/approval/store.rs+++ b/crates/openhuman-core/src/security/approval/store.rs@@ -135,6 +135,10 @@ 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@@ -150,6 +154,12 @@ 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(())}@@ -192,10 +202,14 @@ 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 = config.workspace_dir.join("approval").join("approval.db");+ let db_path = db_path(config);tracing::trace!(path = %db_path.display(),@@ -248,8 +262,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)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",+ session_id, created_at, expires_at, source_context, tool_call_id, agent_id)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",params![pending.request_id,pending.tool_name,@@ -260,6 +274,7 @@ 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")?;@@ -300,7 +315,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+ session_id, created_at, expires_at, source_context, tool_call_id, agent_idFROM pending_approvalsWHERE decided_at IS NULLORDER BY created_at ASC",@@ -405,7 +420,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+ session_id, created_at, expires_at, source_context, tool_call_id, agent_idFROM pending_approvals WHERE request_id = ?1",).context("[approval::store] prepare select decided")?;@@ -575,7 +590,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+ session_id, created_at, expires_at, source_context, tool_call_id, agent_idFROM pending_approvalsWHERE decided_at IS NULLAND expires_at IS NOT NULL@@ -625,6 +640,7 @@ 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(),});}}@@ -699,6 +715,7 @@ 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.@@ -711,6 +728,7 @@ 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,})}@@ -720,6 +738,10 @@ 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 a5a2e2b7fa..0f423d9f0c 100644--- a/crates/openhuman-core/src/security/approval/store_documents.rs+++ b/crates/openhuman-core/src/security/approval/store_documents.rs@@ -110,6 +110,7 @@ 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),}}@@ -185,6 +186,7 @@ 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();@@ -270,6 +272,18 @@ 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 d1732b8493..e8b3758249 100644--- a/crates/openhuman-core/src/security/approval/store_documents_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_documents_tests.rs@@ -25,6 +25,7 @@ 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,}}@@ -372,3 +373,27 @@ 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 96f251e990..a81c6e3bb0 100644--- a/crates/openhuman-core/src/security/approval/store_persistence_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_persistence_tests.rs@@ -664,3 +664,84 @@ 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 8293a64bd4..e9194ccc5c 100644--- a/crates/openhuman-core/src/security/approval/store_tests.rs+++ b/crates/openhuman-core/src/security/approval/store_tests.rs@@ -49,6 +49,7 @@ 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 367617b5be..2bdc77a847 100644--- a/crates/openhuman-core/src/security/approval/types.rs+++ b/crates/openhuman-core/src/security/approval/types.rs@@ -42,6 +42,10 @@ 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 {@@ -63,6 +67,7 @@ impl PendingApproval {expires_at,source_context: None,tool_call_id: None,+ agent_id: None,}}@@ -74,6 +79,12 @@ 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 d6192174d2..08f5e26129 100644--- a/crates/openhuman-core/src/security/approval/types_tests.rs+++ b/crates/openhuman-core/src/security/approval/types_tests.rs@@ -142,6 +142,7 @@ 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 7b0c76d3a8..f2b4d52f49 100644--- a/crates/openhuman-core/src/security/live_policy.rs+++ b/crates/openhuman-core/src/security/live_policy.rs@@ -175,6 +175,21 @@ 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 b4cb45fd81..436cc9edbd 100644--- a/crates/openhuman-core/src/security/live_policy_tests.rs+++ b/crates/openhuman-core/src/security/live_policy_tests.rs@@ -178,3 +178,57 @@ 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 b6a443c49e..35e5594d66 100644--- a/crates/openhuman-core/src/skills/mod.rs+++ b/crates/openhuman-core/src/skills/mod.rs@@ -73,6 +73,8 @@ 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 d93834a525..c6c212ee53 100644--- a/crates/openhuman-core/src/skills/ops_create.rs+++ b/crates/openhuman-core/src/skills/ops_create.rs@@ -172,9 +172,8 @@ pub(crate) fn create_workflow_inner(let scope_root = match params.scope {WorkflowScope::User => {- let home =- home_dir.ok_or_else(|| "could not resolve user home directory".to_string())?;- home.join(".openhuman").join("workflows")+ crate::skills::write_root::user_workflow_root(workspace_dir, home_dir)+ .ok_or_else(|| "could not resolve user home directory".to_string())?}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 b3553f2a30..8a7cc4002c 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);+type MetadataCacheKey = (PathBuf, Option<PathBuf>, bool, Option<String>);static METADATA_CACHE: LazyLock<RwLock<HashMap<MetadataCacheKey, Vec<Workflow>>>> =LazyLock::new(|| RwLock::new(HashMap::new()));static METADATA_GENERATION: AtomicU64 = AtomicU64::new(0);@@ -83,7 +83,12 @@ 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);+ let key = (+ workspace_dir.to_path_buf(),+ home.clone(),+ trusted,+ crate::core::runtime::agent_scope::current_agent_id(),+ );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 647519880a..f9e8ddfeed 100644--- a/crates/openhuman-core/src/skills/ops_discover/scan.rs+++ b/crates/openhuman-core/src/skills/ops_discover/scan.rs@@ -81,6 +81,21 @@ 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 0de2363420..347e590cab 100644--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs@@ -271,10 +271,8 @@ pub(crate) fn install_validated_document(.map(|s| s.name).collect();- let skills_root = home- .ok_or_else(|| "write failed: unable to resolve home directory".to_string())?- .join(".openhuman")- .join("skills");+ let skills_root = crate::skills::write_root::user_skill_install_root(workspace_dir, home)+ .ok_or_else(|| "write failed: unable to resolve home directory".to_string())?;let target_file =match write_installed_document(&skills_root, &slug, &content).map_err(|e| e.to_string())? {diff --git a/crates/openhuman-core/src/skills/ops_install/uninstall.rs b/crates/openhuman-core/src/skills/ops_install/uninstall.rsindex d4239a9b4f..4416884cdf 100644--- a/crates/openhuman-core/src/skills/ops_install/uninstall.rs+++ b/crates/openhuman-core/src/skills/ops_install/uninstall.rs@@ -54,11 +54,17 @@ 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 = [- openhuman_dir.join("workflows"),- openhuman_dir.join("skills"),- home.join(".agents").join("skills"),- ];+ 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 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 b6394460fb..f7e75d3e7a 100644--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs@@ -543,10 +543,8 @@ impl Tool for BrowserTool {context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {if let Some(thread_id) = context.and_then(ToolRunContext::thread_id) {- let key = format!(- "{}:{thread_id}",- self.client.config().workspace_dir.display()- );+ let scope = crate::core::runtime::agent_scope_dir(self.client.config());+ let key = format!("{}:{thread_id}", scope.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 2a10850e9d..fca3451070 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,3 +437,46 @@ 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 50f7930dd1..a860256ce3 100644--- a/crates/openhuman-core/src/tools/orchestrator_tools_tests.rs+++ b/crates/openhuman-core/src/tools/orchestrator_tools_tests.rs@@ -31,6 +31,7 @@ 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 ced93a3c70..deb6aba4da 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`. |+| [`ops/state.rs`](./ops/state.rs) | `thread_sessions()`, `in_flight()`, `parallel_in_flight()`, keying helpers, `invalidate_thread_sessions`, `cancel_should_target`. Each table is a slot of the ambient agent context, so two embedded agents never share an entry; outside an agent context it is the process default. || [`ops/turn_guards.rs`](./ops/turn_guards.rs) | `run_turn_under_cancel_and_deadline`, the wall-clock backstop, Sentry suppression and timeout tagging. |-| [`ops/budget_correlation.rs`](./ops/budget_correlation.rs) | `THREAD_BUDGET_SIGNALS` and `classify_budget_correlation` for the empty-200-after-budget case. |+| [`ops/budget_correlation.rs`](./ops/budget_correlation.rs) | `thread_budget_signals()` and `classify_budget_correlation` for the empty-200-after-budget case. || [`ops/test_hooks.rs`](./ops/test_hooks.rs) | Debug/test hooks that force or block `run_chat_task`. || [`run_task.rs`](./run_task.rs) | `run_chat_task`: checkout, progress bridge, run, budget correlation on error, checkin. || [`session.rs`](./session.rs) | Session checkout and checkin, fingerprinting, `CheckoutPolicy`, target agent id, locale reply directive, per-turn provider and model routing. |@@ -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 6004d6b3f1..1479e9b50d 100644--- a/crates/openhuman-core/src/web_chat/event_bus.rs+++ b/crates/openhuman-core/src/web_chat/event_bus.rs@@ -618,6 +618,7 @@ 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!(@@ -650,6 +651,7 @@ 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 db165ab3fe..5dacc98e92 100644--- a/crates/openhuman-core/src/web_chat/event_bus_tests.rs+++ b/crates/openhuman-core/src/web_chat/event_bus_tests.rs@@ -443,6 +443,7 @@ 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;@@ -469,6 +470,7 @@ 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 1157ab33df..572e6e48d9 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;-#[cfg(test)]-pub(crate) use state::IN_FLIGHT;-pub(super) use state::THREAD_SESSIONS;+pub(super) use state::thread_sessions;pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};pub(crate) use state::{event_session_id_for, key_for};diff --git a/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs b/crates/openhuman-core/src/web_chat/ops/budget_correlation.rsindex c965fdf2e4..3de3895fa9 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,8 +40,11 @@ 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).-static THREAD_BUDGET_SIGNALS: Lazy<Mutex<HashMap<String, BudgetSignal>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+fn thread_budget_signals() -> Arc<ThreadBudgetSignals> {+ crate::core::runtime::current_slot::<ThreadBudgetSignals>()+}++type ThreadBudgetSignals = Mutex<HashMap<String, BudgetSignal>>;/// 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@@ -66,7 +69,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().await;+ let mut signals = thread_budget_signals().lock_owned().await;prune_stale_budget_signals(&mut signals);signals.insert(key_for(thread_id),@@ -80,7 +83,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().await;+ let mut signals = thread_budget_signals().lock_owned().await;signals.remove(&key_for(thread_id));}@@ -89,7 +92,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().await;+ let mut signals = thread_budget_signals().lock_owned().await;let key = key_for(thread_id);match signals.get(&key) {Some(sig)@@ -110,7 +113,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().await;+ let mut signals = thread_budget_signals().lock_owned().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 875361cd05..c2fc900dd7 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, key_for, IN_FLIGHT};+use super::state::{cancel_in_flight_gracefully, cancel_should_target, in_flight, key_for};/// 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().await;+ let mut in_flight = in_flight().lock_owned().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 IN_FLIGHT.lock().await.contains_key(map_key) {+ if super::state::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().await;+ let in_flight = in_flight().lock_owned().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().await;+ let in_flight = in_flight().lock_owned().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().await;+ let in_flight = in_flight().lock_owned().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 c6eab6c57c..3d126632d0 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, unscope, PARALLEL_IN_FLIGHT};+use super::state::{key_for, parallel_in_flight, unscope};use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@ -22,7 +22,7 @@ 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,11 +197,14 @@ pub(crate) async fn spawn_parallel_turn(}}- PARALLEL_IN_FLIGHT.lock().await.remove(&map_key_task);+ parallel_in_flight()+ .lock_owned()+ .await+ .remove(&map_key_task);},));- PARALLEL_IN_FLIGHT.lock().await.insert(+ parallel_in_flight().lock_owned().await.insert(map_key,ParallelEntry {thread_id: key_for(thread_id),@@ -217,7 +220,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().await;+ let mut parallel = parallel_in_flight().lock_owned().await;let request_ids: Vec<String> = parallel.iter().filter(|(_, entry)| entry.thread_id == scoped_thread)@@ -251,7 +254,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().await;+ let mut parallel = parallel_in_flight().lock_owned().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 f5ce3088a8..bf221dd111 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, key_for, IN_FLIGHT};+use super::state::{cancel_in_flight_gracefully, in_flight, key_for};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().await;+ let in_flight = in_flight().lock_owned().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().await;+ let mut in_flight = in_flight().lock_owned().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().await;+ let mut in_flight = in_flight().lock_owned().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().await;+ let mut in_flight = in_flight().lock_owned().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().await;+ let mut in_flight = in_flight().lock_owned().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 445e96e1b0..5013f782e8 100644--- a/crates/openhuman-core/src/web_chat/ops/state.rs+++ b/crates/openhuman-core/src/web_chat/ops/state.rs@@ -3,26 +3,35 @@//! 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};-pub(crate) static THREAD_SESSIONS: Lazy<Mutex<HashMap<String, SessionEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+type ThreadSessions = Mutex<HashMap<String, SessionEntry>>;+type InFlight = Mutex<HashMap<String, InFlightEntry>>;+type ParallelInFlight = Mutex<HashMap<String, ParallelEntry>>;-pub(crate) static IN_FLIGHT: Lazy<Mutex<HashMap<String, InFlightEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// The current agent context's per-thread session cache.+pub(crate) fn thread_sessions() -> Arc<ThreadSessions> {+ crate::core::runtime::current_slot::<ThreadSessions>()+}++/// The current agent context's primary in-flight turns, keyed by thread.+pub(crate) fn in_flight() -> Arc<InFlight> {+ crate::core::runtime::current_slot::<InFlight>()+}/// Parallel (forked) turns, keyed by `request_id`. A separate lane from-/// `IN_FLIGHT` (which holds one primary, interrupt-able turn per thread) so any-/// number of concurrent `QueueMode::Parallel` turns can run on the same thread-/// without touching interrupt/steer/queue semantics. See `QueueMode::Parallel`.-pub(crate) static PARALLEL_IN_FLIGHT: Lazy<Mutex<HashMap<String, ParallelEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// [`in_flight`] (which holds one primary, interrupt-able turn per thread) so+/// any number of concurrent `QueueMode::Parallel` turns can run on the same+/// thread without touching interrupt/steer/queue semantics.+pub(crate) fn parallel_in_flight() -> Arc<ParallelInFlight> {+ crate::core::runtime::current_slot::<ParallelInFlight>()+}/// The map key for `thread_id` in the calling scope.///@@ -114,12 +123,11 @@ 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 slot goes: another agent that- // picked the same thread id keeps its live session. Outside an agent scope- // (a host-level edit or delete of the thread) every scope's slot goes.+ // Under an embedded agent only that agent's entry goes. Outside an agent+ // scope every entry for the thread in the current table goes.let active_agent = crate::core::runtime::CoreContext::current().and_then(|context| context.session_agent().map(str::to_owned));- let mut sessions = THREAD_SESSIONS.lock().await;+ let mut sessions = thread_sessions().lock_owned().await;let keys_to_remove: Vec<String> = match active_agent {Some(_) => {let key = key_for(thread_id);@@ -148,7 +156,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().await;+ let guard = in_flight().lock_owned().await;guard.iter().map(|(k, v)| (k.clone(), v.request_id.clone()))@@ -164,7 +172,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().await;+ let guard = in_flight().lock_owned().await;match guard.get(&key_for(thread_id)) {Some(entry) => entry.run_queue.drain(lane).await,None => Vec::new(),@@ -174,7 +182,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().await;+ let guard = parallel_in_flight().lock_owned().await;guard.iter().map(|(request_id, entry)| (request_id.clone(), entry.thread_id.clone()))@@ -200,3 +208,7 @@ 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 bed138fb86..858b4aec69 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().await;+ let signals = thread_budget_signals().lock_owned().await;assert!(!signals.contains_key(abandoned),"stale entry should be pruned"@@ -110,3 +110,40 @@ 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 16ca30789d..7c594907e2 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().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().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().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().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().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().await;match sessions.entry(super::ops::key_for(thread_id)) {std::collections::hash_map::Entry::Occupied(_) => {log::info!(@@ -552,6 +552,10 @@ 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 0e9bb9adc0..b897a0081f 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;-fn test_config(tmp: &tempfile::TempDir) -> Config {+pub(super) fn test_config(tmp: &tempfile::TempDir) -> Config {let config = Config {workspace_dir: tmp.path().join("workspace"),action_dir: tmp.path().join("workspace"),@@ -32,7 +32,7 @@ fn test_config(tmp: &tempfile::TempDir) -> Config {config}-fn unique_thread(tag: &str) -> String {+pub(super) fn unique_thread(tag: &str) -> String {format!("thread-checkout-{tag}-{}", uuid::Uuid::new_v4())}@@ -86,7 +86,7 @@ fn prose(history: &[TranscriptEntry]) -> Vec<String> {.collect()}-fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {+pub(super) fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {let mut host = OpenHumanSessionHost::from_config_for_agent(config, "orchestrator").unwrap();host.seed_resume_from_messages(vec![@@ -100,7 +100,10 @@ fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {}async fn evict(thread_id: &str) {- THREAD_SESSIONS.lock().await.remove(&key_for(thread_id));+ thread_sessions()+ .lock_owned()+ .await+ .remove(&key_for(thread_id));}#[tokio::test]@@ -149,7 +152,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)));@@ -173,7 +176,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)));@@ -259,7 +262,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)));@@ -548,67 +551,6 @@ 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.@@ -695,7 +637,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)),@@ -709,7 +651,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 6c8a95250e..fe2d4f256a 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().await;+ let held = crate::web_chat::ops::in_flight().lock_owned().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 e5566d8c6b..5ac88622a0 100644--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@ -250,8 +250,9 @@ 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- session_raw/ transcripts (thread + agent)- agents/<id>/skills/ each agent's skills root+ agents/<id>/session_raw/ each agent's transcripts+ agents/<id>/skills/, workflows/ each agent's skills roots+ agents/<id>/cron/jobs.db each agent's cron jobsagents/<id>/action/ default action_dir per agent```@@ -259,33 +260,74 @@ 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.-### Settings that are still runtime-wide--Every agent reads these from the runtime's boot config today. Each is a-candidate follow-up in the core.--- `autonomy.auto_approve` and `auto_approve_all`, and the memory guard's- autonomy tier, come from the boot config (`security::live_policy`). Path- and command policy do use the agent's own tier.-- The approval gate is on or off for the whole process, and parked approvals- are not labelled with an agent id. For an agent that never waits on- approval, use `Access::full()`, whose `TrustedAutomation` origin the gate- honours per turn.-- The sub-agent catalogue is runtime-wide (built-ins plus- `<workspace>/agents/*.toml`). Embedded agents cannot be `delegate_*`- targets of each other. Do not reuse built-in ids such as `orchestrator` or- `summarizer` for your agents.-- Sub-agents an agent spawns, and the experience store, read the runtime's- on-disk config rather than the agent's overlay.-- Sub-agent run-ledger rows, cron jobs and the cost log stay in the- workspace even with a host session store.-- Agents on one workspace share the dynamic `mcp_registry_*` MCP registry.- Servers declared through `AgentSpec::mcp` are per agent. The host-seeded- documentation server is visible to every agent.-- `install_skill` and `create_skill` still write to `~/.openhuman`. With- `include_user_skills(false)` (the default) an agent does not discover the- operator's skills, but an install it performs lands there.-- One API key (or session) is shared by every agent.+### Per agent++Every agent on a runtime is isolated from its siblings on the same workspace:++- Policy and approvals: the autonomy tier, `auto_approve`, `auto_approve_all`+ and the approval gate switch come from the agent's `Access`+ (`auto_approve`, `auto_approve_all`, `approval_gate`). Parked approvals+ carry the agent id; `Agent::approvals()` lists and decides only that+ agent's requests, and a chat reply routes by agent and thread.+- Sub-agents: `AgentSpec::subagents` declares workers only that agent can+ delegate to. Built-in ids (`orchestrator`, `planner`, …) are reserved.+ Detached sub-agents keep the agent's provider route.+- MCP: each agent has its own MCP host and dynamic registry under+ `<workspace>/agents/<id>/`, plus the servers its spec declares.+- Transcripts: `<workspace>/agents/<id>/session_raw/`. Conversations written+ before this layout into `<workspace>/session_raw/` stay readable and are+ copied into the agent's directory when resumed; the shared file is never+ changed.+- Skills: `install_skill` and `create_skill` write user-scope bundles into+ `<workspace>/agents/<id>/skills/` and `workflows/`, which only that agent+ discovers. The operator's `~/.openhuman` is untouched.+- Cron: jobs an agent creates live in `<workspace>/agents/<id>/cron/jobs.db`+ and run under that agent's context, provider and policy.+- Memory sources are synced per live agent, under its own context.+- Turn tables, plan mode, reasoning effort, turn citations, budget signals,+ the request journal, sub-agent dedupe and the `run_workflow` guard live in+ the agent's context, so two agents can use the same thread or session id+ at the same time.++### Lifecycle++`RuntimeBuilder::max_agents` caps live agents (default+`DEFAULT_MAX_AGENTS`, 1024); `Runtime::agent` returns+`AgentError::AgentLimit` past it. `Runtime::remove_agent(id)` denies the+agent's parked approvals (resolution `agent_removed`), refuses new turns and+ends the ones in flight with `CoreError::AgentRemoved` (waiting up to ten+seconds for them to unwind), then drops its state slots and MCP host and+deregisters its context, which leaves its cron jobs dormant. The id is+reusable once it returns; `.purge()` also deletes the agent's home.+Dropping the last handle to an agent tears it down the same way with+resolution `agent_dropped`. Cancellation is cooperative: a tool already+executing, or a sub-agent the turn detached, may finish after removal.++### Still process-owned++- The event bus, keyring and credential store, and the API key (or+ session): one per runtime, shared by every agent.+- 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.## Authentication and the backenddiff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 71f1370c1c..9f8cd616c4 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -7,6 +7,9 @@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};@@ -22,6 +25,10 @@ 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.@@ -160,7 +167,6 @@ 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@@ -171,6 +177,8 @@ 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) => {@@ -188,23 +196,43 @@ 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: config.clone(),+ config: context_config,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={}",+ user_skills={} tier={:?} approval_gate={}",config.action_dir.display(),provider.is_routed(),access.turn_origin().is_some(),- parts.include_user_skills+ parts.include_user_skills,+ config.autonomy.level,+ access.approval_gate_enabled());Ok(AgentInner {@@ -220,10 +248,56 @@ 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 af41498775..b8c000feef 100644--- a/crates/openhuman-embed/src/agent/build_tests.rs+++ b/crates/openhuman-embed/src/agent/build_tests.rs@@ -23,3 +23,92 @@ 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 fb3f7442a6..dd820d6f83 100644--- a/crates/openhuman-embed/src/agent/definition.rs+++ b/crates/openhuman-embed/src/agent/definition.rs@@ -230,6 +230,19 @@ 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 cae19b97ac..2f03d49949 100644--- a/crates/openhuman-embed/src/agent/layout.rs+++ b/crates/openhuman-embed/src/agent/layout.rs@@ -8,10 +8,17 @@//! config.toml, auth-profiles.json, core.token runtime-wide//! workspace///! session_db/sessions.db runtime-wide run ledger-//! agents/<id>/{SOUL.md, skills/} the agent's home-//! session_raw/<ts>_<id>.jsonl its transcripts+//! 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>/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};@@ -36,7 +43,11 @@ impl AgentLayout {Self {home: workspace_dir.join("agents").join(id),skills: workspace_dir.join("agents").join(id).join("skills"),- transcripts: workspace_dir.join("session_raw"),+ transcripts: openhuman_core::agent::session_store::agent_transcript_root(+ workspace_dir,+ id,+ )+ .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 bdd50d425e..2534ecb790 100644--- a/crates/openhuman-embed/src/agent/layout_tests.rs+++ b/crates/openhuman-embed/src/agent/layout_tests.rs@@ -6,7 +6,10 @@ 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/session_raw"));+ assert_eq!(+ layout.transcripts,+ Path::new("/r/workspace/agents/alpha/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 dd79db6077..94ac25e200 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -14,7 +14,10 @@//! 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;@@ -74,6 +77,23 @@ 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@@ -97,11 +117,58 @@ pub(crate) struct AgentInner {/// The agent's own in-process tools, rebuilt per turn. See/// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,+ pub(crate) lifecycle: lifecycle::Lifecycle,/// Built from [`ToolScopeSpec::HostOnly`]: every turn's session is built/// from the host tools alone.pub(crate) host_only: bool,}+impl AgentInner {+ /// Releases what the core keeps for this agent: parked approvals are+ /// denied with `resolution`, its state slots and MCP host are dropped,+ /// and its context leaves the registry. Runs once.+ pub(crate) fn teardown(&self, resolution: &str) {+ if !self.lifecycle.begin_teardown() {+ return;+ }+ self.deny_approvals(resolution);+ self.ctx.agent_state().clear();+ if openhuman_core::mcp::host::take_agent_host(&self.config.workspace_dir, &self.id)+ .is_some()+ {+ log::debug!(+ "[embed][agent] teardown id={} evicted its MCP host",+ self.id+ );+ }+ openhuman_core::core::runtime::AgentContextRegistry::deregister(&self.id, &self.ctx);+ log::debug!("[embed][agent] teardown complete id={}", self.id);+ }++ /// Denies every approval this agent has parked, with `resolution`.+ pub(crate) fn deny_approvals(&self, resolution: &str) {+ let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() else {+ return;+ };+ match gate.deny_all_for_agent(&self.id, resolution) {+ Ok(denied) => log::debug!(+ "[embed][agent] id={} denied_approvals={denied} resolution={resolution}",+ self.id+ ),+ Err(error) => log::warn!(+ "[embed][agent] id={} could not deny approvals: {error}",+ self.id+ ),+ }+ }+}++impl Drop for AgentInner {+ fn drop(&mut self) {+ self.teardown("agent_dropped");+ }+}+/// A handle to one agent on a runtime.////// Cheap to clone; every clone drives the same agent. The id is released for@@ -152,6 +219,12 @@ 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@@ -173,9 +246,9 @@ impl Agent {&self.inner.layout.skills}- /// 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.+ /// `<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.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 7c2db70fa3..edc1d3c512 100644--- a/crates/openhuman-embed/src/agent/spec.rs+++ b/crates/openhuman-embed/src/agent/spec.rs@@ -52,6 +52,7 @@ 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@@ -101,9 +102,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. Avoid the built-in ids (`orchestrator`,- /// `summarizer`, …): the runtime-wide delegation catalog resolves those- /// to the shipped definitions.+ /// directories and transcripts. The built-in ids (`orchestrator`,+ /// `summarizer`, …) are reserved for the shipped definitions and refused+ /// with [`AgentError::ReservedId`](crate::AgentError::ReservedId).pub fn new(id: impl Into<String>) -> Self {Self {id: id.into(),@@ -125,6 +126,7 @@ impl AgentSpec {config_fn: None,host_tools: None,memory: None,+ subagents: Vec::new(),}}@@ -254,6 +256,21 @@ 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@@ -359,6 +376,7 @@ impl AgentSpec {config_fn: self.config_fn,host_tools: self.host_tools,memory: self.memory,+ subagents: self.subagents,}}}@@ -384,6 +402,7 @@ 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 7aa15f9fc7..ad42eb1e55 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -106,6 +106,16 @@ 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 {@@ -156,7 +166,8 @@ impl CoreError {| CoreError::Encode { method, .. }| CoreError::Decode { method, .. }| CoreError::InsecureRoute { method, .. }- | CoreError::InvalidRoute { method } => method,+ | CoreError::InvalidRoute { method }+ | CoreError::AgentRemoved { method, .. } => method,}}diff --git a/crates/openhuman-embed/src/harness/access.rs b/crates/openhuman-embed/src/harness/access.rsindex 5141b68b11..dd97707de4 100644--- a/crates/openhuman-embed/src/harness/access.rs+++ b/crates/openhuman-embed/src/harness/access.rs@@ -33,6 +33,8 @@ 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 {@@ -55,6 +57,8 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: true,+ auto_approve: None,+ auto_approve_all: None,}}@@ -70,6 +74,8 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: true,+ auto_approve: None,+ auto_approve_all: None,}}@@ -94,6 +100,8 @@ impl Access {trusted_roots: Vec::new(),allow_tool_install: false,approval_gate: false,+ auto_approve: None,+ auto_approve_all: None,}}@@ -120,6 +128,36 @@ 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@@ -164,6 +202,12 @@ 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 a8ed8cdeb4..f6071a5e7c 100644--- a/crates/openhuman-embed/src/harness/access_tests.rs+++ b/crates/openhuman-embed/src/harness/access_tests.rs@@ -141,6 +141,36 @@ 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 0eefb76112..09df94e90d 100644--- a/crates/openhuman-embed/src/harness/error.rs+++ b/crates/openhuman-embed/src/harness/error.rs@@ -88,9 +88,12 @@ 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(_) => {- Self::Invalid(err_text(&err))- }+ A::DuplicateId(_)+ | A::InvalidId { .. }+ | A::WidensRuntime(_)+ | A::ReservedId(_)+ | A::AgentLimit { .. }+ | A::UnknownId(_) => 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 f0f4b68e2e..87de273d79 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, MemoryBinding, SandboxModeSpec,- ToolScopeSpec,+ Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals,+ ApprovalsError, MemoryBinding, PendingApproval, SandboxModeSpec, ToolScopeSpec,};pub use auth::{Auth, AuthState, Session};pub use config::{Config, RuntimeFlags};@@ -144,10 +144,13 @@ 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, Runtime, RuntimeBuilder, RuntimeError};+pub use runtime::{+ run_from_args, ApiKey, ConfigSource, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError,+};/// The types the [`RuntimeBuilder`] seam options take: controller/// extensions, embedder hooks, the CLI server launcher and the live securitydiff --git a/crates/openhuman-embed/src/runtime/README.md b/crates/openhuman-embed/src/runtime/README.mdindex 2fc29e9885..edf3205eb8 100644--- a/crates/openhuman-embed/src/runtime/README.md+++ b/crates/openhuman-embed/src/runtime/README.md@@ -98,12 +98,11 @@ 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, and its narrowed-`DomainSet` and `ToolGroups`. Some settings, such as-`autonomy.auto_approve` and the memory guard's autonomy tier, are still read-from the runtime's boot config by every agent; check the crate README's list-of settings that are still runtime-wide before assuming an agent-level-override reaches them.+prompt, tool scope, sandbox mode), its skills root, its narrowed+`DomainSet` and `ToolGroups`, its approval settings and parked approvals,+its sub-agents, its MCP host, its cron jobs and its per-turn state. The+crate README's "Still process-owned" list names what agents share, and its+"Lifecycle" section covers `max_agents` and `Runtime::remove_agent`.## Boundariesdiff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rsindex b15bd509e3..6d041e2717 100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@ -257,6 +257,7 @@ 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 e8d2c34d86..cf204415ce 100644--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@ -86,8 +86,13 @@ 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()@@ -122,6 +127,7 @@ impl RuntimeBuilder {memory_engine: None,session_store: None,seams: HostSeams::default(),+ max_agents: DEFAULT_MAX_AGENTS,}}@@ -168,6 +174,15 @@ 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 c3b8ed7dcc..8ba949bf94 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -44,11 +44,10 @@//! `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`].+//! `DomainSet` and [`ToolGroups`], its approval settings, sub-agents, MCP+//! host, cron jobs and per-turn state.//!-//! 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.+//! The crate README's "Still process-owned" list names what agents share.//!//! # One runtime per process//!@@ -70,6 +69,7 @@mod api_key;mod build;pub(crate) mod builder;+mod lifecycle;mod presets;mod run;mod seams;@@ -77,6 +77,7 @@ 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;@@ -234,6 +235,7 @@ pub struct Runtime {provider: Provider,access: Access,agents: Mutex<HashMap<String, Weak<AgentInner>>>,+ max_agents: usize,}impl Runtime {@@ -274,6 +276,15 @@ 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);@@ -423,6 +434,7 @@ impl Runtime {tool_groups: ToolGroups,provider: Provider,access: Access,+ max_agents: usize,) -> Self {Self {id: uuid::Uuid::new_v4().to_string(),@@ -441,6 +453,7 @@ 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 c4137c248c..0f453a9b69 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -572,6 +572,7 @@ 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}");});@@ -770,7 +771,10 @@ async fn dispatch(.map(|outcome| (outcome.value, Some(report))).map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))});- runtime.run_in(ctx, turn).await+ agent+ .lifecycle+ .admit(&agent.id, AGENT_CHAT, runtime.run_in(ctx, turn))+ .await}}}diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rsindex c127ce2d86..4e7ceede55 100644--- a/crates/openhuman-embed/tests/common/mod.rs+++ b/crates/openhuman-embed/tests/common/mod.rs@@ -177,3 +177,45 @@ 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 de78933097..dcb19c5f48 100644--- a/crates/openhuman-embed/tests/public_api.rs+++ b/crates/openhuman-embed/tests/public_api.rs@@ -1,10 +1,11 @@use std::sync::Arc;use openhuman_embed::{- Access, Agent, AgentDefinitionSpec, AgentSpec, AgentTurnOrigin, ApiKey, Core, CoreBuilder,- CoreRuntime, DomainSet, GroupMode, Harness, HostKind, Provider, Runtime, RuntimeBuilder,- RuntimeConfig, SandboxModeSpec, ServiceSet, ToolGroups, ToolScopeSpec, TrustedAccess,- TrustedAutomationSource, Workspace,+ 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,};#[test]@@ -27,6 +28,23 @@ 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;@@ -41,9 +59,16 @@ 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");+ .backend_url("https://backend.example")+ .max_agents(DEFAULT_MAX_AGENTS);let _ = AgentSpec::new("public-api").system_prompt("You are a test.").definition(@@ -51,7 +76,13 @@ fn exposes_the_host_facing_embedding_contract() {.tools(ToolScopeSpec::Named(vec!["read_file".into()])).sandbox(SandboxModeSpec::ReadOnly),)- .access(Access::readonly())+ .subagents([("public-api-helper", AgentDefinitionSpec::new())])+ .access(+ Access::readonly()+ .auto_approve(["read_file"])+ .auto_approve_all(false)+ .approval_gate(true),+ ).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 1e81eb4080..7cb49093db 100644--- a/crates/openhuman-embed/tests/runtime_agents.rs+++ b/crates/openhuman-embed/tests/runtime_agents.rs@@ -335,7 +335,10 @@ 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("session_raw"));+ assert_eq!(+ alpha.transcripts_dir(),+ workspace_dir.join("agents/alpha/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());@@ -396,12 +399,20 @@ 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 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();+ // 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"+ );// 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@@ -409,7 +420,9 @@ 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_id, session_id) in [("alpha", &a1.session_id), ("beta", &b0.session_id)] {+ for (agent, session_id) in [(&alpha, &a1.session_id), (&beta, &b0.session_id)] {+ let agent_id = agent.id();+ let transcripts = listing(agent.transcripts_dir());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 fbc21b5d21..0ef4b84e6a 100644--- a/crates/openhuman-rpc/src/server/socketio.rs+++ b/crates/openhuman-rpc/src/server/socketio.rs@@ -997,6 +997,7 @@ 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 3a2b39636c..5d0948a03b 100644--- a/gitbooks/features/integrations/mcp-and-skills.md+++ b/gitbooks/features/integrations/mcp-and-skills.md@@ -28,7 +28,9 @@ 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.-- **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.+- **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.- **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 6a7549963d..e75700a10a 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", 1465],+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1466],// 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", 1309],- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1149],+ ["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/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", 1003],+ ["crates/openhuman-core/src/core/events_tests.rs", 997],["crates/openhuman-core/src/core/observability.rs", 3502],];const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);