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
chore: files changed crates/openhuman-core/src/agent/multimodal.rs,crates/openhuman-core/src/agent/o
Steven Enamakelda7844fd5940
diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rsindex 059e55b587..5e5b6061d9 100644--- a/crates/openhuman-core/src/agent/multimodal.rs+++ b/crates/openhuman-core/src/agent/multimodal.rs@@ -4,6 +4,7 @@//! the acting workspace and provider bytes are prepared only on request copies.//! The older stash remains readable so existing conversations can resume.+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::path::PathBuf;use std::sync::OnceLock;@@ -125,7 +126,7 @@ impl TextExtractor for DocumentsTextExtractor {use crate::modules::documents;match tokio::time::timeout(PDF_EXTRACTION_TIMEOUT, async {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).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/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rsindex 84848528ef..f2bf77f9ab 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs@@ -10,6 +10,7 @@//! Use it for non-trivial sub-tasks that benefit from a self-review/revision//! loop; use `spawn_subagent` for a single focused hand-off.+use crate::core::runtime::DispatchCtx;use crate::agent::harness::host_definition::AgentDefinitionRegistry;use crate::agent::orchestration::delegation::run_subagent_delegation_with_parent_context;use async_trait::async_trait;@@ -228,7 +229,7 @@ impl DelegateGraphTool {}};- let config = match crate::config::ops::load_current_or_init().await {+ let config = match crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await {Ok(cfg) => Arc::new(cfg),Err(e) => {return Ok(ToolResult::error(format!(diff --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 49ca90f001..666b1201ad 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@@ -1,6 +1,7 @@//! Public entry points (`start`/`stop`/`resume`) and the spawned engine loop//! that drives a run's phase DAG to completion.+use crate::core::runtime::DispatchCtx;use anyhow::{anyhow, Context, Result};use serde_json::Value;use std::sync::Arc;@@ -68,7 +69,7 @@ pub async fn start_workflow_run(// Inherit-only: `None` leaves the loop unlabelled and failing closed.let inherited_origin = crate::agent::turn_origin::capture();crate::core::runtime::spawn_scoped(async move {- match crate::config::ops::load_current_or_init().await {+ match crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await {Ok(task_config) => {crate::agent::turn_origin::with_inherited_origin(inherited_origin,@@ -207,7 +208,7 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu// loop runs on a fresh task, which would otherwise drop the caller's label.let inherited_origin = crate::agent::turn_origin::capture();crate::core::runtime::spawn_scoped(async move {- match crate::config::ops::load_current_or_init().await {+ match crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await {Ok(task_config) => {crate::agent::turn_origin::with_inherited_origin(inherited_origin,diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rsindex e43f2ca88b..f1a70a0876 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -3,6 +3,7 @@//! revokes between turns, and adopting the integration actions the tinyagents//! session restored for a resumed thread.+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use tinyagents_runtime::ToolSnapshot;@@ -361,7 +362,7 @@ impl OpenHumanTurnPrelude {}let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::ops::load_current_or_init()+ None => crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.ok().map(Arc::new),@@ -399,7 +400,7 @@ impl OpenHumanTurnPrelude {let skills_changed = self.drain_host_events();let config = match self.runtime_config.clone() {Some(config) => Some(config),- None => crate::config::ops::load_current_or_init()+ None => crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.ok().map(Arc::new),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 0f2aca7794..e591893a5a 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@@ -15,6 +15,7 @@//! The committed turn is also published as//! `DomainEvent::ConversationTurnCommitted` for observers.+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use chrono::Utc;@@ -76,7 +77,7 @@ impl OpenHumanTurnPrelude {if let Some(config) = &self.runtime_config {return Some(config.clone());}- crate::config::rpc::load_config_for_workspace_with_timeout(&self.workspace_dir)+ crate::config::rpc::load_config_for_workspace_with_timeout(&DispatchCtx::ambient(), &self.workspace_dir).await.map(Arc::new).map_err(|error| {diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rsindex b9f5873748..60e88d6669 100644--- a/crates/openhuman-core/src/agent/session_import/live.rs+++ b/crates/openhuman-core/src/agent/session_import/live.rs@@ -7,6 +7,7 @@//! key-value store, registered on each turn's `RunContext.stores` under//! [`TINYAGENTS_SESSION_KV_STORE`].+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use tinyagents_harness::store::Store;@@ -26,7 +27,7 @@ pub async fn session_kv_store() -> Option<Arc<dyn Store>> {log::debug!("[session-store] registering the host session store's kv on RunContext.stores");return Some(stores.kv);}- let cfg = match crate::config::ops::load_current_or_init().await {+ let cfg = match crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).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/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 24c6d82ed9..dce7ef848d 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -6,6 +6,7 @@//! calls and tool execution until the model returns without further tool calls//! (or the iteration budget is exhausted).+use crate::core::runtime::DispatchCtx;use std::collections::HashSet;use std::time::Instant;@@ -281,7 +282,7 @@ pub(crate) async fn run_subagent_direct(// 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())+ let loaded_config: LoadedConfig = Box::pin(crate::config::ops::load_current_or_init(&DispatchCtx::ambient())).await.map(std::sync::Arc::new).map_err(|e| e.to_string());diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rsindex b8b815a0f1..efd59bf732 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs@@ -75,6 +75,7 @@//! permission returns [`GateDecision::Deny`], including an unrecognised tool//! name.+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::sync::{Arc, Mutex};@@ -413,7 +414,7 @@ impl OpenHumanSecurityGate {let policy = self.effective_policy();#[cfg(feature = "modules")]let desktop_approval_disabled = match self.resolve_tool(&call.tool_name) {- Some(tool) => crate::desktop::control::approvals_disabled_for(tool).await,+ Some(tool) => crate::desktop::control::approvals_disabled_for(&DispatchCtx::ambient(), tool).await,None => false,};#[cfg(not(feature = "modules"))]diff --git a/crates/openhuman-core/src/agent/tinyagents/journal.rs b/crates/openhuman-core/src/agent/tinyagents/journal.rsindex b8e69ac15a..0a957aa862 100644--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs@@ -43,6 +43,7 @@//!//! [`EventSink::with_stream_id`]: tinyagents_harness::events::EventSink::with_stream_id+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::path::PathBuf;use std::sync::{Arc, Mutex};@@ -95,7 +96,7 @@ pub(crate) fn take_request_journal_run(request_id: &str) -> Option<String> {/// belong to (the storage backend is resolved from it). Async because the/// config load is async; errors are surfaced so callers can log-and-skip.async fn resolve_workspace() -> anyhow::Result<PathBuf> {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.map_err(|e| anyhow::anyhow!("[journal] load config for workspace: {e}"))?;Ok(config.workspace_dir)diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rsindex a6e7f8a8e1..70c19c17c7 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs@@ -1,6 +1,7 @@//! [`ApprovalSecurityMiddleware`]: route external-effect tool calls through//! OpenHuman's human-in-the-loop approval gate at the tool boundary.+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use async_trait::async_trait;@@ -83,7 +84,7 @@ impl ApprovalSecurityMiddleware {.flat_map(|set| set.iter()).find(|tool| tool.name() == name){- Some(tool) => crate::desktop::control::approvals_disabled_for(tool.as_ref()).await,+ Some(tool) => crate::desktop::control::approvals_disabled_for(&DispatchCtx::ambient(), tool.as_ref()).await,None => false,};#[cfg(not(feature = "modules"))]diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rsindex 8f916d8e32..3e39880ae2 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs@@ -332,7 +332,7 @@ impl ToolMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>// level), mirroring the engine order in `agent_tool_exec`.#[cfg(feature = "modules")]let desktop_approval_disabled = match self.resolve_tool(&call.name) {- Some(tool) => crate::desktop::control::approvals_disabled_for(tool.as_ref()).await,+ Some(tool) => crate::desktop::control::approvals_disabled_for(&ctx, tool.as_ref()).await,None => false,};#[cfg(not(feature = "modules"))]diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rsindex 2821990ef8..c498733179 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs@@ -20,6 +20,7 @@//! `agent_id == "orchestrator"`); every other agent's results are compacted//! without a summary.+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use anyhow::{anyhow, Result};@@ -115,7 +116,7 @@ impl HarnessPayloadSummarizer<OpenHumanRunContext> for SubagentPayloadSummarizerOk(Box::new(move |request: GenerateRequest| {Box::pin(async move {- let config_loaded = crate::config::ops::load_current_or_init().await;+ let config_loaded = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await;let (source, model) = subagent_host::resolve_subagent_source(&definition.model,&definition.id,diff --git a/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs b/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rsindex f491562c23..0d751af63e 100644--- a/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs+++ b/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs@@ -222,7 +222,7 @@ fn replay_schema(function: &str) -> ControllerSchema {/// Resolve the configured internal workspace whose `tinyagents_store/` holds the/// journal + status stores.async fn configured_workspace() -> Result<std::path::PathBuf, String> {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.map_err(|e| format!("failed to load config: {e}"))?;Ok(config.workspace_dir)diff --git a/crates/openhuman-core/src/agent/tools/todo.rs b/crates/openhuman-core/src/agent/tools/todo.rsindex 93e53bea7e..dd85893fab 100644--- a/crates/openhuman-core/src/agent/tools/todo.rs+++ b/crates/openhuman-core/src/agent/tools/todo.rs@@ -17,6 +17,7 @@//! (see [`current_scope`] / [`legacy_session_key`]) so an in-flight list isn't//! dropped by the rekey.+use crate::core::runtime::DispatchCtx;use crate::agent::harness::fork_context::ParentExecutionContext;use crate::agent::todos::ops::{self, TodoScope};use async_trait::async_trait;@@ -59,7 +60,7 @@ impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Tlet context = ToolExecutionContext::from_run_context(parent, call_id);let workspace_dir = match parent.data.parent.as_ref() {Some(parent_ctx) => parent_ctx.workspace_dir.clone(),- None => crate::config::ops::load_current_or_init()+ None => crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).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 05bbad5935..fea71562fe 100644--- a/crates/openhuman-core/src/agent/triage/escalation.rs+++ b/crates/openhuman-core/src/agent/triage/escalation.rs@@ -16,6 +16,7 @@//! carried explicitly into [`run_subagent`] so it can inherit the provider//! and tools.+use crate::core::runtime::DispatchCtx;use anyhow::{anyhow, Context};use crate::agent::harness::fork_context::ParentExecutionContext;@@ -243,7 +244,7 @@ async fn dispatch_target_agent(agent_id: &str, prompt: &str) -> anyhow::Result<S));}- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.context("loading config for sub-agent dispatch")?;diff --git a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs b/crates/openhuman-core/src/agent/triage/evaluator/chain.rsindex 08f116b842..0520594e22 100644--- a/crates/openhuman-core/src/agent/triage/evaluator/chain.rs+++ b/crates/openhuman-core/src/agent/triage/evaluator/chain.rs@@ -1,5 +1,6 @@//! The tiered cloud → retry → local fallback orchestration.+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::future::Future;use std::sync::{Mutex, OnceLock};@@ -76,7 +77,7 @@ fn retry_state() -> &'static RetryState {/// 5. On local failure, return `TriageOutcome::Deferred` so the/// caller can retry when a local arm is available.pub async fn run_triage(envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutcome> {- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.context("loading config for triage turn")?;let cloud = resolve_provider_with_config(&config)diff --git a/crates/openhuman-core/src/channels/runtime/session_tests.rs b/crates/openhuman-core/src/channels/runtime/session_tests.rsindex 7a26ca9299..ca2f5ab118 100644--- a/crates/openhuman-core/src/channels/runtime/session_tests.rs+++ b/crates/openhuman-core/src/channels/runtime/session_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::Arc;@@ -86,7 +87,7 @@ async fn clear_session_invalidates_old_channels_and_opens_a_fresh_generation() {};let _signed_out = crate::cron::scheduler_gate::SignedOutTestGuard::set(false);let old_session = channel_session();- crate::security::credentials::ops::clear_session(&config)+ crate::security::credentials::ops::clear_session(&DispatchCtx::process_default(), &config).await.unwrap();assert!(old_session.is_cancelled());diff --git a/crates/openhuman-core/src/config/ops/loader_current_tests.rs b/crates/openhuman-core/src/config/ops/loader_current_tests.rsindex bd049ede6b..363fd99dd2 100644--- a/crates/openhuman-core/src/config/ops/loader_current_tests.rs+++ b/crates/openhuman-core/src/config/ops/loader_current_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::schema::{EphemeralRoute, EPHEMERAL_ROUTE_SLUG};use crate::core::runtime::{context::CoreContext, DomainSet};@@ -21,7 +22,7 @@ async fn a_context_route_follows_every_load_of_the_context_config() {headers: Vec::new(),});- let loaded = CoreContext::scope(context_with(config), load_current_or_init())+ let loaded = CoreContext::scope(context_with(config), load_current_or_init(&DispatchCtx::process_default())).await.expect("context config loads");@@ -40,7 +41,7 @@ async fn a_context_route_follows_every_load_of_the_context_config() {#[tokio::test]async fn a_context_without_a_route_loads_unchanged_providers() {- let loaded = CoreContext::scope(context_with(base_config()), load_current_or_init())+ let loaded = CoreContext::scope(context_with(base_config()), load_current_or_init(&DispatchCtx::process_default())).await.expect("context config loads");diff --git a/crates/openhuman-core/src/config/ops_voice_and_autonomy_tests.rs b/crates/openhuman-core/src/config/ops_voice_and_autonomy_tests.rsindex e4c6635d65..407505a191 100644--- a/crates/openhuman-core/src/config/ops_voice_and_autonomy_tests.rs+++ b/crates/openhuman-core/src/config/ops_voice_and_autonomy_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;#[tokio::test]@@ -29,7 +30,7 @@ async fn load_and_apply_dictation_settings_rejects_invalid_activation_mode() {streaming: None,streaming_interval_ms: None,};- let err = load_and_apply_dictation_settings(patch).await.unwrap_err();+ let err = load_and_apply_dictation_settings(&DispatchCtx::process_default(), patch).await.unwrap_err();assert!(err.contains("invalid activation_mode"));unsafe {std::env::remove_var("OPENHUMAN_WORKSPACE");@@ -55,7 +56,7 @@ async fn load_and_apply_voice_server_settings_rejects_invalid_activation_mode()wake_word: None,stt_engine: None,};- let err = load_and_apply_voice_server_settings(patch)+ let err = load_and_apply_voice_server_settings(&DispatchCtx::process_default(), patch).await.unwrap_err();assert!(err.contains("invalid activation_mode"));@@ -81,7 +82,7 @@ async fn load_and_apply_dictation_settings_accepts_valid_modes() {streaming_interval_ms: Some(500),};assert!(- load_and_apply_dictation_settings(patch).await.is_ok(),+ load_and_apply_dictation_settings(&DispatchCtx::process_default(), patch).await.is_ok(),"mode `{mode}` should be accepted");}@@ -110,7 +111,7 @@ async fn load_and_apply_voice_server_settings_accepts_valid_modes_and_clamps() {wake_word: Some("Hey Tiny".to_string()),stt_engine: Some("elevenlabs".into()),};- let outcome = load_and_apply_voice_server_settings(patch)+ let outcome = load_and_apply_voice_server_settings(&DispatchCtx::process_default(), patch).await.expect("ok");assert!(@@ -155,7 +156,7 @@ async fn load_and_apply_voice_server_settings_rejects_unknown_stt_engine() {// could still send it.stt_engine: Some("whisper".into()),};- let err = load_and_apply_voice_server_settings(patch)+ let err = load_and_apply_voice_server_settings(&DispatchCtx::process_default(), patch).await.unwrap_err();assert!(err.contains("invalid stt_engine"), "got: {err}");@@ -173,7 +174,7 @@ async fn get_dictation_settings_reads_from_loaded_config() {unsafe {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- let outcome = get_dictation_settings().await.expect("ok");+ let outcome = get_dictation_settings(&DispatchCtx::process_default()).await.expect("ok");assert!(outcome.value.get("enabled").is_some());assert!(outcome.value.get("hotkey").is_some());assert!(outcome.value.get("streaming_interval_ms").is_some());@@ -189,7 +190,7 @@ async fn get_voice_server_settings_reads_from_loaded_config() {unsafe {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- let outcome = get_voice_server_settings().await.expect("ok");+ let outcome = get_voice_server_settings(&DispatchCtx::process_default()).await.expect("ok");assert!(outcome.value.get("auto_start").is_some());assert!(outcome.value.get("custom_dictionary").is_some());unsafe {@@ -204,7 +205,7 @@ async fn get_onboarding_completed_reads_from_loaded_config() {unsafe {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- let outcome = get_onboarding_completed().await.expect("ok");+ let outcome = get_onboarding_completed(&DispatchCtx::process_default()).await.expect("ok");// Default value — either true or false is fine; we just verify the call path.let _ = outcome.value;unsafe {@@ -219,7 +220,7 @@ async fn load_and_resolve_api_url_returns_api_url_in_response() {unsafe {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- let outcome = load_and_resolve_api_url().await.expect("ok");+ let outcome = load_and_resolve_api_url(&DispatchCtx::process_default()).await.expect("ok");assert!(outcome.value.get("api_url").is_some());unsafe {std::env::remove_var("OPENHUMAN_WORKSPACE");@@ -245,13 +246,13 @@ async fn workspace_onboarding_flag_resolve_rejects_invalid_and_defaults() {unsafe {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- let err = workspace_onboarding_flag_resolve(Some("a/b".into()), "done")+ let err = workspace_onboarding_flag_resolve(&DispatchCtx::process_default(), Some("a/b".into()), "done").await.unwrap_err();assert!(err.contains("Invalid onboarding flag"));// Happy path: default name on a fresh workspace → file doesn't exist.- let outcome = workspace_onboarding_flag_resolve(None, "onboarding.done")+ let outcome = workspace_onboarding_flag_resolve(&DispatchCtx::process_default(), None, "onboarding.done").await.expect("ok");let _ = outcome.value;@@ -268,7 +269,7 @@ async fn workspace_onboarding_flag_set_rejects_invalid_names() {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}for bad in ["", " ", "a/b", "a\\b", ".."] {- let err = workspace_onboarding_flag_set(Some(bad.into()), "default", true)+ let err = workspace_onboarding_flag_set(&DispatchCtx::process_default(), Some(bad.into()), "default", true).await.unwrap_err();assert!(err.contains("Invalid onboarding flag"), "name {bad}: {err}");@@ -286,12 +287,12 @@ async fn workspace_onboarding_flag_set_round_trip() {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}// Create flag- let created = workspace_onboarding_flag_set(Some("onboarding.done".into()), "default", true)+ let created = workspace_onboarding_flag_set(&DispatchCtx::process_default(), Some("onboarding.done".into()), "default", true).await.expect("create");assert!(created.value);// Remove flag- let removed = workspace_onboarding_flag_set(Some("onboarding.done".into()), "default", false)+ let removed = workspace_onboarding_flag_set(&DispatchCtx::process_default(), Some("onboarding.done".into()), "default", false).await.expect("remove");assert!(!removed.value);@@ -452,7 +453,7 @@ async fn load_and_apply_autonomy_settings_roundtrip() {max_actions_per_hour: Some(500),..Default::default()};- let outcome = load_and_apply_autonomy_settings(patch)+ let outcome = load_and_apply_autonomy_settings(&DispatchCtx::process_default(), patch).await.expect("apply");assert!(outcome.value.get("config").is_some());@@ -559,11 +560,11 @@ async fn add_auto_approve_tool_appends_then_dedupes() {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}- add_auto_approve_tool("git_operations")+ add_auto_approve_tool(&DispatchCtx::process_default(), "git_operations").await.expect("first add");// Idempotent: a second add of the same tool must not create a duplicate.- add_auto_approve_tool("git_operations")+ add_auto_approve_tool(&DispatchCtx::process_default(), "git_operations").await.expect("second add (idempotent)");diff --git a/crates/openhuman-core/src/config/schemas/controllers/agent.rs b/crates/openhuman-core/src/config/schemas/controllers/agent.rsindex fa96ab7ef6..7c294eed5e 100644--- a/crates/openhuman-core/src/config/schemas/controllers/agent.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/agent.rs@@ -13,14 +13,14 @@ use super::super::helpers::{};pub(crate) fn handle_get_autonomy_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async move { to_json(config_rpc::get_autonomy_settings().await?) })+ Box::pin(async move { to_json(config_rpc::get_autonomy_settings(&ctx).await?) })}pub(crate) fn handle_update_autonomy_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -37,35 +37,35 @@ pub(crate) fn handle_update_autonomy_settings(auto_approve: update.auto_approve,auto_approve_all: update.auto_approve_all,};- to_json(config_rpc::load_and_apply_autonomy_settings(patch).await?)+ to_json(config_rpc::load_and_apply_autonomy_settings(&ctx, patch).await?)})}pub(super) fn handle_get_privacy_mode(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async move { to_json(config_rpc::get_privacy_mode().await?) })+ Box::pin(async move { to_json(config_rpc::get_privacy_mode(&ctx).await?) })}pub(super) fn handle_set_privacy_mode(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let update = deserialize_params::<PrivacyModeUpdate>(params)?;let patch = config_rpc::PrivacySettingsPatch { mode: update.mode };- to_json(config_rpc::load_and_apply_privacy_settings(patch).await?)+ to_json(config_rpc::load_and_apply_privacy_settings(&ctx, patch).await?)})}pub(super) fn handle_get_agent_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async {+ Box::pin(async move {log::debug!("[config][rpc] get_agent_settings enter");- match config_rpc::get_agent_settings().await {+ match config_rpc::get_agent_settings(&ctx).await {Ok(outcome) => {log::debug!("[config][rpc] get_agent_settings ok");to_json(outcome)@@ -79,7 +79,7 @@ pub(super) fn handle_get_agent_settings(}pub(super) fn handle_update_agent_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -96,7 +96,7 @@ pub(super) fn handle_update_agent_settings(chat_agent_id: update.chat_agent_id,tool_dispatcher: update.tool_dispatcher,};- match config_rpc::load_and_apply_agent_settings(patch).await {+ match config_rpc::load_and_apply_agent_settings(&ctx, patch).await {Ok(outcome) => {log::debug!("[config][rpc] update_agent_settings ok");to_json(outcome)@@ -110,7 +110,7 @@ pub(super) fn handle_update_agent_settings(}pub(super) fn handle_update_browser_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -129,12 +129,12 @@ pub(super) fn handle_update_browser_settings(task_timeout_secs: update.task_timeout_secs,learn_from_tasks: update.learn_from_tasks,};- to_json(config_rpc::load_and_apply_browser_settings(patch).await?)+ to_json(config_rpc::load_and_apply_browser_settings(&ctx, patch).await?)})}pub(super) fn handle_update_computer_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -146,7 +146,7 @@ pub(super) fn handle_update_computer_settings(rescue_model: update.rescue_model,max_rescues: update.max_rescues,};- to_json(config_rpc::load_and_apply_computer_settings(patch).await?)+ to_json(config_rpc::load_and_apply_computer_settings(&ctx, patch).await?)})}@@ -161,14 +161,14 @@ pub(super) fn handle_set_browser_allow_all(}pub(super) fn handle_get_sandbox_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async move { to_json(config_rpc::get_sandbox_settings().await?) })+ Box::pin(async move { to_json(config_rpc::get_sandbox_settings(&ctx).await?) })}pub(super) fn handle_update_sandbox_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -181,6 +181,6 @@ pub(super) fn handle_update_sandbox_settings(docker_cpu_limit: update.docker_cpu_limit,env_passthrough: update.env_passthrough,};- to_json(config_rpc::load_and_apply_sandbox_settings(patch).await?)+ to_json(config_rpc::load_and_apply_sandbox_settings(&ctx, patch).await?)})}diff --git a/crates/openhuman-core/src/config/schemas/controllers/inference.rs b/crates/openhuman-core/src/config/schemas/controllers/inference.rsindex 8521ff62fd..c85d5396ea 100644--- a/crates/openhuman-core/src/config/schemas/controllers/inference.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/inference.rs@@ -12,19 +12,19 @@ use super::super::helpers::{};pub(super) fn handle_get_config(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::load_and_get_config_snapshot().await?) })+ Box::pin(async move { to_json(config_rpc::load_and_get_config_snapshot(&ctx).await?) })}pub(super) fn handle_get_client_config(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {log::debug!("[config][rpc] get_client_config enter");- match config_rpc::load_and_get_client_config_snapshot().await {+ match config_rpc::load_and_get_client_config_snapshot(&ctx).await {Ok(snapshot) => to_json(snapshot),Err(err) => {log::warn!("[config][rpc] get_client_config load failed: {err}");@@ -35,7 +35,7 @@ pub(super) fn handle_get_client_config(}pub(super) fn handle_update_model_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -173,12 +173,12 @@ pub(super) fn handle_update_model_settings(memory_provider: update.memory_provider,embeddings_provider: update.embeddings_provider,};- to_json(config_rpc::load_and_apply_model_settings(patch).await?)+ to_json(config_rpc::load_and_apply_model_settings(&ctx, patch).await?)})}pub(super) fn handle_update_memory_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -188,12 +188,12 @@ pub(super) fn handle_update_memory_settings(embedding_model: update.embedding_model,embedding_dimensions: update.embedding_dimensions,};- to_json(config_rpc::load_and_apply_memory_settings(patch).await?)+ to_json(config_rpc::load_and_apply_memory_settings(&ctx, patch).await?)})}pub(super) fn handle_update_runtime_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -204,12 +204,12 @@ pub(super) fn handle_update_runtime_settings(reasoning_effort: update.reasoning_effort,reasoning_effort_model: update.reasoning_effort_model,};- to_json(config_rpc::load_and_apply_runtime_settings(patch).await?)+ to_json(config_rpc::load_and_apply_runtime_settings(&ctx, patch).await?)})}pub(super) fn handle_update_local_ai_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -230,15 +230,15 @@ pub(super) fn handle_update_local_ai_settings(usage_embeddings: update.usage_embeddings,api_key: update.api_key,};- to_json(config_rpc::load_and_apply_local_ai_settings(patch).await?)+ to_json(config_rpc::load_and_apply_local_ai_settings(&ctx, patch).await?)})}pub(super) fn handle_resolve_api_url(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::load_and_resolve_api_url().await?) })+ Box::pin(async move { to_json(config_rpc::load_and_resolve_api_url(&ctx).await?) })}pub(super) fn handle_get_runtime_flags(diff --git a/crates/openhuman-core/src/config/schemas/controllers/integrations.rs b/crates/openhuman-core/src/config/schemas/controllers/integrations.rsindex 6ca50df047..544175915c 100644--- a/crates/openhuman-core/src/config/schemas/controllers/integrations.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/integrations.rs@@ -9,7 +9,7 @@ use crate::core::all::ControllerFuture;use super::super::helpers::{deserialize_params, to_json, ComposioTriggerSettingsUpdate};pub(super) fn handle_update_search_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -21,7 +21,7 @@ pub(super) fn handle_update_search_settings(return Err(err);}};- match config_rpc::load_and_apply_search_settings(patch).await {+ match config_rpc::load_and_apply_search_settings(&ctx, patch).await {Ok(outcome) => {log::debug!("[config][rpc] update_search_settings ok");to_json(outcome)@@ -35,12 +35,12 @@ pub(super) fn handle_update_search_settings(}pub(super) fn handle_get_search_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async {+ Box::pin(async move {log::debug!("[config][rpc] get_search_settings enter");- match config_rpc::get_search_settings().await {+ match config_rpc::get_search_settings(&ctx).await {Ok(outcome) => {log::debug!("[config][rpc] get_search_settings ok");to_json(outcome)@@ -54,7 +54,7 @@ pub(super) fn handle_get_search_settings(}pub(super) fn handle_update_composio_trigger_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -70,7 +70,7 @@ pub(super) fn handle_update_composio_trigger_settings(triage_disabled: update.triage_disabled,triage_disabled_toolkits: update.triage_disabled_toolkits,};- match config_rpc::load_and_apply_composio_trigger_settings(patch).await {+ match config_rpc::load_and_apply_composio_trigger_settings(&ctx, patch).await {Ok(outcome) => {log::debug!("[config][rpc] update_composio_trigger_settings ok");to_json(outcome)@@ -84,12 +84,12 @@ pub(super) fn handle_update_composio_trigger_settings(}pub(super) fn handle_get_composio_trigger_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async {+ Box::pin(async move {log::debug!("[config][rpc] get_composio_trigger_settings enter");- match config_rpc::get_composio_trigger_settings().await {+ match config_rpc::get_composio_trigger_settings(&ctx).await {Ok(outcome) => {log::debug!("[config][rpc] get_composio_trigger_settings ok");to_json(outcome)diff --git a/crates/openhuman-core/src/config/schemas/controllers/voice.rs b/crates/openhuman-core/src/config/schemas/controllers/voice.rsindex f0264eb2d5..8a68fb8d45 100644--- a/crates/openhuman-core/src/config/schemas/controllers/voice.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/voice.rs@@ -11,14 +11,14 @@ use super::super::helpers::{};pub(super) fn handle_get_dictation_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::get_dictation_settings().await?) })+ Box::pin(async move { to_json(config_rpc::get_dictation_settings(&ctx).await?) })}pub(super) fn handle_update_dictation_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -31,15 +31,15 @@ pub(super) fn handle_update_dictation_settings(streaming: update.streaming,streaming_interval_ms: update.streaming_interval_ms,};- to_json(config_rpc::load_and_apply_dictation_settings(patch).await?)+ to_json(config_rpc::load_and_apply_dictation_settings(&ctx, patch).await?)})}pub(super) fn handle_get_voice_server_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::get_voice_server_settings().await?) })+ Box::pin(async move { to_json(config_rpc::get_voice_server_settings(&ctx).await?) })}pub(super) fn handle_update_voice_server_settings(@@ -60,7 +60,7 @@ pub(super) fn handle_update_voice_server_settings(wake_word: update.wake_word,stt_engine: update.stt_engine,};- let result = config_rpc::load_and_apply_voice_server_settings(patch).await?;+ let result = config_rpc::load_and_apply_voice_server_settings(&ctx, patch).await?;// Apply the always-on toggle live (start/idle the capture loop) so the// Settings switch takes effect without a restart. Don't fail the RPC if// the reload hiccups, but DO surface it — otherwise the saved settingdiff --git a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs b/crates/openhuman-core/src/config/schemas/controllers/workspace.rsindex 742cc01795..a598799a89 100644--- a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs+++ b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs@@ -13,13 +13,13 @@ use super::super::helpers::{};pub(super) fn handle_workspace_onboarding_flag_exists(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<WorkspaceOnboardingFlagParams>(params)?;to_json(- config_rpc::workspace_onboarding_flag_resolve(+ config_rpc::workspace_onboarding_flag_resolve(&ctx,payload.flag_name,DEFAULT_ONBOARDING_FLAG_NAME,)@@ -29,13 +29,13 @@ pub(super) fn handle_workspace_onboarding_flag_exists(}pub(super) fn handle_workspace_onboarding_flag_set(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<WorkspaceOnboardingFlagSetParams>(params)?;to_json(- config_rpc::workspace_onboarding_flag_set(+ config_rpc::workspace_onboarding_flag_set(&ctx,payload.flag_name,DEFAULT_ONBOARDING_FLAG_NAME,payload.value,@@ -46,7 +46,7 @@ pub(super) fn handle_workspace_onboarding_flag_set(}pub(super) fn handle_update_analytics_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -54,17 +54,17 @@ pub(super) fn handle_update_analytics_settings(let patch = config_rpc::AnalyticsSettingsPatch {enabled: update.enabled,};- to_json(config_rpc::load_and_apply_analytics_settings(patch).await?)+ to_json(config_rpc::load_and_apply_analytics_settings(&ctx, patch).await?)})}pub(super) fn handle_update_user_timezone(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let update = deserialize_params::<UserTimezoneUpdate>(params)?;- to_json(config_rpc::load_and_apply_user_timezone(update.timezone).await?)+ to_json(config_rpc::load_and_apply_user_timezone(&ctx, update.timezone).await?)})}@@ -99,10 +99,10 @@ pub(super) fn handle_get_analytics_settings(}pub(super) fn handle_get_dashboard_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::get_dashboard_settings().await?) })+ Box::pin(async move { to_json(config_rpc::get_dashboard_settings(&ctx).await?) })}pub(super) fn handle_agent_server_status(@@ -113,19 +113,19 @@ pub(super) fn handle_agent_server_status(}pub(super) fn handle_reset_local_data(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::reset_local_data().await?) })+ Box::pin(async move { to_json(config_rpc::reset_local_data(&ctx).await?) })}pub(crate) fn handle_get_data_paths(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {log::debug!("[config][rpc] get_data_paths enter");- match resolve_data_paths(params).await {+ match resolve_data_paths(&ctx, params).await {Ok(outcome) => {log::debug!("[config][rpc] get_data_paths ok");to_json(outcome)@@ -144,7 +144,7 @@ pub(crate) fn handle_get_data_paths(/// the explicit id the core would fall back to the pre-login `users/local` dir/// and leave the real user's data behind. Absent/blank → marker-based/// resolution (the default used by the agent tool and diagnostics).-async fn resolve_data_paths(+async fn resolve_data_paths(ctx: &DispatchCtx,params: Map<String, Value>,) -> Result<crate::core::Outcome<Value>, String> {let user_id = params@@ -159,17 +159,17 @@ async fn resolve_data_paths();match user_id.as_deref() {Some(id) => config_rpc::get_data_paths_for_user(id).await,- None => config_rpc::get_data_paths().await,+ None => config_rpc::get_data_paths(&ctx).await,}}pub(crate) fn handle_get_agent_paths(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async {+ Box::pin(async move {log::debug!("[config][rpc] get_agent_paths enter");- match config_rpc::get_agent_paths().await {+ match config_rpc::get_agent_paths(&ctx).await {Ok(outcome) => {log::debug!("[config][rpc] get_agent_paths ok");to_json(outcome)@@ -183,7 +183,7 @@ pub(crate) fn handle_get_agent_paths(}pub(super) fn handle_update_agent_paths(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -199,7 +199,7 @@ pub(super) fn handle_update_agent_paths(action_dir: update.action_dir,files_dir: update.files_dir,};- match config_rpc::load_and_apply_agent_paths_settings(patch).await {+ match config_rpc::load_and_apply_agent_paths_settings(&ctx, patch).await {Ok(outcome) => {log::debug!("[config][rpc] update_agent_paths ok");to_json(outcome)@@ -213,18 +213,18 @@ pub(super) fn handle_update_agent_paths(}pub(super) fn handle_get_onboarding_completed(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async { to_json(config_rpc::get_onboarding_completed().await?) })+ Box::pin(async move { to_json(config_rpc::get_onboarding_completed(&ctx).await?) })}pub(super) fn handle_set_onboarding_completed(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<OnboardingCompletedSetParams>(params)?;- to_json(config_rpc::set_onboarding_completed(payload.value).await?)+ to_json(config_rpc::set_onboarding_completed(&ctx, payload.value).await?)})}diff --git a/crates/openhuman-core/src/config/schemas_tests.rs b/crates/openhuman-core/src/config/schemas_tests.rsindex fd0618c6bf..46a3f2cc8d 100644--- a/crates/openhuman-core/src/config/schemas_tests.rs+++ b/crates/openhuman-core/src/config/schemas_tests.rs@@ -298,7 +298,7 @@ async fn handle_get_autonomy_settings_returns_current_value() {std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());}// Seed a known value before reading.- let _ = crate::config::ops::load_and_apply_autonomy_settings(+ let _ = crate::config::ops::load_and_apply_autonomy_settings(&DispatchCtx::process_default(),crate::config::ops::AutonomySettingsPatch {max_actions_per_hour: Some(123),..Default::default()diff --git a/crates/openhuman-core/src/config/tools.rs b/crates/openhuman-core/src/config/tools.rsindex c19807bd96..e1db86eece 100644--- a/crates/openhuman-core/src/config/tools.rs+++ b/crates/openhuman-core/src/config/tools.rs@@ -49,7 +49,7 @@ macro_rules! read_tool {}async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {log::debug!(concat!("[tool][config] ", $name, " invoked"));- emit!(ops::$fn().await, $name)+ emit!(ops::$fn(&ctx).await, $name)}fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {truediff --git a/crates/openhuman-core/src/config/workspace/ops_tests.rs b/crates/openhuman-core/src/config/workspace/ops_tests.rsindex 23c05a34c1..98fb0923cb 100644--- a/crates/openhuman-core/src/config/workspace/ops_tests.rs+++ b/crates/openhuman-core/src/config/workspace/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::test_env::EnvVarGuard;use crate::config::TEST_ENV_LOCK as ENV_LOCK;@@ -76,7 +77,7 @@ async fn init_workspace_creates_dirs_and_files_in_fresh_workspace() {let tmp = tempdir().unwrap();let _env = EnvVarGuard::workspace_unlocked(tmp.path());- let value = init_workspace(false)+ let value = init_workspace(&DispatchCtx::process_default(), false).await.expect("init_workspace on empty temp should succeed");@@ -117,10 +118,10 @@ async fn init_workspace_reports_existing_entries_on_second_call_without_force()let _env = EnvVarGuard::workspace_unlocked(tmp.path());// First call populates the workspace.- init_workspace(false).await.expect("first init ok");+ init_workspace(&DispatchCtx::process_default(), false).await.expect("first init ok");// Second call without force should report everything as existing// and nothing as created / overwritten.- let value = init_workspace(false).await.expect("second init ok");+ let value = init_workspace(&DispatchCtx::process_default(), false).await.expect("second init ok");let created = value["result"]["files"]["created"].as_array().unwrap();let overwritten = value["result"]["files"]["overwritten"].as_array().unwrap();@@ -150,7 +151,7 @@ async fn init_workspace_with_force_overwrites_existing_bootstrap_files() {let tmp = tempdir().unwrap();let _env = EnvVarGuard::workspace_unlocked(tmp.path());- let first = init_workspace(false).await.expect("initial init");+ let first = init_workspace(&DispatchCtx::process_default(), false).await.expect("initial init");// The config loader may place the workspace at a subpath of the// env override (e.g. `{tmp}/workspace`), so discover the real// location from the first result rather than assuming it is@@ -163,7 +164,7 @@ async fn init_workspace_with_force_overwrites_existing_bootstrap_files() {let soul = workspace_dir.join("SOUL.md");std::fs::write(&soul, "corrupted").unwrap();- let value = init_workspace(true).await.expect("forced init");+ let value = init_workspace(&DispatchCtx::process_default(), true).await.expect("forced init");let overwritten: Vec<&str> = value["result"]["files"]["overwritten"].as_array()diff --git a/crates/openhuman-core/src/config/workspace/tools.rs b/crates/openhuman-core/src/config/workspace/tools.rsindex 8cb79430c6..3613987d3c 100644--- a/crates/openhuman-core/src/config/workspace/tools.rs+++ b/crates/openhuman-core/src/config/workspace/tools.rs@@ -8,6 +8,7 @@//! identity/scaffold, so they ship default-OFF via `tools/user_filter.rs`//! (`workspace_manage` toggle).+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use async_trait::async_trait;@@ -170,7 +171,7 @@ impl Tool for WorkspaceInitTool {async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {log::debug!("[tool][workspace] init invoked");let force = args.get("force").and_then(Value::as_bool).unwrap_or(false);- let value = ops::init_workspace(force)+ let value = ops::init_workspace(&DispatchCtx::ambient(), force).await.map_err(|e| anyhow::anyhow!("workspace_init: {e}"))?;Ok(ToolResult::success(serde_json::to_string(&value)?))diff --git a/crates/openhuman-core/src/core/invoke.rs b/crates/openhuman-core/src/core/invoke.rsindex c1400039c4..c2317e9128 100644--- a/crates/openhuman-core/src/core/invoke.rs+++ b/crates/openhuman-core/src/core/invoke.rs@@ -51,7 +51,7 @@ pub async fn invoke_method(// local credential cannot use. This extra config read happens only// on a classified session-expiry error, never on the normal path.let local =- crate::security::credentials::session_support::current_session_is_local().await;+ crate::security::credentials::session_support::current_session_is_local(&ctx).await;if should_publish_session_expired(msg, local) {log::warn!("[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",diff --git a/crates/openhuman-core/src/core/runtime/bootstrap.rs b/crates/openhuman-core/src/core/runtime/bootstrap.rsindex dd92524d5f..7023aff5bc 100644--- a/crates/openhuman-core/src/core/runtime/bootstrap.rs+++ b/crates/openhuman-core/src/core/runtime/bootstrap.rs@@ -6,6 +6,7 @@//! [`CoreRuntime::start_services`](super::CoreRuntime::start_services)//! once a transport has bound, or directly when there is none.+use crate::core::runtime::DispatchCtx;/// Initializes long-lived socket/event-bus infrastructure.////// `host_kind` identifies the embedding process (Tauri desktop shell vs@@ -86,7 +87,7 @@ pub(crate) async fn bootstrap_core_runtime(// meant to gate the first tool call of the first turn has to be loaded// before any session exists, and the alternative — loading lazily on the// first event — would let that first call through while the file is read.- crate::hooks::init(&cfg).await;+ crate::hooks::init(&DispatchCtx::ambient(), &cfg).await;// --- Turn-state recovery -------------------------------------------// Any per-thread turn snapshots left on disk from a previous processdiff --git a/crates/openhuman-core/src/core/runtime/subscribers.rs b/crates/openhuman-core/src/core/runtime/subscribers.rsindex 352c99de1e..b7326efc27 100644--- a/crates/openhuman-core/src/core/runtime/subscribers.rs+++ b/crates/openhuman-core/src/core/runtime/subscribers.rs@@ -6,6 +6,7 @@//! [`DomainGroup`](crate::core::all::DomainGroup) registers the first time a//! boot enables it.+use crate::core::runtime::DispatchCtx;/// Per-`DomainGroup` gating decision for each event-bus subscriber that/// [`register_domain_subscribers`] conditionally registers. Extracted as a/// pure value so the subscriber→group mapping has a single source of truth@@ -174,7 +175,7 @@ pub(super) fn register_domain_subscribers(if std::env::var_os(crate::security::credentials::BACKEND_SESSION_TOKEN_ENV).is_some() {let config = config.clone();tokio::spawn(async move {- crate::security::credentials::seed_session_from_env(&config).await;+ crate::security::credentials::seed_session_from_env(&DispatchCtx::ambient(), &config).await;});}diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rsindex f9936c8ddf..0d483fa91d 100644--- a/crates/openhuman-core/src/cron/scheduler.rs+++ b/crates/openhuman-core/src/cron/scheduler.rs@@ -123,7 +123,7 @@ impl LiveAgentSchedulers {for (agent_id, ctx) in live {let scheduler = &mut self.by_agent;crate::core::runtime::CoreContext::scope(ctx, async move {- let config = match crate::config::ops::load_current_or_init().await {+ let config = match crate::config::ops::load_current_or_init(&ctx).await {Ok(config) => config,Err(error) => {tracing::debug!(agent = %agent_id, %error, "[cron:scheduler] agent config unavailable");diff --git a/crates/openhuman-core/src/desktop/app_state/schemas.rs b/crates/openhuman-core/src/desktop/app_state/schemas.rsindex 1e4e941aaf..c80a79d92d 100644--- a/crates/openhuman-core/src/desktop/app_state/schemas.rs+++ b/crates/openhuman-core/src/desktop/app_state/schemas.rs@@ -93,19 +93,19 @@ pub fn app_state_schemas(function: &str) -> ControllerSchema {}}-fn handle_snapshot(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+fn handle_snapshot(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {- crate::desktop::app_state::snapshot()+ crate::desktop::app_state::snapshot(&ctx).await?.into_cli_compatible_json()})}-fn handle_update_local_state(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_update_local_state(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload: UpdateLocalStateParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- crate::desktop::app_state::update_local_state(StoredAppStatePatch {+ crate::desktop::app_state::update_local_state(&ctx, StoredAppStatePatch {encryption_key: payload.encryption_key,onboarding_tasks: payload.onboarding_tasks,keyring_consent: payload.keyring_consent,diff --git a/crates/openhuman-core/src/desktop/notifications/schemas.rs b/crates/openhuman-core/src/desktop/notifications/schemas.rsindex a969429618..0a3d334d4a 100644--- a/crates/openhuman-core/src/desktop/notifications/schemas.rs+++ b/crates/openhuman-core/src/desktop/notifications/schemas.rs@@ -464,44 +464,44 @@ fn schema_unknown() -> ControllerSchema {// Handler wrappers (delegate to rpc.rs)// ─────────────────────────────────────────────────────────────────────────────-fn handle_ingest_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_ingest(params).await })+fn handle_ingest_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_ingest(&ctx, params).await })}-fn handle_list_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_list(params).await })+fn handle_list_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_list(&ctx, params).await })}-fn handle_mark_read_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_mark_read(params).await })+fn handle_mark_read_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_mark_read(&ctx, params).await })}-fn handle_settings_get_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_settings_get(params).await })+fn handle_settings_get_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_settings_get(&ctx, params).await })}-fn handle_settings_set_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_settings_set(params).await })+fn handle_settings_set_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_settings_set(&ctx, params).await })}-fn handle_dismiss_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_dismiss(params).await })+fn handle_dismiss_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_dismiss(&ctx, params).await })}-fn handle_mark_acted_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_mark_acted(params).await })+fn handle_mark_acted_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_mark_acted(&ctx, params).await })}-fn handle_stats_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_stats(params).await })+fn handle_stats_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_stats(&ctx, params).await })}-fn handle_core_list_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_core_list(params).await })+fn handle_core_list_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_core_list(&ctx, params).await })}-fn handle_core_mark_read_wrap(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { super::rpc::handle_core_mark_read(params).await })+fn handle_core_mark_read_wrap(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { super::rpc::handle_core_mark_read(&ctx, params).await })}// ─────────────────────────────────────────────────────────────────────────────diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rsindex 4467b1f682..df9606ea71 100644--- a/crates/openhuman-core/src/flows/ops/builder.rs+++ b/crates/openhuman-core/src/flows/ops/builder.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;/// Runs the `workflow_builder` agent for one authoring turn and returns its@@ -15,12 +16,12 @@ use super::*;/// Persistence stays with the agent's tools: `propose`/`revise` never persist;/// `save_workflow` (only reachable in `build` mode with a real `flow_id`)/// writes onto an existing flow. This op never enables or runs a flow.-pub async fn flows_build(+pub async fn flows_build(ctx: &DispatchCtx,config: &Config,req: crate::flows::agents::workflow_builder::builder_prompt::BuilderRequest,stream: Option<FlowStreamTarget>,) -> Result<Outcome<Value>, String> {- flows_build_with_extra_hidden_tools(config, req, stream, &[]).await+ flows_build_with_extra_hidden_tools(&ctx, config, req, stream, &[]).await}/// [`flows_build`] with caller-specific tools removed in addition to the@@ -29,7 +30,7 @@ pub async fn flows_build(/// This is intentionally crate-private: product surfaces use [`flows_build`]'s/// normal builder belt. Host integrations that add their own persistence/// boundary can hide tools that would bypass that boundary.-pub(crate) async fn flows_build_with_extra_hidden_tools(+pub(crate) async fn flows_build_with_extra_hidden_tools(ctx: &DispatchCtx,config: &Config,req: crate::flows::agents::workflow_builder::builder_prompt::BuilderRequest,stream: Option<FlowStreamTarget>,@@ -49,7 +50,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools() {if let Some(assistant_text) = req.error.as_deref().and_then(backend_repair_message) {if let Some(target) = &stream {- finalize_flow_stream(target, &Ok(assistant_text.clone()), &prompt).await;+ finalize_flow_stream(&ctx, target, &Ok(assistant_text.clone()), &prompt).await;}return Ok(Outcome::single_log(json!({@@ -312,7 +313,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(if cancelled {if let Some(target) = &stream {let terminal: Result<String, String> = Ok(assistant_text.clone());- finalize_flow_stream(target, &terminal, &prompt).await;+ finalize_flow_stream(&ctx, target, &terminal, &prompt).await;}tracing::info!(target: "flows",@@ -338,7 +339,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(if let Some(err) = &run_error {if let Some(target) = &stream {let terminal: Result<String, String> = Err(err.clone());- finalize_flow_stream(target, &terminal, &prompt).await;+ finalize_flow_stream(&ctx, target, &terminal, &prompt).await;}return Err(format!("workflow_builder produced no proposal: {err}"));}@@ -395,7 +396,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(None => Ok(assistant_text.clone()),Some(err) => Err(err.clone()),};- finalize_flow_stream(target, &terminal, &prompt).await;+ finalize_flow_stream(&ctx, target, &terminal, &prompt).await;}tracing::info!(diff --git a/crates/openhuman-core/src/flows/ops/discovery.rs b/crates/openhuman-core/src/flows/ops/discovery.rsindex 413ead1f59..fd5546cd96 100644--- a/crates/openhuman-core/src/flows/ops/discovery.rs+++ b/crates/openhuman-core/src/flows/ops/discovery.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;// ─────────────────────────────────────────────────────────────────────────────@@ -35,7 +36,7 @@ const FLOW_DISCOVER_PROMPT: &str = "Discover the most useful automations you cou/// (`PermissionLevel::None`) — so this never persists, enables, or runs a flow./// Turning a suggestion into a real flow is the user's separate "Build this"/// action, which routes to `workflow_builder`.-pub async fn flows_discover(+pub async fn flows_discover(ctx: &DispatchCtx,config: &Config,stream: Option<FlowStreamTarget>,) -> Result<Outcome<Vec<FlowSuggestion>>, String> {@@ -108,7 +109,7 @@ pub async fn flows_discover(// Emit the terminal chat event so a client viewing the thread finalizes the// assistant bubble instead of spinning (the bridge only streams deltas).if let Some(target) = &stream {- finalize_flow_stream(target, &outcome, FLOW_DISCOVER_PROMPT).await;+ finalize_flow_stream(&ctx, target, &outcome, FLOW_DISCOVER_PROMPT).await;}let suggestions = store::list_suggestions(config, Some(SuggestionStatus::New), 50)diff --git a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rsindex 25877db564..fef54331c2 100644--- a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs+++ b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::{config::Config,@@ -64,7 +65,7 @@ fn repair_backend_failure_returns_no_proposal_before_starting_the_builder() {};let outcome =- flows_build_with_extra_hidden_tools(&Config::default(), req.clone(), None, &[])+ flows_build_with_extra_hidden_tools(&DispatchCtx::process_default(), &Config::default(), req.clone(), None, &[]).await.expect("backend failure should short-circuit before the builder starts");@@ -82,7 +83,7 @@ fn repair_backend_failure_returns_no_proposal_before_starting_the_builder() {};let mut events = crate::web_chat::subscribe_web_channel_events();- flows_build_with_extra_hidden_tools(&Config::default(), req, Some(stream), &[])+ flows_build_with_extra_hidden_tools(&DispatchCtx::process_default(), &Config::default(), req, Some(stream), &[]).await.expect("streamed backend failure should short-circuit before the builder starts");diff --git a/crates/openhuman-core/src/flows/schemas_handlers.rs b/crates/openhuman-core/src/flows/schemas_handlers.rsindex 983493c596..8a49c97ae6 100644--- a/crates/openhuman-core/src/flows/schemas_handlers.rs+++ b/crates/openhuman-core/src/flows/schemas_handlers.rs@@ -288,7 +288,7 @@ fn handle_build(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuturlet req: crate::flows::agents::workflow_builder::builder_prompt::BuilderRequest =serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid flows.build params: {e}"))?;- to_json(ops::flows_build(&config, req, stream).await?)+ to_json(ops::flows_build(&ctx, &config, req, stream).await?)})}@@ -309,7 +309,7 @@ fn handle_discover(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFu// Optional streaming target for the Flow Scout run (Phase B) — same// `thread_id`/`request_id` convention as `flows.build`.let stream = read_flow_stream_target(¶ms);- to_json(ops::flows_discover(&config, stream).await?)+ to_json(ops::flows_discover(&ctx, &config, stream).await?)})}diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs b/crates/openhuman-core/src/flows/tinyflows/caps/code.rsindex 2fc1a4bed0..d87c11ca0d 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs@@ -5,6 +5,7 @@#![allow(unused_imports)]+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use async_trait::async_trait;@@ -142,7 +143,7 @@ impl CodeRunner for OpenHumanCode {"[flows] code: running sandboxed script");- execute_in_sandbox(+ execute_in_sandbox(&DispatchCtx::ambient(),&policy,&command,&self.config.action_dir,diff --git a/crates/openhuman-core/src/hooks/host.rs b/crates/openhuman-core/src/hooks/host.rsindex 1a052b420d..b60207f97b 100644--- a/crates/openhuman-core/src/hooks/host.rs+++ b/crates/openhuman-core/src/hooks/host.rs@@ -6,6 +6,7 @@//! `OPENHUMAN_*` hook environment, the user's home directory, the platform//! shell, and the model behind `prompt` hooks.+use crate::core::runtime::DispatchCtx;use std::sync::{Arc, LazyLock};use async_trait::async_trait;@@ -23,7 +24,7 @@ struct HostPromptEvaluator;#[async_trait]impl PromptEvaluator for HostPromptEvaluator {async fn evaluate(&self, instruction: &str, model: Option<&str>) -> Result<String, String> {- super::prompt_eval::evaluate(instruction, model).await+ super::prompt_eval::evaluate(&DispatchCtx::ambient(), instruction, model).await}}@@ -46,13 +47,13 @@ pub fn engine() -> &'static HookEngine {/// with, which froze the home directory at first use. Discovery resolves the/// user layer against the home directory **now**, as it did before the engine/// moved upstream, so a reload after `HOME` changes reads the right file.-pub async fn reload(+pub async fn reload(ctx: &DispatchCtx,project_dir: Option<std::path::PathBuf>,workspace_dir: Option<std::path::PathBuf>,) -> Arc<HookConfig> {// Hook commands run under the shell TinyBox selects; ask it here, where the// caller is async, so the engine's synchronous shell factory can use it.- super::shell::resolve().await;+ super::shell::resolve(&ctx).await;let current = environment();let loaded = tokio::task::spawn_blocking(move || {config::load(¤t, project_dir.as_deref(), workspace_dir.as_deref())diff --git a/crates/openhuman-core/src/hooks/ops.rs b/crates/openhuman-core/src/hooks/ops.rsindex 5b87dd1090..7008185a9c 100644--- a/crates/openhuman-core/src/hooks/ops.rs+++ b/crates/openhuman-core/src/hooks/ops.rs@@ -7,6 +7,7 @@//! [`HookEngine::has_hooks`](super::engine::HookEngine::has_hooks) first and//! returns without building an envelope.+use crate::core::runtime::DispatchCtx;use std::path::PathBuf;use std::time::Duration;@@ -23,7 +24,7 @@ use tinyagents_runtime::command_hooks::types::{////// Safe to call again — a reload replaces the whole config and re-registers the/// bridge by name rather than appending a second copy.-pub async fn init(config: &crate::config::schema::Config) {+pub async fn init(ctx: &DispatchCtx, config: &crate::config::schema::Config) {let settings = &config.hooks;set_host_context(HostContext {workspace_roots: workspace_roots(config),@@ -42,7 +43,7 @@ pub async fn init(config: &crate::config::schema::Config) {super::host::engine().set_default_timeout(Duration::from_secs(settings.default_timeout_secs)).await;- let loaded = super::host::reload(+ let loaded = super::host::reload(&ctx,Some(config.action_dir.clone()),Some(config.workspace_dir.clone()),)diff --git a/crates/openhuman-core/src/hooks/schemas.rs b/crates/openhuman-core/src/hooks/schemas.rsindex 92cf0cf3c6..1afdf7b8d4 100644--- a/crates/openhuman-core/src/hooks/schemas.rs+++ b/crates/openhuman-core/src/hooks/schemas.rs@@ -112,7 +112,7 @@ fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFutufn handle_reload(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = ctx.load_config().await?;- super::ops::init(&config).await;+ super::ops::init(&ctx, &config).await;Ok(describe(super::host::engine().snapshot().await.as_ref()))})}diff --git a/crates/openhuman-core/src/inference/embedding_host/schemas.rs b/crates/openhuman-core/src/inference/embedding_host/schemas.rsindex f2bf987ffb..ce0acb620a 100644--- a/crates/openhuman-core/src/inference/embedding_host/schemas.rs+++ b/crates/openhuman-core/src/inference/embedding_host/schemas.rs@@ -178,11 +178,11 @@ fn handle_get_settings(ctx: DispatchCtx, _params: Map<String, Value>) -> Control})}-fn handle_update_settings(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_update_settings(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let p = deserialize_params::<UpdateSettingsParams>(params)?;to_json(- super::rpc::update_settings(+ super::rpc::update_settings(&ctx,p.provider,p.model,p.dimensions,diff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rsindex 684a7ef6c8..2c7688ca0a 100644--- a/crates/openhuman-core/src/inference/ops.rs+++ b/crates/openhuman-core/src/inference/ops.rs@@ -251,9 +251,9 @@ pub async fn inference_analyze_sentiment(result}-pub async fn inference_get_client_config() -> Result<Outcome<Value>, String> {+pub async fn inference_get_client_config(ctx: &DispatchCtx, ) -> Result<Outcome<Value>, String> {debug!("{LOG_PREFIX} get_client_config:start");- let result = config_rpc::load_and_get_client_config_snapshot().await;+ let result = config_rpc::load_and_get_client_config_snapshot(&ctx).await;match &result {Ok(_) => debug!("{LOG_PREFIX} get_client_config:ok"),Err(err) => warn!(error = %err, "{LOG_PREFIX} get_client_config:error"),@@ -261,11 +261,11 @@ pub async fn inference_get_client_config() -> Result<Outcome<Value>, String> {result}-pub async fn inference_update_model_settings(+pub async fn inference_update_model_settings(ctx: &DispatchCtx,update: config_rpc::ModelSettingsPatch,) -> Result<Outcome<Value>, String> {debug!("{LOG_PREFIX} update_model_settings:start");- let result = config_rpc::load_and_apply_model_settings(update).await;+ let result = config_rpc::load_and_apply_model_settings(&ctx, update).await;match &result {Ok(_) => debug!("{LOG_PREFIX} update_model_settings:ok"),Err(err) => warn!(error = %err, "{LOG_PREFIX} update_model_settings:error"),@@ -277,7 +277,7 @@ pub async fn inference_update_local_settings(ctx: &DispatchCtx,update: config_rpc::LocalAiSettingsPatch,) -> Result<Outcome<Value>, String> {debug!("{LOG_PREFIX} update_local_settings:start");- let result = config_rpc::load_and_apply_local_ai_settings(update).await;+ let result = config_rpc::load_and_apply_local_ai_settings(&ctx, update).await;match &result {Ok(_) => {debug!("{LOG_PREFIX} update_local_settings:ok");diff --git a/crates/openhuman-core/src/inference/ops_tests.rs b/crates/openhuman-core/src/inference/ops_tests.rsindex 77fcdb6be0..ae3594211e 100644--- a/crates/openhuman-core/src/inference/ops_tests.rs+++ b/crates/openhuman-core/src/inference/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::security::credentials::openai_oauth::{OPENAI_OAUTH_PROFILE_NAME, OPENAI_PROVIDER_KEY};use crate::security::credentials::profiles::{AuthProfile, AuthProfilesStore, TokenSet};@@ -137,7 +138,7 @@ async fn inference_get_client_config_returns_safe_snapshot() {let (config, _tmp) = disabled_config();config.save().await.expect("save config");- let outcome = inference_get_client_config()+ let outcome = inference_get_client_config(&DispatchCtx::process_default()).await.expect("client config snapshot");assert!(outcome.value.get("cloud_providers").is_some());diff --git a/crates/openhuman-core/src/inference/schemas/settings_handlers.rs b/crates/openhuman-core/src/inference/schemas/settings_handlers.rsindex d6be1b7102..839e5a29a1 100644--- a/crates/openhuman-core/src/inference/schemas/settings_handlers.rs+++ b/crates/openhuman-core/src/inference/schemas/settings_handlers.rs@@ -115,14 +115,14 @@ pub(super) fn handle_inference_status(}pub(super) fn handle_inference_get_client_config(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {- Box::pin(async move { to_json(crate::inference::rpc::inference_get_client_config().await?) })+ Box::pin(async move { to_json(crate::inference::rpc::inference_get_client_config(&ctx).await?) })}pub(super) fn handle_inference_update_model_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -255,12 +255,12 @@ pub(super) fn handle_inference_update_model_settings(memory_provider: update.memory_provider,embeddings_provider: update.embeddings_provider,};- to_json(crate::inference::rpc::inference_update_model_settings(patch).await?)+ to_json(crate::inference::rpc::inference_update_model_settings(&ctx, patch).await?)})}pub(super) fn handle_inference_update_local_settings(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -281,7 +281,7 @@ pub(super) fn handle_inference_update_local_settings(usage_embeddings: update.usage_embeddings,api_key: update.api_key,};- to_json(crate::inference::rpc::inference_update_local_settings(patch).await?)+ to_json(crate::inference::rpc::inference_update_local_settings(&ctx, patch).await?)})}diff --git a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rsindex d3f6315e6b..0d3a910ef5 100644--- a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs@@ -1,6 +1,7 @@//! Thin query adapters for the module-owned CCR store and REPL algorithms.//! OpenHuman authorizes tool-result artifacts; only their content crosses the bus.+use crate::core::runtime::DispatchCtx;use std::path::{Component, Path, PathBuf};use std::sync::Arc;@@ -41,7 +42,7 @@ impl QuerySource for ModuleSource {async fn query(&self, request: QueryRequest) -> Result<QueryResponse, String> {match &self.config {Some(config) => super::query_for_config(config, request).await,- None => super::query(request).await,+ None => super::query(&DispatchCtx::ambient(), request).await,}}}diff --git a/crates/openhuman-core/src/integrations/composio/action_tool.rs b/crates/openhuman-core/src/integrations/composio/action_tool.rsindex 9dc42b9b2a..2189b31c39 100644--- a/crates/openhuman-core/src/integrations/composio/action_tool.rs+++ b/crates/openhuman-core/src/integrations/composio/action_tool.rs@@ -240,7 +240,7 @@ impl Tool for ComposioActionTool {}async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let (config, outcome) = Box::pin(self.execute_unredacted(args, None)).await;+ let (config, outcome) = Box::pin(self.execute_unredacted(&DispatchCtx::ambient(), args, None)).await;super::tools::redact_composio_outcome(&config, outcome)}async fn execute_with_context(@@ -250,7 +250,7 @@ impl Tool for ComposioActionTool {context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {let (config, outcome) =- Box::pin(self.execute_unredacted(args, sandbox_mode_for_tool(context))).await;+ Box::pin(self.execute_unredacted(&DispatchCtx::ambient(), args, sandbox_mode_for_tool(context))).await;super::tools::redact_composio_outcome(&config, outcome)}}@@ -261,7 +261,7 @@ impl ComposioActionTool {/// credential that dispatched — for both a spawn-time config and a/// deferred instance with none.async fn execute_unredacted(- &self,+ &self, ctx: &DispatchCtx,args: Value,sandbox_mode: Option<SandboxMode>,) -> (Box<Config>, anyhow::Result<ToolResult>) {@@ -309,7 +309,7 @@ impl ComposioActionTool {// fresh routing. Anchored to this tool's original config path rather than// re-resolving process-global `OPENHUMAN_WORKSPACE` (the tool is scoped to// the user/workspace it was created for).- let live_config = match self.live_config().await {+ let live_config = match self.live_config(&ctx).await {Ok(c) => Box::new(c),Err(e) => {tracing::warn!(diff --git a/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs b/crates/openhuman-core/src/integrations/composio/action_tool_tests.rsindex c32bc201c3..fa9718c3d8 100644--- a/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/action_tool_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::test_env::EnvVarGuard;@@ -496,7 +497,7 @@ fn deferred_instance_returns_live_config_for_redaction() {// Boxed exactly like `Tool::execute` does.let (live_config, outcome) =- Box::pin(t.execute_unredacted(serde_json::json!({}), None)).await;+ Box::pin(t.execute_unredacted(&DispatchCtx::process_default(), serde_json::json!({}), None)).await;let first = outcome.expect("contract-gate surface is Ok(error result)");assert!(first.is_error && error_text(&first).contains("Input JSON schema"),@@ -548,7 +549,7 @@ fn configured_instance_resolves_live_config_not_the_stale_snapshot() {None,);- let live_config = Box::pin(t.live_config())+ let live_config = Box::pin(t.live_config(&DispatchCtx::process_default())).await.expect("reload from a valid on-disk config must succeed");assert_eq!(diff --git a/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rsindex 00e5e27127..a268b13c42 100644--- a/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs+++ b/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs@@ -90,7 +90,7 @@ impl EventHandler<DomainEvent> for ComposioConnectionCreatedSubscriber {// The cache refresh runs for every toolkit; only the profile fetch is gated on a native provider.let toolkit = toolkit.clone();let connection_id = connection_id.clone();- tokio::spawn(async move { on_connection_created(toolkit, connection_id).await });+ tokio::spawn(async move { on_connection_created(&DispatchCtx::ambient(), toolkit, connection_id).await });}}diff --git a/crates/openhuman-core/src/integrations/composio/ops_direct_mode_and_error_classification_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_direct_mode_and_error_classification_tests.rsindex ac31d3f655..f111c8de4e 100644--- a/crates/openhuman-core/src/integrations/composio/ops_direct_mode_and_error_classification_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_direct_mode_and_error_classification_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;#[tokio::test]@@ -23,7 +24,7 @@ async fn composio_set_api_key_rejects_invalid_direct_key_before_persisting() {let config = direct_mode_no_key_config(&tmp);let _auth_guard = DirectAuthFailureGuard::new("ck_invalid_direct");- let err = composio_set_api_key(&config, "ck_invalid_direct", false)+ let err = composio_set_api_key(&DispatchCtx::process_default(), &config, "ck_invalid_direct", false).await.expect_err("invalid direct-mode key must be rejected before persistence");assert!(@@ -79,7 +80,7 @@ async fn composio_set_api_key_validates_candidate_key_even_when_stored_key_exist.expect("seed old stored composio key");let _new_key_guard = DirectAuthFailureGuard::new("ck_new_invalid");- let err = composio_set_api_key(&config, "ck_new_invalid", false)+ let err = composio_set_api_key(&DispatchCtx::process_default(), &config, "ck_new_invalid", false).await.expect_err("candidate invalid key must be rejected even if old stored key is valid");assert!(diff --git a/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs b/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rsindex f123741f65..0608c892f9 100644--- a/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs@@ -86,7 +86,7 @@ pub(super) fn handle_set_api_key(ctx: DispatchCtx, params: Map<String, Value>) -let config = ctx.load_config().await?;let api_key = read_required_non_empty(¶ms, "api_key")?;let activate_direct = read_optional::<bool>(¶ms, "activate_direct")?.unwrap_or(false);- to_json(ops::composio_set_api_key(&config, &api_key, activate_direct).await?)+ to_json(ops::composio_set_api_key(&ctx, &config, &api_key, activate_direct).await?)})}@@ -97,6 +97,6 @@ pub(super) fn handle_clear_api_key(Box::pin(async move {tracing::debug!("[composio-direct] rpc clear_api_key entry");let config = ctx.load_config().await?;- to_json(ops::composio_clear_api_key(&config).await?)+ to_json(ops::composio_clear_api_key(&ctx, &config).await?)})}diff --git a/crates/openhuman-core/src/integrations/task_sources/bus.rs b/crates/openhuman-core/src/integrations/task_sources/bus.rsindex 5734d8413a..7b6a99d368 100644--- a/crates/openhuman-core/src/integrations/task_sources/bus.rs+++ b/crates/openhuman-core/src/integrations/task_sources/bus.rs@@ -53,7 +53,7 @@ impl EventHandler<DomainEvent> for TaskSourcesConnectionSubscriber {// Every scope may hold sources for this toolkit (`crate::storage`):// handle each scope as its own agent, with that agent's config.crate::storage::agents::for_each_live_scope("task_sources connection", || {- fire_in_scope(provider, toolkit, connection_id)+ fire_in_scope(&DispatchCtx::ambient(), provider, toolkit, connection_id)}).await;}diff --git a/crates/openhuman-core/src/integrations/task_sources/bus_tests.rs b/crates/openhuman-core/src/integrations/task_sources/bus_tests.rsindex c86e59feeb..d181fb1364 100644--- a/crates/openhuman-core/src/integrations/task_sources/bus_tests.rs+++ b/crates/openhuman-core/src/integrations/task_sources/bus_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::integrations::task_sources::types::{FilterSpec, SourceTarget};use serde_json::json;@@ -90,5 +91,5 @@ async fn a_connection_event_is_handled_per_scope() {connection_id: "conn-1".to_string(),}).await;- fire_in_scope(ProviderSlug::Github, "github", "conn-1").await;+ fire_in_scope(&DispatchCtx::process_default(), ProviderSlug::Github, "github", "conn-1").await;}diff --git a/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rs b/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rsindex c2aad66e50..f2a7260d7e 100644--- a/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rs+++ b/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::integrations::task_sources::types::{provider_can_fetch, FilterSpec, ProviderSlug, SourceTarget,@@ -159,7 +160,7 @@ async fn a_tick_over_an_unfetchable_source_records_nothing() {CoreContext::scope(CoreContext::for_test_with_config(DomainSet::full(), config.clone()),- run_one_tick(),+ run_one_tick(&DispatchCtx::process_default()),).await.expect("a tick must not fail");diff --git a/crates/openhuman-core/src/mcp/server/tools/params.rs b/crates/openhuman-core/src/mcp/server/tools/params.rsindex 316a18c22d..12860c9b38 100644--- a/crates/openhuman-core/src/mcp/server/tools/params.rs+++ b/crates/openhuman-core/src/mcp/server/tools/params.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use serde_json::{Map, Value};use tinymcp_bus::ToolCallError;@@ -215,7 +216,7 @@ async fn validate_tool_arguments(}};- let config = crate::config::ops::load_current_or_init()+ let config = crate::config::ops::load_current_or_init(&DispatchCtx::ambient()).await.map_err(|_| ToolCallError::Internal("MCP argument validation is unavailable".into()))?;let client = crate::mcp::module_client::McpConfiguredClient::for_config(&config)diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rsindex 65bec34f31..b3a7cc60a3 100644--- a/crates/openhuman-core/src/memory/bus.rs+++ b/crates/openhuman-core/src/memory/bus.rs@@ -116,7 +116,7 @@ impl EventHandler<DomainEvent> for SystemJobsSubscriber {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 {+ match crate::config::ops::load_current_or_init(&ctx).await {Ok(config) => {tracing::debug!(agent = %agent_id, "[memory:bus] agent source sync");run_system_job(&config, SOURCES_SYNC_JOB).await;diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rsindex 0f08c45eef..2b3cb2970f 100644--- a/crates/openhuman-core/src/memory/schemas/handlers.rs+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs@@ -45,24 +45,24 @@ async fn save(config: &Config) -> MemoryResult<()> {.map_err(|error| MemoryError::Engine(format!("saving config failed: {error:#}")))}-pub(super) fn engines_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn engines_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- to_json(ops::engines_list(&load().await?))+ to_json(ops::engines_list(&load(&ctx).await?))})}-pub(super) fn engine_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn engine_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- to_json(ops::engine_get(&load().await?).await)+ to_json(ops::engine_get(&load(&ctx).await?).await)})}-pub(super) fn engine_set(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn engine_set(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<EngineSetParams>(params)?;- let mut config = load().await?;+ let mut config = load(&ctx).await?;let result = async {ops::apply_engine_set(&mut config, ¶ms)?;save(&config).await@@ -74,168 +74,168 @@ pub(super) fn engine_set(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr})}-pub(super) fn recall(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn recall(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<RecallParams>(params)?;- finish(confine::recall(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::recall(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn fetch(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn fetch(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<FetchParams>(params)?;- finish(confine::fetch(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::fetch(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn learn(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn learn(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<LearnParams>(params)?;- finish(confine::learn(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::learn(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn forget(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn forget(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<ForgetParams>(params)?;- finish(confine::forget(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::forget(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn erase_all(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn erase_all(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<EraseAllParams>(params)?;- finish(ops::erase_all(&load().await?, params).await)+ finish(ops::erase_all(&load(&ctx).await?, params).await)})}-pub(super) fn items_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn items_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<ItemsListParams>(params)?;- finish(confine::items_list(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::items_list(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn explore(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn explore(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<ExploreParams>(params)?;- finish(confine::explore(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::explore(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn items_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn items_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<ItemsGetParams>(params)?;- finish(confine::items_get(&load().await?, &MemoryIdentity::root(), params).await)+ finish(confine::items_get(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn policy_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn policy_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- to_json(views::policy_view(&load().await?))+ to_json(views::policy_view(&load(&ctx).await?))})}-pub(super) fn policy_set(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn policy_set(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<PolicySetParams>(params)?;- let mut config = load().await?;+ let mut config = load(&ctx).await?;views::apply_policy_set(&mut config, ¶ms).map_err(String::from)?;save(&config).await.map_err(String::from)?;to_json(views::policy_view(&config))})}-pub(super) fn pack_preview(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn pack_preview(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<PackPreviewParams>(params)?;- finish(views::pack_preview(&load().await?, &MemoryIdentity::root(), params).await)+ finish(views::pack_preview(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn agents_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn agents_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(views::agents_list(&load().await?, &MemoryIdentity::root()).await)+ finish(views::agents_list(&load(&ctx).await?, &MemoryIdentity::root()).await)})}pub(super) fn conversations_backfill_status(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(backfill::status(&load().await?).await)+ finish(backfill::status(&load(&ctx).await?).await)})}pub(super) fn conversations_backfill_start(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let params = parse::<backfill::BackfillStartParams>(params)?;- finish(backfill::start(&load().await?, params).await)+ finish(backfill::start(&load(&ctx).await?, params).await)})}-pub(super) fn brain_sources(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn brain_sources(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(brain::sources(&load().await?, &MemoryIdentity::root()).await)+ finish(brain::sources(&load(&ctx).await?, &MemoryIdentity::root()).await)})}-pub(super) fn brain_search(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn brain_search(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<brain::BrainSearchParams>(params)?;- finish(brain::search(&load().await?, &MemoryIdentity::root(), params).await)+ finish(brain::search(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn brain_ingest(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn brain_ingest(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<brain::BrainIngestParams>(params)?;- finish(brain::ingest(&load().await?, &MemoryIdentity::root(), params).await)+ finish(brain::ingest(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn brain_forget(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn brain_forget(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<brain::BrainForgetParams>(params)?;- finish(brain::forget(&load().await?, &MemoryIdentity::root(), params).await)+ finish(brain::forget(&load(&ctx).await?, &MemoryIdentity::root(), params).await)})}-pub(super) fn jobs_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn jobs_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- to_json(views::jobs_list(&load().await?).await)+ to_json(views::jobs_list(&load(&ctx).await?).await)})}-pub(super) fn jobs_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn jobs_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<JobsRunParams>(params)?;- finish(views::jobs_run(&load().await?, params).await)+ finish(views::jobs_run(&load(&ctx).await?, params).await)})}-pub(super) fn sources_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn sources_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;to_json(SourcesListView {- sources: sources::list(&load().await?),+ sources: sources::list(&load(&ctx).await?),})})}-pub(super) fn sources_add(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn sources_add(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<SourcesAddParams>(params)?;- let mut config = load().await?;+ let mut config = load(&ctx).await?;let source = sources::apply_add(&mut config, ¶ms).map_err(String::from)?;save(&config).await.map_err(String::from)?;to_json(SourceAddedView {@@ -244,10 +244,10 @@ pub(super) fn sources_add(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont})}-pub(super) fn sources_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn sources_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<SourcesRemoveParams>(params)?;- let mut config = load().await?;+ let mut config = load(&ctx).await?;let Some(removed) = sources::apply_remove(&mut config, ¶ms.id) else {return to_json(SourceRemovedView { removed: false });};@@ -262,26 +262,26 @@ pub(super) fn sources_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> C})}-pub(super) fn sources_sync(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn sources_sync(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<SourcesSyncParams>(params)?;- let config = load().await?;+ let config = load(&ctx).await?;let started = sources::start_sync(&config, params.id.as_deref()).map_err(String::from)?;to_json(SourcesSyncView { started })})}-pub(super) fn import_scan(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn import_scan(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(import::scan(&load().await?).await)+ finish(import::scan(&load(&ctx).await?).await)})}-pub(super) fn import_start(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn import_start(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<ImportStartParams>(params)?;- let config = load().await?;+ let config = load(&ctx).await?;finish(import::start(&config, params.consent).await@@ -290,10 +290,10 @@ pub(super) fn import_start(_ctx: DispatchCtx, params: Map<String, Value>) -> Con})}-pub(super) fn import_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn import_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- let config = load().await?;+ let config = load(&ctx).await?;to_json(json!(ImportStateView {state: import::status(&config)}))@@ -301,12 +301,12 @@ pub(super) fn import_status(_ctx: DispatchCtx, params: Map<String, Value>) -> Co}pub(super) fn import_retry_failed(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- let config = load().await?;+ let config = load(&ctx).await?;finish(import::retry_failed(&config).await@@ -315,17 +315,17 @@ pub(super) fn import_retry_failed(})}-pub(super) fn migration_scan(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn migration_scan(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(layout_migration::scan(&layout_migration::AppHost::new(load().await?)).await)+ finish(layout_migration::scan(&layout_migration::AppHost::new(load(&ctx).await?)).await)})}-pub(super) fn migration_start(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn migration_start(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let params = parse::<layout_migration::StartParams>(params)?;- let config = load().await?;+ let config = load(&ctx).await?;let started = layout_migration::start(config.clone(),std::sync::Arc::new(layout_migration::AppHost::new(config.clone())),@@ -339,16 +339,16 @@ pub(super) fn migration_start(_ctx: DispatchCtx, params: Map<String, Value>) ->})}-pub(super) fn migration_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn migration_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(layout_migration::status(&load().await?))+ finish(layout_migration::status(&load(&ctx).await?))})}-pub(super) fn migration_retry(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn migration_retry(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {parse::<EmptyParams>(params)?;- finish(layout_migration::retry(&load().await?))+ finish(layout_migration::retry(&load(&ctx).await?))})}diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rsindex 9a5312b474..e54fd2b4f7 100644--- a/crates/openhuman-core/src/modules/wallet_host.rs+++ b/crates/openhuman-core/src/modules/wallet_host.rs@@ -5,6 +5,7 @@//! transport, authenticated wallet-backend transport, and a confirmation//! decision bound to an in-flight confirmed execution request.+use crate::core::runtime::DispatchCtx;use std::collections::{HashMap, HashSet};use std::future::Future;use std::sync::{Mutex, OnceLock};@@ -162,7 +163,7 @@ pub(super) fn has_endpoint_reference_for_test(reference: &str) -> bool {pub(crate) async fn wallet_accounts_snapshot() -> Result<tinywallet_bus::wire::WalletAccountsResponse, String> {- let status = crate::web3::wallet::status()+ let status = crate::web3::wallet::status(&DispatchCtx::ambient()).await.map_err(|error| error.to_string())?.value;diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rsindex 9d3ddde56d..fc6076c2b3 100644--- a/crates/openhuman-core/src/modules/wallet_service.rs+++ b/crates/openhuman-core/src/modules/wallet_service.rs@@ -1,5 +1,6 @@//! Serialized, user-scoped access to the module-owned native wallet service.+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::future::Future;use std::path::PathBuf;@@ -231,7 +232,7 @@ async fn signing_secret(tinywallet_bus::wire::WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,tinywallet_bus::wire::WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,};- let stored = crate::web3::wallet::secret_material(local_chain)+ let stored = crate::web3::wallet::secret_material(&DispatchCtx::ambient(), local_chain).await.map_err(WalletCallError::Failed)?;let mnemonic =diff --git a/crates/openhuman-core/src/modules/web3_service.rs b/crates/openhuman-core/src/modules/web3_service.rsindex 452496055f..4c71f7197d 100644--- a/crates/openhuman-core/src/modules/web3_service.rs+++ b/crates/openhuman-core/src/modules/web3_service.rs@@ -1,5 +1,6 @@//! User-scoped lifecycle and host transport for TinyWallet Web3 quotes.+use crate::core::runtime::DispatchCtx;use std::collections::HashMap;use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};@@ -245,7 +246,7 @@ pub(crate) async fn execute(WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,};- let stored = crate::web3::wallet::secret_material(chain)+ let stored = crate::web3::wallet::secret_material(&DispatchCtx::ambient(), chain).await.map_err(|error| wallet::WalletCallError::Failed(error.to_string()))?;let mnemonic =diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rsindex e216b3bf60..f5b58a4220 100644--- a/crates/openhuman-core/src/modules/x402_service.rs+++ b/crates/openhuman-core/src/modules/x402_service.rs@@ -1,5 +1,6 @@//! User-scoped lifecycle for the module-owned x402 ledger.+use crate::core::runtime::DispatchCtx;use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::OnceLock;@@ -77,7 +78,7 @@ async fn signing_secret(config: &Config,chain: crate::web3::wallet::WalletChain,) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {- let stored = crate::web3::wallet::secret_material(chain)+ let stored = crate::web3::wallet::secret_material(&DispatchCtx::ambient(), chain).await.map_err(WalletCallError::Failed)?;let phrase =diff --git a/crates/openhuman-core/src/platform/socket/schemas.rs b/crates/openhuman-core/src/platform/socket/schemas.rsindex 46a629c01d..467bf66a94 100644--- a/crates/openhuman-core/src/platform/socket/schemas.rs+++ b/crates/openhuman-core/src/platform/socket/schemas.rs@@ -233,10 +233,10 @@ fn handle_emit(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur})}-fn handle_connect_with_session(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+fn handle_connect_with_session(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let mgr = require_manager()?;- let state = super::ops::connect_with_session(mgr).await?;+ let state = super::ops::connect_with_session(&ctx, mgr).await?;Ok(status_payload(&state))})}diff --git a/crates/openhuman-core/src/platform/update/ops.rs b/crates/openhuman-core/src/platform/update/ops.rsindex 4f3c0edf77..efc4fd25d9 100644--- a/crates/openhuman-core/src/platform/update/ops.rs+++ b/crates/openhuman-core/src/platform/update/ops.rs@@ -17,8 +17,8 @@ async fn load_update_policy(ctx: &DispatchCtx, ) -> Result<UpdateConfig, String>.map_err(|err| format!("failed to load config for update policy: {err}"))}-async fn enforce_update_mutation_policy(method: &str) -> Result<UpdateConfig, String> {- let policy = load_update_policy().await.map_err(|err| {+async fn enforce_update_mutation_policy(ctx: &DispatchCtx, method: &str) -> Result<UpdateConfig, String> {+ let policy = load_update_policy(&ctx).await.map_err(|err| {let message = format!("{method} blocked: {err}; failing closed because update policy could not be loaded");@@ -178,9 +178,9 @@ pub async fn update_version() -> Outcome<Value> {/// update was applied the function publishes a restart request before/// returning, so the caller will see `restart_requested: true` and the/// core process will exit shortly afterwards.-pub async fn update_run() -> Outcome<Value> {+pub async fn update_run(ctx: &DispatchCtx, ) -> Outcome<Value> {log::info!("[update:rpc] update_run invoked");- let policy = match enforce_update_mutation_policy("openhuman.update_run").await {+ let policy = match enforce_update_mutation_policy(&ctx, "openhuman.update_run").await {Ok(policy) => policy,Err(error) => {return Outcome::single_log(@@ -342,7 +342,7 @@ fn validate_asset_name(name: &str) -> Result<(), String> {/// - `asset_name` (string, required): must be a safe filename starting with `openhuman-core-`./// - `staging_dir` (string, optional): ignored — always uses the default staging directory/// for security (next to the running executable or Resources/).-pub async fn update_apply(+pub async fn update_apply(ctx: &DispatchCtx,download_url: String,asset_name: String,_staging_dir: Option<String>,@@ -352,7 +352,7 @@ pub async fn update_apply(download_url,asset_name,);- let policy = match enforce_update_mutation_policy("openhuman.update_apply").await {+ let policy = match enforce_update_mutation_policy(&ctx, "openhuman.update_apply").await {Ok(policy) => policy,Err(error) => {return Outcome::single_log(diff --git a/crates/openhuman-core/src/platform/update/ops_tests.rs b/crates/openhuman-core/src/platform/update/ops_tests.rsindex 8e36b63efd..72c335744a 100644--- a/crates/openhuman-core/src/platform/update/ops_tests.rs+++ b/crates/openhuman-core/src/platform/update/ops_tests.rs@@ -10,6 +10,7 @@//! - `build_run_result_from_staged_update` sets `restart_requested = false`//! under the `Supervisor` strategy.+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::UpdateRestartStrategy;use crate::platform::update::types::{UpdateApplyResult, UpdateInfo};@@ -235,7 +236,7 @@ async fn update_run_rejected_when_rpc_mutations_disabled() {cfg.save().await.expect("save config");std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());- let outcome = update_run().await;+ let outcome = update_run(&DispatchCtx::process_default()).await;std::env::remove_var("OPENHUMAN_WORKSPACE");diff --git a/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs b/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rsindex 7e1b90e048..4cf0be231a 100644--- a/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs+++ b/crates/openhuman-core/src/platform/update/ops_tests_2_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::test_env::EnvVarGuard;use crate::config::TEST_ENV_LOCK;@@ -101,7 +102,7 @@ fn validate_asset_name_rejects_unprefixed_asset() {#[tokio::test]async fn update_apply_rejects_non_github_url_before_network_call() {let _guard = TEST_ENV_LOCK.lock().await;- let outcome = update_apply(+ let outcome = update_apply(&DispatchCtx::process_default(),"https://evil.example.com/asset".to_string(),"openhuman-core-x86_64.tar.gz".to_string(),None,@@ -117,7 +118,7 @@ async fn update_apply_rejects_non_github_url_before_network_call() {#[tokio::test]async fn update_apply_rejects_unsafe_asset_name() {let _guard = TEST_ENV_LOCK.lock().await;- let outcome = update_apply(+ let outcome = update_apply(&DispatchCtx::process_default(),"https://github.com/owner/repo/releases/download/v1/x".to_string(),"../etc/passwd".to_string(),None,@@ -144,7 +145,7 @@ async fn update_apply_rejects_when_rpc_mutations_disabled() {).await;- let outcome = update_apply(+ let outcome = update_apply(&DispatchCtx::process_default(),"https://github.com/owner/repo/releases/download/v1/x".to_string(),"openhuman-core-x86_64.tar.gz".to_string(),None,diff --git a/crates/openhuman-core/src/platform/update/schemas.rs b/crates/openhuman-core/src/platform/update/schemas.rsindex 103301a1bc..fdf9f3d23a 100644--- a/crates/openhuman-core/src/platform/update/schemas.rs+++ b/crates/openhuman-core/src/platform/update/schemas.rs@@ -130,11 +130,11 @@ fn handle_check(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFutBox::pin(async { to_json(crate::platform::update::rpc::update_check().await) })}-fn handle_run(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async { to_json(crate::platform::update::rpc::update_run().await) })+fn handle_run(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(crate::platform::update::rpc::update_run(&ctx).await) })}-fn handle_apply(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_apply(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let download_url = params.get("download_url")@@ -152,7 +152,7 @@ fn handle_apply(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu.map(|s| s.to_string());to_json(- crate::platform::update::rpc::update_apply(download_url, asset_name, staging_dir).await,+ crate::platform::update::rpc::update_apply(&ctx, download_url, asset_name, staging_dir).await,)})}diff --git a/crates/openhuman-core/src/profiles/host_tests.rs b/crates/openhuman-core/src/profiles/host_tests.rsindex f8fc1af08e..098eb6683d 100644--- a/crates/openhuman-core/src/profiles/host_tests.rs+++ b/crates/openhuman-core/src/profiles/host_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;fn host(tmp: &tempfile::TempDir, max_open: usize, idle_secs: u64) -> ProfileHost {@@ -395,7 +396,7 @@ async fn the_operators_cron_limits_bind_every_profile_whatever_its_config_says()let forced = host.provisioned_config(&id).await.unwrap();let opened = host.open(&id).await.unwrap();let loaded = CoreContext::scope(Arc::clone(opened.context()), async {- crate::config::ops::load_current_or_init().await.unwrap()+ crate::config::ops::load_current_or_init(&DispatchCtx::process_default()).await.unwrap()}).await;for config in [&forced, &opened.config, &loaded] {diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rsindex 51b4e9ee1d..80ade801dc 100644--- a/crates/openhuman-core/src/sandbox/ops.rs+++ b/crates/openhuman-core/src/sandbox/ops.rs@@ -286,14 +286,14 @@ fn docker_error_handle() -> SandboxBackendHandle {////// Returns the sandboxed execution result. The caller (typically the/// shell tool) is responsible for converting this into a `ToolResult`.-pub async fn execute_in_sandbox(+pub async fn execute_in_sandbox(ctx: &DispatchCtx,policy: &SandboxPolicy,command: &str,working_dir: &Path,extra_env: HashMap<OsString, OsString>,timeout: Duration,) -> anyhow::Result<SandboxExecResult> {- execute_in_sandbox_metered(policy, command, working_dir, extra_env, timeout, None).await+ execute_in_sandbox_metered(&ctx, policy, command, working_dir, extra_env, timeout, None).await}/// [`execute_in_sandbox`] that feeds `meter` with the command's output as itdiff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rsindex e225b222ce..1c0083c24c 100644--- a/crates/openhuman-core/src/sandbox/ops_tests.rs+++ b/crates/openhuman-core/src/sandbox/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::RuntimeConfig;@@ -94,7 +95,7 @@ async fn create_sandbox_backend_none() {&RuntimeConfig::default(),false,);- let handle = create_sandbox_backend(&policy).await;+ let handle = create_sandbox_backend(&DispatchCtx::process_default(), &policy).await;assert_eq!(handle.kind, SandboxBackendKind::None);assert_eq!(handle.status, SandboxStatus::Ready);}@@ -206,7 +207,7 @@ async fn execute_in_sandbox_none_backend() {&RuntimeConfig::default(),false,);- let result = execute_in_sandbox(+ let result = execute_in_sandbox(&DispatchCtx::process_default(),&policy,"echo sandbox-test",Path::new("/tmp"),@@ -281,7 +282,7 @@ async fn execute_in_sandbox_none_backend_runs_on_every_os() {&RuntimeConfig::default(),false,);- let result = execute_in_sandbox(+ let result = execute_in_sandbox(&DispatchCtx::process_default(),&policy,"echo sandbox-test",tempdir.path(),@@ -354,7 +355,7 @@ async fn sandbox_off_component_forces_the_unsandboxed_fallback_and_no_module_loacrate::core::runtime::context::CoreContext::scope(ctx, async {assert!(sandbox_component_off());assert!(sandbox_disabled_by_host());- assert!(!command_requires_sandbox(Some(SandboxMode::Sandboxed))+ assert!(!command_requires_sandbox(&ctx, Some(SandboxMode::Sandboxed)).await.unwrap());})diff --git a/crates/openhuman-core/src/search/tools.rs b/crates/openhuman-core/src/search/tools.rsindex 76aa8e7137..959f115c8e 100644--- a/crates/openhuman-core/src/search/tools.rs+++ b/crates/openhuman-core/src/search/tools.rs@@ -245,7 +245,7 @@ impl Tool for TinySearchTool {args: Value,options: ToolCallOptions,) -> anyhow::Result<ToolResult> {- let config = self.live_config().await?;+ let config = self.live_config(&DispatchCtx::ambient()).await?;// Re-read per call, so a key added or a provider switched mid-session// clears an earlier refusal instead of outliving it.let signature = self.provider_signature(&config);diff --git a/crates/openhuman-core/src/security/approval/rpc.rs b/crates/openhuman-core/src/security/approval/rpc.rsindex 401674d190..2c716e2e02 100644--- a/crates/openhuman-core/src/security/approval/rpc.rs+++ b/crates/openhuman-core/src/security/approval/rpc.rs@@ -3,6 +3,7 @@//! Exposed as `approval_list_pending` and `approval_decide` through//! the controller registry (see [`super::schemas`]).+use crate::core::runtime::DispatchCtx;use anyhow::anyhow;use crate::core::Outcome;@@ -201,7 +202,7 @@ pub async fn approval_preauthorize_flow(/// Apply a decision to a pending row. Errors when the request id is/// unknown / already decided / belongs to a different session. With/// `agent_id`, also errors when the request belongs to another agent.-pub async fn approval_decide(+pub async fn approval_decide(ctx: &DispatchCtx,request_id: &str,decision: ApprovalDecision,agent_id: Option<&str>,@@ -292,7 +293,7 @@ pub async fn approval_decide(row.tool_name));} else if decision == ApprovalDecision::ApproveAlwaysForTool {- match crate::config::ops::add_auto_approve_tool(&row.tool_name).await {+ match crate::config::ops::add_auto_approve_tool(&ctx, &row.tool_name).await {Ok(()) => {tracing::info!(tool = row.tool_name.as_str(),diff --git a/crates/openhuman-core/src/security/approval/schemas.rs b/crates/openhuman-core/src/security/approval/schemas.rsindex 07d362067c..fb81a4dccf 100644--- a/crates/openhuman-core/src/security/approval/schemas.rs+++ b/crates/openhuman-core/src/security/approval/schemas.rs@@ -209,7 +209,7 @@ fn handle_get_gate_state(_ctx: DispatchCtx, _params: Map<String, Value>) -> Cont})}-fn handle_decide(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_decide(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let request_id = read_required_string(¶ms, "request_id")?;let decision_str = read_required_string(¶ms, "decision")?;@@ -221,7 +221,7 @@ fn handle_decide(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut})?;let agent_id = read_optional_string(¶ms, "agent_id")?;let outcome =- approval_rpc::approval_decide(request_id.trim(), decision, agent_id.as_deref())+ approval_rpc::approval_decide(&ctx, request_id.trim(), decision, agent_id.as_deref()).await.map_err(|e| e.to_string())?;to_json(outcome)diff --git a/crates/openhuman-core/src/security/credentials/bus.rs b/crates/openhuman-core/src/security/credentials/bus.rsindex 5ecf5d4192..31a208be6c 100644--- a/crates/openhuman-core/src/security/credentials/bus.rs+++ b/crates/openhuman-core/src/security/credentials/bus.rs@@ -56,7 +56,7 @@ impl EventHandler<DomainEvent> for SessionExpiredSubscriber {}async fn handle(&self, event: &DomainEvent) {- self.handle_with(crate::core::runtime::is_saas(), event)+ self.handle_with(&DispatchCtx::ambient(), crate::core::runtime::is_saas(), event).await;}}@@ -130,7 +130,7 @@ impl SessionExpiredSubscriber {// loaded config; if the config can't load (rare — disk issue),// we've at least pinned the scheduler gate so background work// can't make things worse.- if let Err(err) = crate::security::credentials::rpc::clear_session(&config).await {+ if let Err(err) = crate::security::credentials::rpc::clear_session(&ctx, &config).await {tracing::warn!(source = %source,error = %err,diff --git a/crates/openhuman-core/src/security/credentials/bus_tests.rs b/crates/openhuman-core/src/security/credentials/bus_tests.rsindex 71a5a9a897..6f2379b3d7 100644--- a/crates/openhuman-core/src/security/credentials/bus_tests.rs+++ b/crates/openhuman-core/src/security/credentials/bus_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;#[test]@@ -37,7 +38,7 @@ async fn session_expired_in_saas_returns_before_any_teardown() {// in SaaS it must return at once, leaving the gate untouched.tokio::time::timeout(std::time::Duration::from_secs(1),- s.handle_with(+ s.handle_with(&DispatchCtx::process_default(),true,&DomainEvent::SessionExpired {source: "test".into(),diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env.rsindex 1877a98fe8..ae275bb18d 100644--- a/crates/openhuman-core/src/security/credentials/ops/boot_env.rs+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env.rs@@ -11,6 +11,7 @@//! a fresh install and is otherwise ignored, so rotating it means clearing the//! stored one first (`openhuman-core auth clear_credential`).+use crate::core::runtime::DispatchCtx;use crate::config::Config;use crate::security::credentials::api_key;use crate::security::credentials::session_support::{get_session_token, CredentialKind};@@ -49,7 +50,7 @@ pub fn seed_api_key_from_env(config: &Config) {/// Install the session JWT from `OPENHUMAN_BACKEND_SESSION_TOKEN` when no/// session is stored. Runs the full `set_credential` path (user-dir/// activation, gated services, scheduler gate), so it is async.-pub async fn seed_session_from_env(config: &Config) {+pub async fn seed_session_from_env(ctx: &DispatchCtx, config: &Config) {let Some(token) = env_secret(BACKEND_SESSION_TOKEN_ENV) else {return;};@@ -64,7 +65,7 @@ pub async fn seed_session_from_env(config: &Config) {user: None,issuing_backend: None,};- match set_credential(config, request).await {+ match set_credential(&ctx, config, request).await {Ok(outcome) => log::info!("[auth][boot] session installed from {BACKEND_SESSION_TOKEN_ENV} (user_id={})",outcome.value.user_id.as_deref().unwrap_or("?")diff --git a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rsindex fe6be4830e..de3bb081ed 100644--- a/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops/boot_env_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::test_env::EnvVarGuard;use crate::config::Config;@@ -50,12 +51,12 @@ async fn session_env_is_ignored_without_a_subject_and_when_unset() {let _guard = EnvVarGuard::unset(BACKEND_SESSION_TOKEN_ENV);unsafe { std::env::remove_var(BACKEND_SESSION_TOKEN_ENV) };- seed_session_from_env(&config).await;+ seed_session_from_env(&DispatchCtx::process_default(), &config).await;assert!(get_session_token(&config).unwrap().is_none());// An opaque token has no subject claim and no host to supply one, so the// install is refused (logged) and the store stays empty.unsafe { std::env::set_var(BACKEND_SESSION_TOKEN_ENV, "opaque-token") };- seed_session_from_env(&config).await;+ seed_session_from_env(&DispatchCtx::process_default(), &config).await;assert!(get_session_token(&config).unwrap().is_none());}diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rsindex de0347979e..85df58c7ee 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@ -181,7 +181,7 @@ fn resolve(request: SetCredentialRequest) -> Result<Resolved, String> {/// no purge, no service restart). A **different user** than the one stored is/// signed out first so `active_user.toml` never points at one user while/// another's profile exists.-pub async fn set_credential(+pub async fn set_credential(ctx: &DispatchCtx,config: &Config,request: SetCredentialRequest,) -> Result<Outcome<AuthStateResponse>, String> {@@ -270,7 +270,7 @@ pub async fn set_credential(operation = "set_credential","{LOG_PREFIX} credential names a different user than the stored one; clearing the previous session first");- let cleared = clear_session_credential(config).await?;+ let cleared = clear_session_credential(&ctx, config).await?;logs.extend(cleared.logs);}metadata.insert("user_id".to_string(), user_id.clone());@@ -297,9 +297,9 @@ pub async fn set_credential(logs.extend(activate_user_scope(&user_id)?);// Reload so auth-profiles.json, the encryption key and the workspace// resolve to the user-scoped location before the profile is written.- let effective = reload_config_or(config).await?;+ let effective = reload_config_or(&ctx, config).await?;if resolved.kind == CredentialKind::Local {- match crate::config::ops::set_onboarding_completed(false).await {+ match crate::config::ops::set_onboarding_completed(&ctx, false).await {Ok(_) => {logs.push("onboarding left incomplete for local session setup".to_string())}@@ -377,7 +377,7 @@ pub async fn set_credential(/// Remove the stored credential of `kind` — or every credential when `None`./// A session (or local) removal runs the sign-out teardown; an API-key removal/// only closes the scheduler gate when no other credential remains.-pub async fn clear_credential(+pub async fn clear_credential(ctx: &DispatchCtx,config: &Config,kind: Option<CredentialKind>,) -> Result<Outcome<Value>, String> {@@ -412,14 +412,14 @@ pub async fn clear_credential(kind,None | Some(CredentialKind::Session) | Some(CredentialKind::Local)) {- let outcome = clear_session_credential(config).await?;+ let outcome = clear_session_credential(&ctx, config).await?;removed_session = outcome.value;logs.extend(outcome.logs);if removed_session {// Follow the same process globals the teardown just rebound to,// so the api-key checks below agree with `auth.get_state`.- effective_config = reload_config_or(config).await?;+ effective_config = reload_config_or(&ctx, config).await?;if let Some(key) = source_api_key.as_deref() {if matches!(kind,@@ -573,13 +573,13 @@ async fn clear_session_credential(ctx: &DispatchCtx, config: &Config) -> Result</// Historical entry point: install a session (or local) credential from a/// bare token. Same as [`set_credential`] with the kind classified by shape.-pub async fn store_session(+pub async fn store_session(ctx: &DispatchCtx,config: &Config,token: &str,user_id: Option<String>,user: Option<Value>,) -> Result<Outcome<AuthStateResponse>, String> {- set_credential(+ set_credential(&ctx,config,SetCredentialRequest {token: token.to_string(),@@ -594,8 +594,8 @@ pub async fn store_session(/// Historical entry point: sign the session out. Same as/// [`clear_credential`] for the session kind.-pub async fn clear_session(config: &Config) -> Result<Outcome<Value>, String> {- clear_credential(config, Some(CredentialKind::Session)).await+pub async fn clear_session(ctx: &DispatchCtx, config: &Config) -> Result<Outcome<Value>, String> {+ clear_credential(&ctx, config, Some(CredentialKind::Session)).await}/// A process-wide credential is a single-user concept: installing onediff --git a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rsindex adac89a47a..88859358e4 100644--- a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::security::credentials::api_key;@@ -19,7 +20,7 @@ async fn same_token_refresh_preserves_issuing_backend_and_refuses_rebinding() {true,).unwrap();- let state = set_credential(+ let state = set_credential(&DispatchCtx::process_default(),&config,SetCredentialRequest {token: "synthetic-session".into(),@@ -34,7 +35,7 @@ async fn same_token_refresh_preserves_issuing_backend_and_refuses_rebinding() {state.issuing_backend.as_deref(),Some("https://issuer.example"));- let error = set_credential(+ let error = set_credential(&DispatchCtx::process_default(),&config,SetCredentialRequest {token: "synthetic-session".into(),@@ -96,9 +97,9 @@ async fn decrypt_secret_round_trips_noise_through_migrate_path() {async fn set_credential_rejects_empty_or_whitespace_token() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- let err = store_session(&config, "", None, None).await.unwrap_err();+ let err = store_session(&DispatchCtx::process_default(), &config, "", None, None).await.unwrap_err();assert!(err.contains("token is required"));- let err = store_session(&config, " ", None, None).await.unwrap_err();+ let err = store_session(&DispatchCtx::process_default(), &config, " ", None, None).await.unwrap_err();assert!(err.contains("token is required"));}@@ -106,7 +107,7 @@ async fn set_credential_rejects_empty_or_whitespace_token() {async fn set_credential_rejects_unknown_kind() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- let err = set_credential(+ let err = set_credential(&DispatchCtx::process_default(),&config,SetCredentialRequest {token: "x".into(),@@ -127,7 +128,7 @@ async fn set_credential_rejects_an_expired_jwt_without_storing() {"sub": "user-1","exp": (chrono::Utc::now() - chrono::Duration::hours(1)).timestamp()}));- let err = store_session(&config, &token, None, None)+ let err = store_session(&DispatchCtx::process_default(), &config, &token, None, None).await.unwrap_err();assert!(err.starts_with("CREDENTIAL_EXPIRED:"), "{err}");@@ -146,11 +147,11 @@ async fn set_credential_requires_a_user_id_for_a_session() {let token = jwt_with_payload(json!({"exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp()}));- let err = store_session(&config, &token, None, None)+ let err = store_session(&DispatchCtx::process_default(), &config, &token, None, None).await.unwrap_err();assert!(err.contains("userId required"), "{err}");- let err = store_session(+ let err = store_session(&DispatchCtx::process_default(),&config,"opaque-token",None,@@ -175,7 +176,7 @@ async fn set_credential_installs_a_session_without_touching_the_backend() {let exp = chrono::Utc::now() + chrono::Duration::hours(1);let token = jwt_with_payload(json!({ "sub": "user-42", "exp": exp.timestamp() }));- let result = store_session(+ let result = store_session(&DispatchCtx::process_default(),&config,&token,None,@@ -222,14 +223,14 @@ async fn set_credential_derives_the_user_id_from_the_jwt_subject() {"sub": "from-claims","exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp()}));- let state = store_session(&config, &token, None, None)+ let state = store_session(&DispatchCtx::process_default(), &config, &token, None, None).await.unwrap().value;assert_eq!(state.user_id.as_deref(), Some("from-claims"));// Explicit userId wins over the claim; the user payload's id wins over// the claim too.- let state = store_session(&config, &token, Some("explicit".into()), None)+ let state = store_session(&DispatchCtx::process_default(), &config, &token, Some("explicit".into()), None).await.unwrap().value;@@ -247,7 +248,7 @@ async fn set_credential_with_the_same_token_and_user_is_a_cheap_refresh() {"sub": "user-7","exp": (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp()}));- let first = store_session(+ let first = store_session(&DispatchCtx::process_default(),&config,&token,None,@@ -259,7 +260,7 @@ async fn set_credential_with_the_same_token_and_user_is_a_cheap_refresh() {// The host's `/auth/me` answer arrives: same token, same user.let user_config = crate::config::load_config_with_timeout().await.unwrap();- let second = store_session(+ let second = store_session(&DispatchCtx::process_default(),&user_config,&token,None,@@ -287,7 +288,7 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first()let _home = EnvVarGuard::set("HOME", tmp.path());let config = test_config(&tmp);let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp();- store_session(+ store_session(&DispatchCtx::process_default(),&config,&jwt_with_payload(json!({ "sub": "alice", "exp": exp })),None,@@ -296,7 +297,7 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first().await.unwrap();let alice_config = crate::config::load_config_with_timeout().await.unwrap();- let result = store_session(+ let result = store_session(&DispatchCtx::process_default(),&alice_config,&jwt_with_payload(json!({ "sub": "bob", "exp": exp })),None,@@ -327,7 +328,7 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first()async fn set_and_clear_api_key_credential() {let tmp = TempDir::new().unwrap();let config = test_config(&tmp);- let state = set_credential(+ let state = set_credential(&DispatchCtx::process_default(),&config,SetCredentialRequest {token: "sk-live".into(),@@ -342,7 +343,7 @@ async fn set_and_clear_api_key_credential() {assert_eq!(state.credential.as_deref(), Some("api-key"));assert!(state.user_id.is_none());- let cleared = clear_credential(&config, Some(session_support::CredentialKind::ApiKey))+ let cleared = clear_credential(&DispatchCtx::process_default(), &config, Some(session_support::CredentialKind::ApiKey)).await.unwrap().value;@@ -371,14 +372,14 @@ async fn clearing_the_session_preserves_a_coexisting_api_key() {// Install the session first: this activates the user-scoped directory.let exp = chrono::Utc::now() + chrono::Duration::hours(1);let token = jwt_with_payload(json!({ "sub": "user-42", "exp": exp.timestamp() }));- store_session(&config, &token, None, Some(json!({ "id": "user-42" })))+ store_session(&DispatchCtx::process_default(), &config, &token, None, Some(json!({ "id": "user-42" }))).await.unwrap();// Store the API key against the now-active user-scoped config, exactly// as the dispatcher would for a follow-up `auth.set_credential` call.let user_scoped = crate::config::load_config_with_timeout().await.unwrap();- set_credential(+ set_credential(&DispatchCtx::process_default(),&user_scoped,SetCredentialRequest {token: "sk-live".into(),@@ -394,7 +395,7 @@ async fn clearing_the_session_preserves_a_coexisting_api_key() {);// Sign the session out only — the API key must not be cleared.- let cleared = clear_credential(&user_scoped, Some(session_support::CredentialKind::Session))+ let cleared = clear_credential(&DispatchCtx::process_default(), &user_scoped, Some(session_support::CredentialKind::Session)).await.unwrap().value;@@ -448,7 +449,7 @@ async fn clearing_the_session_preserves_the_active_key_over_a_stale_destination_// Key A already sits at the real pre-login/signed-out scope — e.g. left// over from an earlier api-key-only run before any session existed.let pre_login = crate::config::load_config_with_timeout().await.unwrap();- set_credential(+ set_credential(&DispatchCtx::process_default(),&pre_login,SetCredentialRequest {token: "sk-stale-a".into(),@@ -467,13 +468,13 @@ async fn clearing_the_session_preserves_the_active_key_over_a_stale_destination_// from the pre-login one key A lives beside.let exp = chrono::Utc::now() + chrono::Duration::hours(1);let token = jwt_with_payload(json!({ "sub": "user-99", "exp": exp.timestamp() }));- store_session(&pre_login, &token, None, Some(json!({ "id": "user-99" })))+ store_session(&DispatchCtx::process_default(), &pre_login, &token, None, Some(json!({ "id": "user-99" }))).await.unwrap();// Key B is the one actually active while the session is up.let user_scoped = crate::config::load_config_with_timeout().await.unwrap();- set_credential(+ set_credential(&DispatchCtx::process_default(),&user_scoped,SetCredentialRequest {token: "sk-live-b".into(),@@ -490,7 +491,7 @@ async fn clearing_the_session_preserves_the_active_key_over_a_stale_destination_// A session-only clear must preserve key B as the effective credential,// not let the stale key A at the destination win by default.- clear_credential(&user_scoped, Some(session_support::CredentialKind::Session))+ clear_credential(&DispatchCtx::process_default(), &user_scoped, Some(session_support::CredentialKind::Session)).await.unwrap();@@ -519,12 +520,12 @@ async fn clearing_without_a_kind_removes_a_user_scoped_api_key_at_its_source() {let exp = chrono::Utc::now() + chrono::Duration::hours(1);let token = jwt_with_payload(json!({ "sub": "user-77", "exp": exp.timestamp() }));- store_session(&config, &token, None, Some(json!({ "id": "user-77" })))+ store_session(&DispatchCtx::process_default(), &config, &token, None, Some(json!({ "id": "user-77" }))).await.unwrap();let user_scoped = crate::config::load_config_with_timeout().await.unwrap();- set_credential(+ set_credential(&DispatchCtx::process_default(),&user_scoped,SetCredentialRequest {token: "sk-live".into(),@@ -536,7 +537,7 @@ async fn clearing_without_a_kind_removes_a_user_scoped_api_key_at_its_source() {.unwrap();assert!(api_key::has_api_key(&user_scoped));- let cleared = clear_credential(&user_scoped, None).await.unwrap().value;+ let cleared = clear_credential(&DispatchCtx::process_default(), &user_scoped, None).await.unwrap().value;assert_eq!(cleared["removed"], true);assert_eq!(cleared["removedSession"], true);assert_eq!(@@ -568,7 +569,7 @@ async fn clear_credential_without_a_kind_removes_everything() {std::fs::create_dir_all(tmp.path().join("workspace")).unwrap();let _home = EnvVarGuard::set("HOME", tmp.path());let config = test_config(&tmp);- set_credential(+ set_credential(&DispatchCtx::process_default(),&config,SetCredentialRequest {token: "sk-live".into(),@@ -578,7 +579,7 @@ async fn clear_credential_without_a_kind_removes_everything() {).await.unwrap();- let cleared = clear_credential(&config, None).await.unwrap().value;+ let cleared = clear_credential(&DispatchCtx::process_default(), &config, None).await.unwrap().value;assert_eq!(cleared["removed"], true);assert_eq!(cleared["removedApiKey"], true);assert!(@@ -603,7 +604,7 @@ async fn store_session_local_token_rejects_missing_user_payload() {let _home = EnvVarGuard::set("HOME", tmp.path());let config = test_config(&tmp);let local_token = "header.payload.local";- let err = store_session(&config, local_token, None, None)+ let err = store_session(&DispatchCtx::process_default(), &config, local_token, None, None).await.unwrap_err();assert!(@@ -630,7 +631,7 @@ async fn store_session_local_token_succeeds_without_network_and_forces_local_use"email": "[email protected]"});// Pass a different user_id to verify it is overridden.- let result = store_session(+ let result = store_session(&DispatchCtx::process_default(),&config,local_token,Some("should-be-overridden".to_string()),diff --git a/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs b/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rsindex 50ea6e28c9..0e94351f21 100644--- a/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs+++ b/crates/openhuman-core/src/security/credentials/ops_provider_oauth_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;// ── clear_session ──────────────────────────────────────────────@@ -14,7 +15,7 @@ async fn clear_session_on_empty_store_reports_removed_false() {let tmp = TempDir::new().unwrap();let _home = EnvVarGuard::set("HOME", tmp.path());let config = test_config(&tmp);- let result = clear_session(&config).await.unwrap();+ let result = clear_session(&DispatchCtx::process_default(), &config).await.unwrap();assert_eq!(result.value["removed"], false);}@@ -398,7 +399,7 @@ async fn clear_session_on_one_account_does_not_affect_another() {.unwrap();// Clearing the session for account A must not wipe account B's credentials.- clear_session(&config_a).await.unwrap();+ clear_session(&DispatchCtx::process_default(), &config_a).await.unwrap();let listed_b = list_provider_credentials(&config_b, None).awaitdiff --git a/crates/openhuman-core/src/security/credentials/schemas.rs b/crates/openhuman-core/src/security/credentials/schemas.rsindex 2f1d1319c5..d0f1cb1168 100644--- a/crates/openhuman-core/src/security/credentials/schemas.rs+++ b/crates/openhuman-core/src/security/credentials/schemas.rs@@ -198,7 +198,7 @@ fn handle_auth_set_credential(ctx: DispatchCtx, params: Map<String, Value>) -> Clet config = ctx.load_config().await?;let payload =deserialize_params::<crate::security::credentials::SetCredentialRequest>(params)?;- to_json(crate::security::credentials::rpc::set_credential(&config, payload).await?)+ to_json(crate::security::credentials::rpc::set_credential(&ctx, &config, payload).await?)})}@@ -218,7 +218,7 @@ fn handle_auth_clear_credential(ctx: DispatchCtx, params: Map<String, Value>) ->),None => None,};- to_json(crate::security::credentials::rpc::clear_credential(&config, kind).await?)+ to_json(crate::security::credentials::rpc::clear_credential(&ctx, &config, kind).await?)})}diff --git a/crates/openhuman-core/src/security/devices/bus.rs b/crates/openhuman-core/src/security/devices/bus.rsindex 96eaa9a322..ac93119215 100644--- a/crates/openhuman-core/src/security/devices/bus.rs+++ b/crates/openhuman-core/src/security/devices/bus.rs@@ -95,11 +95,11 @@ impl EventHandler<DomainEvent> for DeviceTunnelSubscriber {.unwrap_or_else(std::sync::PoisonError::into_inner).get(channel_id.as_str()).cloned();- match super::owner::owner_of(channel_id, pending.as_ref()).await {+ match super::owner::owner_of(&DispatchCtx::ambient(), channel_id, pending.as_ref()).await {Ok(owner) => {let handled = crate::storage::agents::within_agent(owner.as_deref(),- handle_tunnel_frame(channel_id, payload_b64),+ handle_tunnel_frame(&DispatchCtx::ambient(), channel_id, payload_b64),).await;// Fail closed: no context can act for the owner.diff --git a/crates/openhuman-core/src/security/devices/owner.rs b/crates/openhuman-core/src/security/devices/owner.rsindex 427dc06fc7..61693bafff 100644--- a/crates/openhuman-core/src/security/devices/owner.rs+++ b/crates/openhuman-core/src/security/devices/owner.rs@@ -95,7 +95,7 @@ async fn is_revoked(ctx: &DispatchCtx, channel_id: &str) -> Result<bool, String>////// [`OwnerLookupFailed`] when no scope has the device and at least one/// scope's lookup failed.-pub(super) async fn owner_of(+pub(super) async fn owner_of(ctx: &DispatchCtx,channel_id: &str,pending: Option<&PairingSession>,) -> Result<Option<String>, OwnerLookupFailed> {@@ -110,7 +110,7 @@ pub(super) async fn owner_of(return Ok(session.agent.clone());}let revoked =- crate::storage::agents::within_agent(session.agent.as_deref(), is_revoked(channel_id))+ crate::storage::agents::within_agent(session.agent.as_deref(), is_revoked(&ctx, channel_id)).await;return match revoked {Some(Ok(false)) => Ok(session.agent.clone()),@@ -129,7 +129,7 @@ pub(super) async fn owner_of(};}if let Some(owner) = cached(channel_id) {- match crate::storage::agents::within_agent(owner.as_deref(), has_live_device(channel_id))+ match crate::storage::agents::within_agent(owner.as_deref(), has_live_device(&ctx, channel_id)).await{Some(Ok(true)) => return Ok(owner),@@ -143,7 +143,7 @@ pub(super) async fn owner_of(}}let lookups =- crate::storage::agents::for_each_scope("device owner", || has_live_device(channel_id))+ crate::storage::agents::for_each_scope("device owner", || has_live_device(&ctx, channel_id)).await;let owner = decide(lookups)?;if let Some(owner) = &owner {diff --git a/crates/openhuman-core/src/security/devices/owner_tests.rs b/crates/openhuman-core/src/security/devices/owner_tests.rsindex d41eb37aac..6f0c1a9aa7 100644--- a/crates/openhuman-core/src/security/devices/owner_tests.rs+++ b/crates/openhuman-core/src/security/devices/owner_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;fn session(agent: Option<&str>) -> PairingSession {@@ -15,14 +16,14 @@ fn session(agent: Option<&str>) -> PairingSession {async fn a_pending_pairing_names_its_agent() {let pending = session(Some("agent-7"));assert_eq!(- owner_of("owner-test-pending", Some(&pending))+ owner_of(&DispatchCtx::process_default(), "owner-test-pending", Some(&pending)).await.unwrap().as_deref(),Some("agent-7"));let local = session(None);- assert_eq!(owner_of("owner-test-pending", Some(&local)).await, Ok(None));+ assert_eq!(owner_of(&DispatchCtx::process_default(), "owner-test-pending", Some(&local)).await, Ok(None));}/// A remembered owner is re-checked in its scope: once that scope no longer@@ -37,7 +38,7 @@ async fn a_remembered_owner_that_lost_the_device_is_forgotten() {);remember("owner-test-stale", None);let owner =- crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-stale", None)).await;+ crate::core::runtime::CoreContext::scope(context, owner_of(&DispatchCtx::process_default(), "owner-test-stale", None)).await;assert_eq!(owner, Ok(None));assert_eq!(cached("owner-test-stale"), None, "the stale entry is gone");}@@ -54,7 +55,7 @@ async fn a_revoked_device_is_not_its_agents_any_more() {config,);let owner =- crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-revoked", None))+ crate::core::runtime::CoreContext::scope(context, owner_of(&DispatchCtx::process_default(), "owner-test-revoked", None)).await;assert_eq!(owner, Ok(None));assert_eq!(@@ -90,7 +91,7 @@ async fn a_device_found_in_the_local_scope_belongs_to_local_and_is_remembered()config,);let owner =- crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-found", None)).await;+ crate::core::runtime::CoreContext::scope(context, owner_of(&DispatchCtx::process_default(), "owner-test-found", None)).await;assert_eq!(owner, Ok(None));assert_eq!(cached("owner-test-found"), Some(None));}@@ -103,7 +104,7 @@ async fn a_channel_no_scope_knows_is_local_and_not_remembered() {scoped_config(tmp.path()),);let owner =- crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-missing", None))+ crate::core::runtime::CoreContext::scope(context, owner_of(&DispatchCtx::process_default(), "owner-test-missing", None)).await;assert_eq!(owner, Ok(None));assert_eq!(cached("owner-test-missing"), None);@@ -153,7 +154,7 @@ async fn a_revoked_device_with_a_live_cipher_is_dropped() {)),);let owner =- crate::core::runtime::CoreContext::scope(context, owner_of("owner-test-cipher", None))+ crate::core::runtime::CoreContext::scope(context, owner_of(&DispatchCtx::process_default(), "owner-test-cipher", None)).await;super::super::rpc::ACTIVE_CIPHERS.lock()@@ -177,7 +178,7 @@ async fn a_leftover_pairing_session_does_not_outlive_a_revocation() {let pending = session(None);// Before the handshake the session names the agent.assert_eq!(- owner_of("owner-test-leftover", Some(&pending)).await,+ owner_of(&DispatchCtx::process_default(), "owner-test-leftover", Some(&pending)).await,Ok(None));super::super::rpc::ACTIVE_CIPHERS.lock().unwrap().insert(@@ -189,7 +190,7 @@ async fn a_leftover_pairing_session_does_not_outlive_a_revocation() {// Cipher live, row not persisted yet: still the session's agent.let racing = crate::core::runtime::CoreContext::scope(std::sync::Arc::clone(&context),- owner_of("owner-test-leftover", Some(&pending)),+ owner_of(&DispatchCtx::process_default(), "owner-test-leftover", Some(&pending)),).await;assert_eq!(racing, Ok(None));@@ -199,7 +200,7 @@ async fn a_leftover_pairing_session_does_not_outlive_a_revocation() {super::super::store::revoke_device(&config, "owner-test-leftover").unwrap();let owner = crate::core::runtime::CoreContext::scope(context,- owner_of("owner-test-leftover", Some(&pending)),+ owner_of(&DispatchCtx::process_default(), "owner-test-leftover", Some(&pending)),).await;super::super::rpc::ACTIVE_CIPHERSdiff --git a/crates/openhuman-core/src/security/keyring_consent/ops.rs b/crates/openhuman-core/src/security/keyring_consent/ops.rsindex ec20e7b79c..2570592406 100644--- a/crates/openhuman-core/src/security/keyring_consent/ops.rs+++ b/crates/openhuman-core/src/security/keyring_consent/ops.rs@@ -1,5 +1,6 @@//! RPC handler implementations for keyring consent.+use crate::core::runtime::DispatchCtx;use crate::core::Outcome;use super::policy;@@ -18,7 +19,7 @@ pub async fn keyring_status() -> Result<Outcome<KeyringStatus>, String> {Ok(Outcome::single_log(status, "keyring status fetched"))}-pub async fn keyring_consent_decide(mode: String) -> Result<Outcome<ConsentPreference>, String> {+pub async fn keyring_consent_decide(ctx: &DispatchCtx, mode: String) -> Result<Outcome<ConsentPreference>, String> {if mode != "local_encrypted" && mode != "declined" {return Err(format!("invalid mode '{mode}': expected 'local_encrypted' or 'declined'"@@ -31,7 +32,7 @@ pub async fn keyring_consent_decide(mode: String) -> Result<Outcome<ConsentPrefe// Persist to disk first. If this fails we return an error without// updating the cache, so cache and disk stay consistent.- persist_consent(&pref).await?;+ persist_consent(&ctx, &pref).await?;// Only update the in-memory cache after a successful persist.policy::apply_consent(&pref);@@ -51,12 +52,12 @@ pub async fn keyring_retry_probe() -> Result<Outcome<KeyringStatus>, String> {))}-async fn persist_consent(pref: &ConsentPreference) -> Result<(), String> {+async fn persist_consent(ctx: &DispatchCtx, pref: &ConsentPreference) -> Result<(), String> {let patch = crate::desktop::app_state::StoredAppStatePatch {keyring_consent: Some(Some(pref.clone())),..Default::default()};- crate::desktop::app_state::update_local_state(patch).await?;+ crate::desktop::app_state::update_local_state(&ctx, patch).await?;log::debug!("{LOG_PREFIX} consent persisted to app state");Ok(())}diff --git a/crates/openhuman-core/src/security/keyring_consent/ops_tests.rs b/crates/openhuman-core/src/security/keyring_consent/ops_tests.rsindex ff867b4ba3..7822932353 100644--- a/crates/openhuman-core/src/security/keyring_consent/ops_tests.rs+++ b/crates/openhuman-core/src/security/keyring_consent/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;#[tokio::test]@@ -10,7 +11,7 @@ async fn keyring_status_returns_ok() {#[tokio::test]async fn keyring_consent_decide_rejects_invalid_mode() {- let result = keyring_consent_decide("invalid".to_string()).await;+ let result = keyring_consent_decide(&DispatchCtx::process_default(), "invalid".to_string()).await;assert!(result.is_err());assert!(result.unwrap_err().contains("invalid mode"));}diff --git a/crates/openhuman-core/src/security/keyring_consent/schemas.rs b/crates/openhuman-core/src/security/keyring_consent/schemas.rsindex e6c04c11e4..6121016897 100644--- a/crates/openhuman-core/src/security/keyring_consent/schemas.rs+++ b/crates/openhuman-core/src/security/keyring_consent/schemas.rs@@ -97,14 +97,14 @@ fn handle_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFu})}-fn handle_decide(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_decide(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let mode = params.get("mode").and_then(|v| v.as_str()).ok_or("missing required param 'mode'")?.to_string();- super::ops::keyring_consent_decide(mode)+ super::ops::keyring_consent_decide(&ctx, mode).await?.into_cli_compatible_json()})diff --git a/crates/openhuman-core/src/security/ops_tests.rs b/crates/openhuman-core/src/security/ops_tests.rsindex a96b4fc88c..4442fae42d 100644--- a/crates/openhuman-core/src/security/ops_tests.rs+++ b/crates/openhuman-core/src/security/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::test_env::EnvVarGuard;@@ -88,7 +89,7 @@ async fn load_and_get_security_policy_info_reflects_env_overlay() {let _workspace_guard = EnvVarGuard::set("OPENHUMAN_WORKSPACE", workspace.path());let _budget_guard = EnvVarGuard::set("OPENHUMAN_MAX_ACTIONS_PER_HOUR", budget.to_string());- let outcome = load_and_get_security_policy_info()+ let outcome = load_and_get_security_policy_info(&DispatchCtx::process_default()).await.expect("load_and_get_security_policy_info should succeed");diff --git a/crates/openhuman-core/src/security/schemas.rs b/crates/openhuman-core/src/security/schemas.rsindex c889f34fd7..75fe00aa31 100644--- a/crates/openhuman-core/src/security/schemas.rs+++ b/crates/openhuman-core/src/security/schemas.rs@@ -40,10 +40,10 @@ pub fn schemas(function: &str) -> ControllerSchema {}}-fn handle_policy_info(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async {+fn handle_policy_info(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {log::debug!("[security][rpc] policy_info enter");- match crate::security::rpc::load_and_get_security_policy_info().await {+ match crate::security::rpc::load_and_get_security_policy_info(&ctx).await {Ok(outcome) => {log::debug!("[security][rpc] policy_info ok");to_json(outcome)diff --git a/crates/openhuman-core/src/threads/ops_conversion_tests.rs b/crates/openhuman-core/src/threads/ops_conversion_tests.rsindex f01010e650..ac9c976f6a 100644--- a/crates/openhuman-core/src/threads/ops_conversion_tests.rs+++ b/crates/openhuman-core/src/threads/ops_conversion_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;// NOTE: the title_log_fingerprint / collapse_whitespace copies were removed@@ -185,7 +186,7 @@ async fn message_append_returns_typed_not_found_for_stale_thread() {let _workspace_guard = EnvVarGuard::set("OPENHUMAN_WORKSPACE", workspace.path());let thread_id = "thread-missing";- let err = message_append(AppendConversationMessageRequest {+ let err = message_append(&DispatchCtx::process_default(), AppendConversationMessageRequest {thread_id: thread_id.to_string(),message: ConversationMessageRecord {id: "msg-1".to_string(),@@ -361,7 +362,7 @@ async fn thread_delete_removes_persisted_turn_state_snapshot() {.await;assert_eq!(bg::pending_for(&dir, thread_id).len(), 1);- thread_delete(DeleteConversationThreadRequest {+ thread_delete(&DispatchCtx::process_default(), DeleteConversationThreadRequest {thread_id: thread_id.to_string(),deleted_at: "2026-01-01T00:02:00Z".into(),})@@ -491,7 +492,7 @@ async fn thread_delete_forgets_its_conversation_memory_or_queues_it() {.expect("load config").workspace_dir;- thread_delete(DeleteConversationThreadRequest {+ thread_delete(&DispatchCtx::process_default(), DeleteConversationThreadRequest {thread_id: thread_id.to_string(),deleted_at: "2026-01-01T00:02:00Z".into(),})diff --git a/crates/openhuman-core/src/threads/schemas/handlers.rs b/crates/openhuman-core/src/threads/schemas/handlers.rsindex 469ac26448..3d3136e0a9 100644--- a/crates/openhuman-core/src/threads/schemas/handlers.rs+++ b/crates/openhuman-core/src/threads/schemas/handlers.rs@@ -56,12 +56,12 @@ pub(super) fn handle_messages_list(}pub(super) fn handle_message_append(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let p = parse::<AppendConversationMessageRequest>(params)?;- to_json(ops::message_append(p).await?)+ to_json(ops::message_append(&ctx, p).await?)})}@@ -115,10 +115,10 @@ pub(super) fn handle_message_update(})}-pub(super) fn handle_delete(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_delete(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let p = parse::<DeleteConversationThreadRequest>(params)?;- to_json(ops::thread_delete(p).await?)+ to_json(ops::thread_delete(&ctx, p).await?)})}diff --git a/crates/openhuman-core/src/threads/store/bus.rs b/crates/openhuman-core/src/threads/store/bus.rsindex e0cbe1f459..38ab792c93 100644--- a/crates/openhuman-core/src/threads/store/bus.rs+++ b/crates/openhuman-core/src/threads/store/bus.rs@@ -241,7 +241,7 @@ impl EventHandler<DomainEvent> for ConversationPersistenceSubscriber {);return;}- if let Err(error) = persist_channel_turn(+ if let Err(error) = persist_channel_turn(&DispatchCtx::ambient(),&my_workspace,ChannelTurnDescriptor {channel,@@ -299,7 +299,7 @@ impl EventHandler<DomainEvent> for ConversationPersistenceSubscriber {);return;}- if let Err(error) = persist_channel_turn(+ if let Err(error) = persist_channel_turn(&DispatchCtx::ambient(),&my_workspace,ChannelTurnDescriptor {channel,diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rsindex 4061e57934..60d1f050d4 100644--- a/crates/openhuman-core/src/tools/impl/network/host.rs+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@ -48,7 +48,7 @@ impl AsyncHtmlExtractor for TinyJuiceHtml {}async fn to_markdown(&self, html: &str) -> anyhow::Result<String> {- crate::inference::tokenjuice::extract_html(html.to_string())+ crate::inference::tokenjuice::extract_html(&DispatchCtx::ambient(), html.to_string()).await.map_err(anyhow::Error::msg)}diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex 29d85e9042..6857d689cd 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -264,7 +264,7 @@ impl Tool for ShellTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, None).await+ self.execute_in_context(&DispatchCtx::ambient(), args, None).await}async fn execute_with_context(@@ -273,13 +273,13 @@ impl Tool for ShellTool {_options: ToolCallOptions,context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, context).await+ self.execute_in_context(&DispatchCtx::ambient(), args, context).await}}impl ShellTool {async fn execute_in_context(- &self,+ &self, ctx: &DispatchCtx,args: serde_json::Value,context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {@@ -298,7 +298,7 @@ impl ShellTool {let (allowed, result) = crate::sandbox::shell_progress::with_shell_progress(context,crate::sandbox::shell_progress::HEARTBEAT_INTERVAL,- |meter| self.run_with_security_in_context(command, requested_timeout, context, meter),+ |meter| self.run_with_security_in_context(&ctx, command, requested_timeout, context, meter),).await;let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);@@ -326,11 +326,11 @@ impl ShellTool {/// checks (rate limits, path guards, approval gate routing) apply/// identically to workflow-triggered commands.pub(crate) async fn run_with_security(- &self,+ &self, ctx: &DispatchCtx,command: &str,requested_timeout: Option<u64>,) -> (bool, ToolResult) {- self.run_with_security_in_context(command, requested_timeout, None, None)+ self.run_with_security_in_context(&ctx, command, requested_timeout, None, None).await}@@ -410,7 +410,7 @@ impl ShellTool {let action_dir = saas_action_dir;return match resolved {Ok(policy) => {- self.run_in_policy(policy, command, requested_timeout, &action_dir, meter)+ self.run_in_policy(&ctx, policy, command, requested_timeout, &action_dir, meter).await}Err(why) => {@@ -423,7 +423,7 @@ impl ShellTool {// A sandboxed agent or an explicit operator backend uses the sandbox// execution path. Security checks above still apply.- let sandbox_required = match crate::sandbox::command_requires_sandbox(+ let sandbox_required = match crate::sandbox::command_requires_sandbox(&ctx,crate::agent::tinyagents::host::run_context::sandbox_mode_for_tool(context),).await@@ -439,7 +439,7 @@ impl ShellTool {if sandbox_required {let action_dir = self.effective_action_dir_for_context(context);return self- .run_sandboxed(command, requested_timeout, &action_dir, meter)+ .run_sandboxed(&ctx, command, requested_timeout, &action_dir, meter).await;}@@ -624,7 +624,7 @@ impl ShellTool {/// Execute a command through the sandbox backend. Called when the/// agent's `SandboxMode` is `Sandboxed`.async fn run_sandboxed(- &self,+ &self, ctx: &DispatchCtx,command: &str,requested_timeout: Option<u64>,action_dir: &Path,@@ -638,13 +638,13 @@ impl ShellTool {&config,false,);- self.run_in_policy(policy, command, requested_timeout, action_dir, meter)+ self.run_in_policy(&ctx, policy, command, requested_timeout, action_dir, meter).await}/// Execute a command under a resolved sandbox `policy`.async fn run_in_policy(- &self,+ &self, ctx: &DispatchCtx,policy: crate::sandbox::SandboxPolicy,command: &str,requested_timeout: Option<u64>,@@ -681,7 +681,7 @@ impl ShellTool {"[shell] starting sandboxed command");- let result = sandbox::ops::execute_in_sandbox_metered(+ let result = sandbox::ops::execute_in_sandbox_metered(&ctx,&policy, command, action_dir, extra_env, effective, meter,).await;diff --git a/crates/openhuman-core/src/tools/impl/system/update_apply.rs b/crates/openhuman-core/src/tools/impl/system/update_apply.rsindex 07ade78343..69a1ef0af1 100644--- a/crates/openhuman-core/src/tools/impl/system/update_apply.rs+++ b/crates/openhuman-core/src/tools/impl/system/update_apply.rs@@ -19,6 +19,7 @@//! high impact (replaces a binary on disk, optionally restarts the core//! process) and must not happen silently.+use crate::core::runtime::DispatchCtx;use std::sync::Arc;use async_trait::async_trait;@@ -116,7 +117,7 @@ impl Tool for UpdateApplyTool {return Ok(blocked);}- let outcome = update::rpc::update_run().await;+ let outcome = update::rpc::update_run(&DispatchCtx::ambient()).await;for log in &outcome.logs {tracing::debug!(target: "update_apply", "{log}");}diff --git a/crates/openhuman-core/src/tools/schemas/web_search.rs b/crates/openhuman-core/src/tools/schemas/web_search.rsindex 1062f17955..196844cf2c 100644--- a/crates/openhuman-core/src/tools/schemas/web_search.rs+++ b/crates/openhuman-core/src/tools/schemas/web_search.rs@@ -151,20 +151,20 @@ fn search_arguments(params: &Map<String, Value>, provider: Option<&str>) -> ResuOk(arguments)}-pub(super) fn handle_web_search(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_web_search(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let arguments = search_arguments(¶ms, None)?;- run_role_tool(tinysearch_bus::tools::WEB_SEARCH, arguments, "web_search").await+ run_role_tool(&ctx, tinysearch_bus::tools::WEB_SEARCH, arguments, "web_search").await})}pub(super) fn handle_searxng_search(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let arguments = search_arguments(¶ms, Some("searxng"))?;- run_role_tool(+ run_role_tool(&ctx,tinysearch_bus::tools::WEB_SEARCH,arguments,"searxng_search",@@ -173,7 +173,7 @@ pub(super) fn handle_searxng_search(})}-pub(super) fn handle_web_answer(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+pub(super) fn handle_web_answer(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let query = required_text(¶ms, "query")?;let mut arguments = json!({ "query": query });@@ -190,12 +190,12 @@ pub(super) fn handle_web_answer(_ctx: DispatchCtx, params: Map<String, Value>) -query_len = query.chars().count(),"[rpc][tools.web_answer] request");- run_role_tool(tinysearch_bus::tools::WEB_ANSWER, arguments, "web_answer").await+ run_role_tool(&ctx, tinysearch_bus::tools::WEB_ANSWER, arguments, "web_answer").await})}pub(super) fn handle_web_contents(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {@@ -211,7 +211,7 @@ pub(super) fn handle_web_contents(arguments["provider"] = json!(provider);}tracing::debug!(urls = urls.len(), "[rpc][tools.web_contents] request");- run_role_tool(+ run_role_tool(&ctx,tinysearch_bus::tools::WEB_CONTENTS,arguments,"web_contents",diff --git a/crates/openhuman-core/src/web3/module_tools.rs b/crates/openhuman-core/src/web3/module_tools.rsindex 70b6ff3f54..c8404a7c09 100644--- a/crates/openhuman-core/src/web3/module_tools.rs+++ b/crates/openhuman-core/src/web3/module_tools.rs@@ -36,7 +36,7 @@ impl Tool for Web3ModuleTool {}async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- self.run(args, None).await+ self.run(&DispatchCtx::ambient(), args, None).await}async fn execute_with_context(@@ -46,7 +46,7 @@ impl Tool for Web3ModuleTool {context: Option<&dyn tinytools::ToolRunContext>,) -> anyhow::Result<ToolResult> {let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);- self.run(args, approval.chat.as_ref()).await+ self.run(&DispatchCtx::ambient(), args, approval.chat.as_ref()).await}async fn execute_with_options(diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rsindex e435f65474..ebf711046d 100644--- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs+++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs@@ -1,3 +1,4 @@+use crate::core::runtime::DispatchCtx;use super::*;use crate::config::Config;@@ -67,7 +68,7 @@ fn word_count_validation_follows_the_wallet_contract() {#[tokio::test]async fn generate_recovery_phrase_rejects_unsupported_word_count_before_the_module() {- let error = generate_recovery_phrase(13)+ let error = generate_recovery_phrase(&DispatchCtx::process_default(), 13).await.expect_err("13 words is not a BIP-39 length");assert!(error.contains("13"), "{error}");@@ -236,7 +237,7 @@ async fn reveal_recovery_phrase_returns_error_when_no_wallet() {let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await;let _workspace_guard =crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;- let result = reveal_recovery_phrase().await;+ let result = reveal_recovery_phrase(&DispatchCtx::process_default()).await;let err = result.expect_err("should error when no wallet configured");assert!(err.contains("No recovery phrase is available"),@@ -248,10 +249,10 @@ async fn reveal_recovery_phrase_returns_error_when_no_wallet() {async fn reveal_recovery_phrase_returns_phrase_for_existing_wallet() {let temp = tempfile::tempdir().expect("temp dir");let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock().await;- let _workspace_guard = crate::web3::wallet::test_support::setup_wallet_in(&temp)+ let _workspace_guard = crate::web3::wallet::test_support::setup_wallet_in(&DispatchCtx::process_default(), &temp).await.expect("setup wallet");- let result = reveal_recovery_phrase()+ let result = reveal_recovery_phrase(&DispatchCtx::process_default()).await.expect("reveal should succeed");assert_eq!(diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rsindex 03f53261a7..03cc789f38 100644--- a/crates/openhuman-core/src/web3/wallet/schemas.rs+++ b/crates/openhuman-core/src/web3/wallet/schemas.rs@@ -428,19 +428,19 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema {}}-fn handle_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {- crate::web3::wallet::status()+ crate::web3::wallet::status(&ctx).await?.into_cli_compatible_json()})}-fn handle_setup(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_setup(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload: SetupWalletParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- crate::web3::wallet::setup(WalletSetupParams {+ crate::web3::wallet::setup(&ctx, WalletSetupParams {consent_granted: payload.consent_granted,source: payload.source,mnemonic_word_count: payload.mnemonic_word_count,@@ -453,123 +453,123 @@ fn handle_setup(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu})}-fn handle_balances(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { balances().await?.into_cli_compatible_json() })+fn handle_balances(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { balances(&ctx).await?.into_cli_compatible_json() })}-fn handle_network_defaults(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { network_defaults().await?.into_cli_compatible_json() })+fn handle_network_defaults(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { network_defaults(&ctx).await?.into_cli_compatible_json() })}-fn handle_supported_assets(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { supported_assets().await?.into_cli_compatible_json() })+fn handle_supported_assets(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { supported_assets(&ctx).await?.into_cli_compatible_json() })}-fn handle_encode_erc20_transfer(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_encode_erc20_transfer(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: EncodeErc20TransferParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;if parsed.chain != WalletChain::Evm {return Err("encode_erc20_transfer only supports the evm chain".to_string());}- serde_json::to_value(encode_erc20_transfer(&parsed.to_address, &parsed.amount_raw).await?)+ serde_json::to_value(encode_erc20_transfer(&ctx, &parsed.to_address, &parsed.amount_raw).await?).map_err(|e| format!("failed to encode ERC20 transfer output: {e}"))})}-fn handle_chain_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move { chain_status().await?.into_cli_compatible_json() })+fn handle_chain_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { chain_status(&ctx).await?.into_cli_compatible_json() })}-fn handle_prepare_transfer(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_prepare_transfer(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: PrepareTransferParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- prepare_transfer(parsed, None)+ prepare_transfer(&ctx, parsed, None).await?.into_cli_compatible_json()})}-fn handle_execute_prepared(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_execute_prepared(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: ExecutePreparedParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- execute_prepared(parsed, None)+ execute_prepared(&ctx, parsed, None).await?.into_cli_compatible_json()})}-fn handle_tx_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_tx_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: TxQueryParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- tx_status(parsed.chain, parsed.evm_network, &parsed.hash)+ tx_status(&ctx, parsed.chain, parsed.evm_network, &parsed.hash).await?.into_cli_compatible_json()})}-fn handle_tx_receipt(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_tx_receipt(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: TxQueryParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- tx_receipt(parsed.chain, parsed.evm_network, &parsed.hash)+ tx_receipt(&ctx, parsed.chain, parsed.evm_network, &parsed.hash).await?.into_cli_compatible_json()})}-fn handle_lookup_tx(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_lookup_tx(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: TxQueryParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- lookup_tx(parsed.chain, parsed.evm_network, &parsed.hash)+ lookup_tx(&ctx, parsed.chain, parsed.evm_network, &parsed.hash).await?.into_cli_compatible_json()})}fn handle_reveal_recovery_phrase(- _ctx: DispatchCtx,+ ctx: DispatchCtx,_params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {- crate::web3::wallet::reveal_recovery_phrase()+ crate::web3::wallet::reveal_recovery_phrase(&ctx).await?.into_cli_compatible_json()})}-fn handle_generate_mnemonic(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_generate_mnemonic(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: GenerateMnemonicParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- crate::web3::wallet::generate_recovery_phrase(parsed.word_count)+ crate::web3::wallet::generate_recovery_phrase(&ctx, parsed.word_count).await?.into_cli_compatible_json()})}-fn handle_validate_mnemonic(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+fn handle_validate_mnemonic(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- crate::web3::wallet::validate_recovery_phrase(parsed.phrase)+ crate::web3::wallet::validate_recovery_phrase(&ctx, parsed.phrase).await?.into_cli_compatible_json()})}fn handle_derive_recovery_material(- _ctx: DispatchCtx,+ ctx: DispatchCtx,params: Map<String, Value>,) -> ControllerFuture {Box::pin(async move {let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- crate::web3::wallet::derive_recovery_material(parsed.phrase)+ crate::web3::wallet::derive_recovery_material(&ctx, parsed.phrase).await?.into_cli_compatible_json()})diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rsindex d254fb1071..c36f1f52e8 100644--- a/crates/openhuman-core/src/web3/wallet/test_support.rs+++ b/crates/openhuman-core/src/web3/wallet/test_support.rs@@ -9,6 +9,7 @@//! so every chain's signer derives a deterministic address.//! - Sample addresses corresponding to that mnemonic (one per chain).+use crate::core::runtime::DispatchCtx;use tempfile::TempDir;use super::ops::{setup, WalletAccount, WalletChain, WalletSetupParams, WalletSetupSource};@@ -115,7 +116,7 @@ pub(crate) async fn set_workspace_env_for_test(temp: &TempDir) -> EnvVarGuard {EnvVarGuard::workspace_async(temp.path()).await}-pub(crate) async fn setup_wallet_in(temp: &TempDir) -> Result<EnvVarGuard, String> {+pub(crate) async fn setup_wallet_in(ctx: &DispatchCtx, temp: &TempDir) -> Result<EnvVarGuard, String> {// Wallet state lookups rely on OPENHUMAN_WORKSPACE for the duration of// each test. Return a guard so the tempdir path does not leak into later// parallel tests after this test's TempDir has been dropped.@@ -124,7 +125,7 @@ pub(crate) async fn setup_wallet_in(temp: &TempDir) -> Result<EnvVarGuard, Strinlet encrypted = crate::security::encryption::rpc::encrypt_secret(&config, TEST_MNEMONIC).await?.value;- setup(WalletSetupParams {+ setup(&ctx, WalletSetupParams {consent_granted: true,source: WalletSetupSource::Imported,mnemonic_word_count: 12,diff --git a/crates/openhuman-core/src/web3/wallet/tools.rs b/crates/openhuman-core/src/web3/wallet/tools.rsindex be4bf5369e..a93e2ab57e 100644--- a/crates/openhuman-core/src/web3/wallet/tools.rs+++ b/crates/openhuman-core/src/web3/wallet/tools.rs@@ -1,5 +1,6 @@//! Agent tool adapters that send wallet operations through TinyWallet's bus.+use crate::core::runtime::DispatchCtx;use async_trait::async_trait;use serde::Deserialize;use serde::Serialize;@@ -56,7 +57,7 @@ impl Tool for WalletModuleTool {}async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- self.run(args, None).await+ self.run(&DispatchCtx::ambient(), args, None).await}async fn execute_with_context(@@ -66,20 +67,20 @@ impl Tool for WalletModuleTool {context: Option<&dyn tinytools::ToolRunContext>,) -> anyhow::Result<ToolResult> {let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);- self.run(args, approval.chat.as_ref()).await+ self.run(&DispatchCtx::ambient(), args, approval.chat.as_ref()).await}}impl WalletModuleTool {/// Runs the tool for a turn whose approval context is `chat`.pub(crate) async fn run(- &self,+ &self, ctx: &DispatchCtx,args: Value,chat: Option<&crate::security::approval::ApprovalChatContext>,) -> anyhow::Result<ToolResult> {let result = match self.name() {- "wallet_status" => outcome_value(crate::web3::wallet::status().await),- "wallet_chain_status" => outcome_value(crate::web3::wallet::chain_status().await),+ "wallet_status" => outcome_value(crate::web3::wallet::status(&ctx).await),+ "wallet_chain_status" => outcome_value(crate::web3::wallet::chain_status(&ctx).await),"wallet_prepare_transfer" => {let params = match serde_json::from_value(args) {Ok(params) => params,@@ -104,11 +105,11 @@ impl WalletModuleTool {};let result = match self.name() {"wallet_tx_status" => outcome_value(- crate::web3::wallet::tx_status(query.chain, query.evm_network, &query.hash)+ crate::web3::wallet::tx_status(&ctx, query.chain, query.evm_network, &query.hash).await,),"wallet_tx_receipt" => outcome_value(- crate::web3::wallet::tx_receipt(+ crate::web3::wallet::tx_receipt(&ctx,query.chain,query.evm_network,&query.hash,@@ -116,7 +117,7 @@ impl WalletModuleTool {.await,),_ => outcome_value(- crate::web3::wallet::lookup_tx(query.chain, query.evm_network, &query.hash)+ crate::web3::wallet::lookup_tx(&ctx, query.chain, query.evm_network, &query.hash).await,),};