Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(core): thread DispatchCtx through config and ops functions

Steven Enamakel17bd377205ea
diff --git a/crates/openhuman-core/src/config/ops/agent.rs b/crates/openhuman-core/src/config/ops/agent.rs
index 1c735aef61..040a8c157e 100644
--- a/crates/openhuman-core/src/config/ops/agent.rs
+++ b/crates/openhuman-core/src/config/ops/agent.rs
@@ -1,5 +1,6 @@
//! Agent, autonomy, paths, and memory-sync config operations.
+use crate::core::runtime::DispatchCtx;
use std::path::{Path, PathBuf};
use serde_json::json;
@@ -148,7 +149,7 @@ pub async fn apply_autonomy_settings(
}
/// Loads the configuration, applies autonomy settings updates, and saves it.
-pub async fn load_and_apply_autonomy_settings(
+pub async fn load_and_apply_autonomy_settings(ctx: &DispatchCtx,
update: AutonomySettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -156,7 +157,7 @@ pub async fn load_and_apply_autonomy_settings(
}
/// Returns the current `[autonomy]` settings block as JSON (no secrets).
-pub async fn get_autonomy_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_autonomy_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let value = serde_json::to_value(&config.autonomy).map_err(|e| e.to_string())?;
Ok(Outcome::single_log(value, "autonomy settings read"))
@@ -170,7 +171,7 @@ fn auto_approve_write_lock() -> &'static tokio::sync::Mutex<()> {
/// Append `tool_name` to `autonomy.auto_approve` ("Always allow") and persist +
/// reload the live policy. Idempotent — a no-op (no disk write) when the tool is
/// already allow-listed. Backs the `ApproveAlwaysForTool` approval decision.
-pub async fn add_auto_approve_tool(tool_name: &str) -> Result<(), String> {
+pub async fn add_auto_approve_tool(ctx: &DispatchCtx, tool_name: &str) -> Result<(), String> {
let _guard = auto_approve_write_lock().lock().await;
let mut config = ctx.load_config().await?;
if config.autonomy.auto_approve.iter().any(|t| t == tool_name) {
@@ -264,7 +265,7 @@ pub async fn apply_agent_settings(
}
/// Loads the configuration, applies agent settings updates, and saves it.
-pub async fn load_and_apply_agent_settings(
+pub async fn load_and_apply_agent_settings(ctx: &DispatchCtx,
update: AgentSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -274,7 +275,7 @@ pub async fn load_and_apply_agent_settings(
/// Returns the agent execution settings (currently the action timeout) plus the
/// runtime-effective value and whether the `OPENHUMAN_TOOL_TIMEOUT_SECS` env var
/// is overriding the configured value, so the UI can explain a no-op control.
-pub async fn get_agent_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_agent_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
crate::tools::timeout::set_tool_timeout_secs(config.agent.agent_timeout_secs);
let value = serde_json::json!({
@@ -650,7 +651,7 @@ pub async fn apply_agent_paths_settings(
}
/// Loads the configuration, applies agent-paths updates, and saves it.
-pub async fn load_and_apply_agent_paths_settings(
+pub async fn load_and_apply_agent_paths_settings(ctx: &DispatchCtx,
update: AgentPathsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -666,7 +667,7 @@ fn paths_equal(a: &Path, b: &Path) -> bool {
/// Reports the agent's filesystem roots so the UI can render them live
/// instead of hard-coding strings that drift away from `Config`.
-pub async fn get_agent_paths() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_agent_paths(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
Ok(Outcome::new(
agent_paths_payload(&config),
diff --git a/crates/openhuman-core/src/config/ops/computer.rs b/crates/openhuman-core/src/config/ops/computer.rs
index 542e4c2104..65ad8f4351 100644
--- a/crates/openhuman-core/src/config/ops/computer.rs
+++ b/crates/openhuman-core/src/config/ops/computer.rs
@@ -1,6 +1,7 @@
//! TinyComputer model settings: the decision model and the planner and
//! rescue models the module runs a task with.
+use crate::core::runtime::DispatchCtx;
use crate::config::{ComputerConfig, Config, DecisionModel};
use crate::core::Outcome;
@@ -93,7 +94,7 @@ pub async fn apply_computer_settings(
}
/// Load the configuration, update `[computer]`, and save it.
-pub async fn load_and_apply_computer_settings(
+pub async fn load_and_apply_computer_settings(ctx: &DispatchCtx,
update: ComputerSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
diff --git a/crates/openhuman-core/src/config/ops/loader/load.rs b/crates/openhuman-core/src/config/ops/loader/load.rs
index 3146b28aa9..0ead1000e1 100644
--- a/crates/openhuman-core/src/config/ops/loader/load.rs
+++ b/crates/openhuman-core/src/config/ops/loader/load.rs
@@ -1,6 +1,7 @@
//! Loading persisted config with a timeout, anchored reloads, and the
//! in-memory normalization that runs on every load.
+use crate::core::runtime::DispatchCtx;
use std::path::Path;
use crate::config::Config;
@@ -85,7 +86,7 @@ pub async fn load_config_in(ctx: &crate::core::runtime::DispatchCtx) -> Result<C
/// The context-aware counterpart of [`Config::load_or_init`] for code that
/// runs inside a turn: [`load_config_with_timeout`] with the context's
/// inference route applied.
-pub async fn load_current_or_init() -> anyhow::Result<Config> {
+pub async fn load_current_or_init(ctx: &DispatchCtx, ) -> anyhow::Result<Config> {
let mut config = ctx.load_config()
.await
.map_err(anyhow::Error::msg)?;
@@ -119,7 +120,7 @@ pub async fn load_current_or_init() -> anyhow::Result<Config> {
/// exists there is nothing workspace-specific to read, so this falls back to
/// the process-global load with `workspace_dir` re-anchored — the previous
/// behaviour, and still correct for a single-workspace host.
-pub async fn load_config_for_workspace_with_timeout(
+pub async fn load_config_for_workspace_with_timeout(ctx: &DispatchCtx,
workspace_dir: &Path,
) -> Result<Config, String> {
let candidate = [
diff --git a/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs b/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs
index 1e4663629d..2e51aab226 100644
--- a/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs
+++ b/crates/openhuman-core/src/config/ops/loader/reset_local_data.rs
@@ -2,6 +2,7 @@
//! root markers, plus the path-discovery RPCs the Tauri shell uses to do the
//! same from outside the core process.
+use crate::core::runtime::DispatchCtx;
use std::path::Path;
use serde_json::json;
@@ -147,7 +148,7 @@ pub(crate) async fn reset_local_data_for_paths(
/// callers where in-process removal is acceptable (POSIX file semantics
/// tolerate unlinking open files; on Windows the CLI invocation runs
/// without the core attached, so no handle is in the way).
-pub async fn reset_local_data() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn reset_local_data(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let current_openhuman_dir = config_openhuman_dir(&config);
let default_openhuman_dir = default_openhuman_dir();
@@ -164,7 +165,7 @@ pub async fn reset_local_data() -> Result<Outcome<serde_json::Value>, String> {
/// after which the Tauri shell removes them while no process holds open
/// handles. See OPENHUMAN-TAURI-AF for the Windows file-locking failure
/// that motivated the split.
-pub async fn get_data_paths() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_data_paths(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let current_openhuman_dir = config_openhuman_dir(&config);
let default_openhuman_dir = default_openhuman_dir();
diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs
index 9bd2feaa64..aa2d1535f6 100644
--- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs
+++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs
@@ -1,5 +1,6 @@
//! Config snapshots serialized for the desktop UI.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use super::load::load_config_with_timeout;
@@ -135,7 +136,7 @@ pub fn client_config_json(config: &Config) -> serde_json::Value {
}
/// Loads config and returns the client-facing AI config slice.
-pub async fn load_and_get_client_config_snapshot() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn load_and_get_client_config_snapshot(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let snapshot = client_config_json(&config);
Ok(Outcome::new(
@@ -157,13 +158,13 @@ pub async fn get_config_snapshot(config: &Config) -> Result<Outcome<serde_json::
}
/// Loads the configuration from disk and returns a snapshot.
-pub async fn load_and_get_config_snapshot() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn load_and_get_config_snapshot(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
get_config_snapshot(&config).await
}
/// Reads dashboard settings exposed to the desktop UI.
-pub async fn get_dashboard_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_dashboard_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let request_id = uuid::Uuid::new_v4().to_string();
tracing::debug!(
target: "openhuman_core::config",
diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs
index 9fead2a0f5..b06dec546c 100644
--- a/crates/openhuman-core/src/config/ops/model.rs
+++ b/crates/openhuman-core/src/config/ops/model.rs
@@ -1,5 +1,6 @@
//! Model/provider config operations: AI providers, memory, runtime, local AI, Composio.
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
use crate::core::Outcome;
@@ -439,7 +440,7 @@ pub async fn apply_model_settings(
}
/// Loads the configuration, applies model settings updates, and saves it.
-pub async fn load_and_apply_model_settings(
+pub async fn load_and_apply_model_settings(ctx: &DispatchCtx,
update: ModelSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -484,7 +485,7 @@ pub async fn apply_memory_settings(
}
/// Loads the configuration, applies memory settings updates, and saves it.
-pub async fn load_and_apply_memory_settings(
+pub async fn load_and_apply_memory_settings(ctx: &DispatchCtx,
update: MemorySettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -542,7 +543,7 @@ pub async fn apply_runtime_settings(
}
/// Loads the configuration, applies runtime settings updates, and saves it.
-pub async fn load_and_apply_runtime_settings(
+pub async fn load_and_apply_runtime_settings(ctx: &DispatchCtx,
update: RuntimeSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -619,7 +620,7 @@ pub async fn apply_local_ai_settings(
}
/// Loads the configuration, applies local-AI settings updates, and saves it.
-pub async fn load_and_apply_local_ai_settings(
+pub async fn load_and_apply_local_ai_settings(ctx: &DispatchCtx,
update: LocalAiSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -657,7 +658,7 @@ pub async fn apply_composio_trigger_settings(
}
/// Loads the configuration, applies composio trigger settings, and saves it.
-pub async fn load_and_apply_composio_trigger_settings(
+pub async fn load_and_apply_composio_trigger_settings(ctx: &DispatchCtx,
update: ComposioTriggerSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -665,7 +666,7 @@ pub async fn load_and_apply_composio_trigger_settings(
}
/// Reads the current composio trigger-triage settings.
-pub async fn get_composio_trigger_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_composio_trigger_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let result = serde_json::json!({
"triage_disabled": config.composio.triage_disabled,
@@ -687,7 +688,7 @@ pub(crate) fn resolve_backend_api_url(config: &Config) -> Option<String> {
/// Resolves the effective backend API URL from configuration or defaults;
/// `api_url` is `null` when the core has no hosted backend.
-pub async fn load_and_resolve_api_url() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn load_and_resolve_api_url(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let resolved = resolve_backend_api_url(&config);
Ok(Outcome::new(
diff --git a/crates/openhuman-core/src/config/ops/privacy.rs b/crates/openhuman-core/src/config/ops/privacy.rs
index 13b403ff36..8aa413c52c 100644
--- a/crates/openhuman-core/src/config/ops/privacy.rs
+++ b/crates/openhuman-core/src/config/ops/privacy.rs
@@ -5,6 +5,7 @@
//! live `SecurityPolicy` so the inference chokepoint enforces the change
//! immediately, without a core restart.
+use crate::core::runtime::DispatchCtx;
use crate::config::{Config, PrivacyMode};
use crate::core::Outcome;
@@ -41,7 +42,7 @@ fn privacy_mode_value(mode: PrivacyMode) -> serde_json::Value {
}
/// Returns the current `[privacy]` mode as `{ "mode": "<snake_case>" }`.
-pub async fn get_privacy_mode() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_privacy_mode(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
log::debug!(
"[privacy][rpc] get_privacy_mode -> {:?}",
@@ -95,7 +96,7 @@ pub async fn apply_privacy_settings(
}
/// Loads the configuration, applies the privacy-mode update, and saves it.
-pub async fn load_and_apply_privacy_settings(
+pub async fn load_and_apply_privacy_settings(ctx: &DispatchCtx,
update: PrivacySettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
diff --git a/crates/openhuman-core/src/config/ops/sandbox.rs b/crates/openhuman-core/src/config/ops/sandbox.rs
index e84602e058..6c6bb4ed7d 100644
--- a/crates/openhuman-core/src/config/ops/sandbox.rs
+++ b/crates/openhuman-core/src/config/ops/sandbox.rs
@@ -1,5 +1,6 @@
//! Sandbox / Docker runtime config operations.
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
use crate::core::Outcome;
@@ -16,7 +17,7 @@ pub struct SandboxSettingsPatch {
pub env_passthrough: Option<Vec<String>>,
}
-pub async fn get_sandbox_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_sandbox_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let sandbox = &config.sandbox;
let docker = &config.runtime.docker;
@@ -120,7 +121,7 @@ pub async fn apply_sandbox_settings(
))
}
-pub async fn load_and_apply_sandbox_settings(
+pub async fn load_and_apply_sandbox_settings(ctx: &DispatchCtx,
update: SandboxSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
diff --git a/crates/openhuman-core/src/config/ops/search.rs b/crates/openhuman-core/src/config/ops/search.rs
index 02b643ca97..d87008449f 100644
--- a/crates/openhuman-core/src/config/ops/search.rs
+++ b/crates/openhuman-core/src/config/ops/search.rs
@@ -5,6 +5,7 @@
//! Keys are write-only here. Reads report `key_configured` booleans and the
//! resolved state from `crate::search::providers`, never a secret.
+use crate::core::runtime::DispatchCtx;
use std::collections::BTreeMap;
use serde::Deserialize;
@@ -309,7 +310,7 @@ pub async fn apply_search_settings(
))
}
-pub async fn load_and_apply_search_settings(
+pub async fn load_and_apply_search_settings(ctx: &DispatchCtx,
update: SearchSettingsPatch,
) -> Result<Outcome<Value>, String> {
let mut config = ctx.load_config().await?;
@@ -390,7 +391,7 @@ pub(crate) fn search_settings_json_with(config: &Config, managed_available: bool
}
/// Read the current search settings. Keys are reported only as booleans.
-pub async fn get_search_settings() -> Result<Outcome<Value>, String> {
+pub async fn get_search_settings(ctx: &DispatchCtx, ) -> Result<Outcome<Value>, String> {
let config = ctx.load_config().await?;
Ok(Outcome::new(
search_settings_json(&config),
diff --git a/crates/openhuman-core/src/config/ops/ui.rs b/crates/openhuman-core/src/config/ops/ui.rs
index 1d4addb034..c98c6ba147 100644
--- a/crates/openhuman-core/src/config/ops/ui.rs
+++ b/crates/openhuman-core/src/config/ops/ui.rs
@@ -1,6 +1,7 @@
//! UI-facing config operations: browser, analytics, dictation, voice server,
//! onboarding flags. Search settings live in `search.rs`.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use crate::config::Config;
@@ -162,7 +163,7 @@ fn normalize_browser_backend(raw: &str) -> Result<String, String> {
}
/// Loads the configuration, applies browser settings updates, and saves it.
-pub async fn load_and_apply_browser_settings(
+pub async fn load_and_apply_browser_settings(ctx: &DispatchCtx,
update: BrowserSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -229,7 +230,7 @@ pub async fn apply_user_timezone(
}
/// Loads the configuration, sets the user's time zone, and saves it.
-pub async fn load_and_apply_user_timezone(
+pub async fn load_and_apply_user_timezone(ctx: &DispatchCtx,
timezone: Option<String>,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -246,7 +247,7 @@ pub fn user_timezone_json(config: &Config) -> serde_json::Value {
}
/// Loads the configuration, applies analytics settings updates, and saves it.
-pub async fn load_and_apply_analytics_settings(
+pub async fn load_and_apply_analytics_settings(ctx: &DispatchCtx,
update: AnalyticsSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -254,7 +255,7 @@ pub async fn load_and_apply_analytics_settings(
}
/// Resolves a workspace onboarding flag, creating or checking its existence.
-pub async fn workspace_onboarding_flag_resolve(
+pub async fn workspace_onboarding_flag_resolve(ctx: &DispatchCtx,
flag_name: Option<String>,
default_name: &str,
) -> Result<Outcome<bool>, String> {
@@ -294,7 +295,7 @@ pub fn workspace_onboarding_flag_exists(
}
/// Creates or removes an onboarding flag file in the workspace.
-pub async fn workspace_onboarding_flag_set(
+pub async fn workspace_onboarding_flag_set(ctx: &DispatchCtx,
flag_name: Option<String>,
default_name: &str,
value: bool,
@@ -331,7 +332,7 @@ pub async fn workspace_onboarding_flag_set(
}
/// Returns whether the onboarding process has been marked as completed.
-pub async fn get_onboarding_completed() -> Result<Outcome<bool>, String> {
+pub async fn get_onboarding_completed(ctx: &DispatchCtx, ) -> Result<Outcome<bool>, String> {
let config = ctx.load_config().await?;
Ok(Outcome::single_log(
config.onboarding_completed,
@@ -343,7 +344,7 @@ pub async fn get_onboarding_completed() -> Result<Outcome<bool>, String> {
///
/// On a false→true transition, seeds the recurring morning-briefing
/// cron job via [`crate::cron::seed::seed_proactive_agents`].
-pub async fn set_onboarding_completed(value: bool) -> Result<Outcome<bool>, String> {
+pub async fn set_onboarding_completed(ctx: &DispatchCtx, value: bool) -> Result<Outcome<bool>, String> {
tracing::debug!(value, "[onboarding] set_onboarding_completed called");
let mut config = ctx.load_config().await?;
let was_completed = config.onboarding_completed;
@@ -376,7 +377,7 @@ pub async fn set_onboarding_completed(value: bool) -> Result<Outcome<bool>, Stri
}
/// Returns the current dictation settings as a JSON object.
-pub async fn get_dictation_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_dictation_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let result = json!({
"enabled": config.dictation.enabled,
@@ -393,7 +394,7 @@ pub async fn get_dictation_settings() -> Result<Outcome<serde_json::Value>, Stri
}
/// Loads configuration, applies dictation settings updates, and saves it.
-pub async fn load_and_apply_dictation_settings(
+pub async fn load_and_apply_dictation_settings(ctx: &DispatchCtx,
update: DictationSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
@@ -439,7 +440,7 @@ pub async fn load_and_apply_dictation_settings(
}
/// Returns the current voice server settings as a JSON object.
-pub async fn get_voice_server_settings() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn get_voice_server_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
let result = json!({
"auto_start": config.voice_server.auto_start,
@@ -460,7 +461,7 @@ pub async fn get_voice_server_settings() -> Result<Outcome<serde_json::Value>, S
}
/// Loads configuration, applies voice server settings updates, and saves it.
-pub async fn load_and_apply_voice_server_settings(
+pub async fn load_and_apply_voice_server_settings(ctx: &DispatchCtx,
update: VoiceServerSettingsPatch,
) -> Result<Outcome<serde_json::Value>, String> {
let mut config = ctx.load_config().await?;
diff --git a/crates/openhuman-core/src/config/workspace/ops.rs b/crates/openhuman-core/src/config/workspace/ops.rs
index 6abbe6336a..4a6de5fbc8 100644
--- a/crates/openhuman-core/src/config/workspace/ops.rs
+++ b/crates/openhuman-core/src/config/workspace/ops.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use crate::config::rpc as config_rpc;
@@ -67,7 +68,7 @@ fn classify_workspace_entry(
}
/// Create default dirs, copy bundled prompts, and the skills README.
-pub async fn init_workspace(force: bool) -> Result<serde_json::Value, String> {
+pub async fn init_workspace(ctx: &DispatchCtx, force: bool) -> Result<serde_json::Value, String> {
let config = ctx.load_config().await?;
let workspace_dir = config.workspace_dir.clone();
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
index a032cc31cc..248612a111 100644
--- a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
+++ b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs
@@ -8,6 +8,7 @@
//! shell's `openhuman_tinyhumans::session` cache — so this snapshot never talks to the
//! backend.
+use crate::core::runtime::DispatchCtx;
use super::runtime_snapshot::{
build_runtime_snapshot, degraded_runtime_snapshot, RUNTIME_SNAPSHOT_TIMEOUT,
};
@@ -38,7 +39,7 @@ pub(super) fn sanitize_snapshot_user(user: Option<Value>) -> Option<Value> {
}
}
-pub async fn snapshot() -> Result<Outcome<AppStateSnapshot>, String> {
+pub async fn snapshot(ctx: &DispatchCtx, ) -> Result<Outcome<AppStateSnapshot>, String> {
let req_id = SNAPSHOT_REQ_COUNTER.fetch_add(1, Ordering::Relaxed);
let t_total = Instant::now();
@@ -140,7 +141,7 @@ pub async fn snapshot() -> Result<Outcome<AppStateSnapshot>, String> {
))
}
-pub async fn update_local_state(
+pub async fn update_local_state(ctx: &DispatchCtx,
patch: StoredAppStatePatch,
) -> Result<Outcome<StoredAppState>, String> {
let config = ctx.load_config().await?;
diff --git a/crates/openhuman-core/src/desktop/control/ops.rs b/crates/openhuman-core/src/desktop/control/ops.rs
index 59bb36b686..28ce36399b 100644
--- a/crates/openhuman-core/src/desktop/control/ops.rs
+++ b/crates/openhuman-core/src/desktop/control/ops.rs
@@ -1,5 +1,6 @@
//! Local desktop enablement and permission-aware status.
+use crate::core::runtime::DispatchCtx;
use std::fs;
use std::io::Write;
use std::sync::{
@@ -25,7 +26,7 @@ const DESKTOP_AGENT_TOOLS: &[&str] = &[
/// A registered desktop tool skips only approval parks when its explicit
/// desktop setting is off. Permission caps, denies, enabled state, OS grants,
/// and the action budget still run at their normal gates.
-pub(crate) async fn approvals_disabled_for(tool: &dyn tinytools::Tool) -> bool {
+pub(crate) async fn approvals_disabled_for(ctx: &DispatchCtx, tool: &dyn tinytools::Tool) -> bool {
if tool.family() != Some("desktop") || !DESKTOP_AGENT_TOOLS.contains(&tool.name()) {
return false;
}
diff --git a/crates/openhuman-core/src/desktop/control/tools.rs b/crates/openhuman-core/src/desktop/control/tools.rs
index 8303785996..c24e849337 100644
--- a/crates/openhuman-core/src/desktop/control/tools.rs
+++ b/crates/openhuman-core/src/desktop/control/tools.rs
@@ -1,5 +1,6 @@
//! Deferred desktop tools. Only their names and descriptions enter discovery.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use async_trait::async_trait;
@@ -180,7 +181,7 @@ impl Tool for DesktopTool {
Err(error) => Err(error.into()),
},
DesktopToolKind::Goal => {
- let live_config = match ctx.load_config().await {
+ let live_config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/desktop/notifications/rpc.rs b/crates/openhuman-core/src/desktop/notifications/rpc.rs
index 0e19fcca23..e2c97a67b6 100644
--- a/crates/openhuman-core/src/desktop/notifications/rpc.rs
+++ b/crates/openhuman-core/src/desktop/notifications/rpc.rs
@@ -8,6 +8,7 @@
//! - `notification_mark_acted` — mark a single notification as acted upon
//! - `notification_stats` — return aggregate pipeline statistics
+use crate::core::runtime::DispatchCtx;
use chrono::Utc;
use serde_json::{json, Map, Value};
use uuid::Uuid;
@@ -35,7 +36,7 @@ use super::types::{
///
/// Writes the record immediately, returns the new `id`, then spawns a
/// background task to run the triage pipeline and back-fill the score.
-pub async fn handle_ingest(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_ingest(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let ingest_started_at = Utc::now();
let config = ctx.load_config().await?;
@@ -257,7 +258,7 @@ pub async fn handle_ingest(params: Map<String, Value>) -> Result<Value, String>
///
/// Optional params: `provider` (string), `limit` (u64), `offset` (u64),
/// `min_score` (f64).
-pub async fn handle_list(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_list(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let provider = params
@@ -294,7 +295,7 @@ pub async fn handle_list(params: Map<String, Value>) -> Result<Value, String> {
// ─────────────────────────────────────────────────────────────────────────────
/// Mark a single notification as read.
-pub async fn handle_mark_read(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_mark_read(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let id = params
@@ -313,7 +314,7 @@ pub async fn handle_mark_read(params: Map<String, Value>) -> Result<Value, Strin
}
/// Read notification routing settings for a provider.
-pub async fn handle_settings_get(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_settings_get(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let provider = params
.get("provider")
@@ -326,7 +327,7 @@ pub async fn handle_settings_get(params: Map<String, Value>) -> Result<Value, St
}
/// Upsert notification routing settings for a provider.
-pub async fn handle_settings_set(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_settings_set(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let req: NotificationSettingsUpsertRequest = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("[notification_intel] invalid settings_set params: {e}"))?;
@@ -347,7 +348,7 @@ pub async fn handle_settings_set(params: Map<String, Value>) -> Result<Value, St
// ─────────────────────────────────────────────────────────────────────────────
/// Mark a single notification as dismissed.
-pub async fn handle_dismiss(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_dismiss(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let id = params
.get("id")
@@ -367,7 +368,7 @@ pub async fn handle_dismiss(params: Map<String, Value>) -> Result<Value, String>
// ─────────────────────────────────────────────────────────────────────────────
/// Mark a single notification as acted upon.
-pub async fn handle_mark_acted(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_mark_acted(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let id = params
.get("id")
@@ -396,7 +397,7 @@ pub async fn handle_mark_acted(params: Map<String, Value>) -> Result<Value, Stri
/// closed / disconnected — these are otherwise lost because the live channel
/// is broadcast-only. Optional params: `only_unread` (bool, default true),
/// `limit` (u64, default 100).
-pub async fn handle_core_list(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_core_list(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let only_unread = params
@@ -420,7 +421,7 @@ pub async fn handle_core_list(params: Map<String, Value>) -> Result<Value, Strin
/// Mark a persisted core notification as read so it isn't re-surfaced on the
/// next sync-down.
-pub async fn handle_core_mark_read(params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_core_mark_read(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
let id = params
.get("id")
@@ -440,7 +441,7 @@ pub async fn handle_core_mark_read(params: Map<String, Value>) -> Result<Value,
// ─────────────────────────────────────────────────────────────────────────────
/// Return aggregate pipeline statistics.
-pub async fn handle_stats(_params: Map<String, Value>) -> Result<Value, String> {
+pub async fn handle_stats(ctx: &DispatchCtx, _params: Map<String, Value>) -> Result<Value, String> {
let config = ctx.load_config().await?;
tracing::debug!("[notification_intel] stats requested");
diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rs
index 9d8147adc8..7d02ec18a0 100644
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@ -22,6 +22,7 @@
//! [`FlowMemoryRecallTool`] only ever reads with a flow tag filter
//! (`flow:<id>` or `flows`), so it never reaches the user's own memory.
+use crate::core::runtime::DispatchCtx;
use crate::tools::schema_cache::static_schema;
use std::sync::Arc;
@@ -335,7 +336,7 @@ impl Tool for FlowMemoryRecallTool {
.and_then(serde_json::Value::as_u64)
.map_or(5, |v| v as usize);
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
@@ -472,7 +473,7 @@ impl Tool for FlowMemoryRememberTool {
));
}
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/flows/ops/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rs
index fbcbd0cea1..377689dec1 100644
--- a/crates/openhuman-core/src/flows/ops/streaming.rs
+++ b/crates/openhuman-core/src/flows/ops/streaming.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
// ─────────────────────────────────────────────────────────────────────────────
@@ -90,7 +91,7 @@ pub(super) fn attach_flow_progress_bridge(
/// path, so segmentation/reaction match a normal turn), a failure publishes a
/// `chat_error`. Broadcast as `"system"` so any viewer of the thread receives
/// it (frontend keys by `thread_id`).
-pub(super) async fn finalize_flow_stream(
+pub(super) async fn finalize_flow_stream(ctx: &DispatchCtx,
target: &FlowStreamTarget,
result: &Result<String, String>,
prompt: &str,
diff --git a/crates/openhuman-core/src/hooks/prompt_eval.rs b/crates/openhuman-core/src/hooks/prompt_eval.rs
index 9934e6ffbc..caf0d20033 100644
--- a/crates/openhuman-core/src/hooks/prompt_eval.rs
+++ b/crates/openhuman-core/src/hooks/prompt_eval.rs
@@ -11,6 +11,7 @@
//! keeps the override scoped to this evaluation: nothing persists, and a
//! concurrent turn on the real config is unaffected.
+use crate::core::runtime::DispatchCtx;
use crate::config::schema::Config;
/// Ask the model to judge a hook condition, returning its raw answer.
@@ -18,7 +19,7 @@ use crate::config::schema::Config;
/// Errors are strings rather than `anyhow` because every caller folds them into
/// the fail-open / fail-closed decision, where the only thing that matters is
/// the message.
-pub async fn evaluate(instruction: &str, model: Option<&str>) -> Result<String, String> {
+pub async fn evaluate(ctx: &DispatchCtx, instruction: &str, model: Option<&str>) -> Result<String, String> {
let mut config = ctx.load_config()
.await
.map_err(|error| format!("loading config for prompt hook: {error}"))?;
diff --git a/crates/openhuman-core/src/hooks/shell.rs b/crates/openhuman-core/src/hooks/shell.rs
index ac5e6b3ce2..be58a0e44a 100644
--- a/crates/openhuman-core/src/hooks/shell.rs
+++ b/crates/openhuman-core/src/hooks/shell.rs
@@ -7,6 +7,7 @@
//! command into that selection. A selection that never resolved yields a command
//! that fails to spawn, so a hook never silently runs under a different shell.
+use crate::core::runtime::DispatchCtx;
use std::sync::{OnceLock, RwLock};
use tinybox_bus::ShellInvocation;
@@ -26,7 +27,7 @@ fn slot() -> &'static RwLock<Option<ShellInvocation>> {
/// Ask TinyBox which shell it selects and remember it for [`command`].
///
/// A failure is logged and leaves any earlier selection in place.
-pub(super) async fn resolve() {
+pub(super) async fn resolve(ctx: &DispatchCtx, ) {
#[cfg(feature = "modules")]
{
let config = match ctx.load_config().await {
diff --git a/crates/openhuman-core/src/inference/embedding_host/rpc/settings.rs b/crates/openhuman-core/src/inference/embedding_host/rpc/settings.rs
index 52dfbf68a5..99bb34e691 100644
--- a/crates/openhuman-core/src/inference/embedding_host/rpc/settings.rs
+++ b/crates/openhuman-core/src/inference/embedding_host/rpc/settings.rs
@@ -1,6 +1,7 @@
//! Embedding settings: reading the current configuration and applying an
//! update, including the save-time verification of a custom endpoint.
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
use crate::core::Outcome;
use crate::security::credentials::AuthService;
@@ -192,7 +193,7 @@ pub async fn get_settings(config: &Config) -> Result<Outcome<serde_json::Value>,
/// Updates embedding provider/model/dimensions. Nothing persisted depends on
/// the embedding signature any more (memory v2 engines embed server-side), so a
/// change applies directly.
-pub async fn update_settings(
+pub async fn update_settings(ctx: &DispatchCtx,
provider: Option<String>,
model: Option<String>,
dimensions: Option<usize>,
diff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rs
index 72deb77835..684a7ef6c8 100644
--- a/crates/openhuman-core/src/inference/ops.rs
+++ b/crates/openhuman-core/src/inference/ops.rs
@@ -1,5 +1,6 @@
//! JSON-RPC controller surface for inference operations.
+use crate::core::runtime::DispatchCtx;
use crate::config::rpc as config_rpc;
use crate::config::Config;
use crate::core::Outcome;
@@ -272,7 +273,7 @@ pub async fn inference_update_model_settings(
result
}
-pub async fn inference_update_local_settings(
+pub async fn inference_update_local_settings(ctx: &DispatchCtx,
update: config_rpc::LocalAiSettingsPatch,
) -> Result<Outcome<Value>, String> {
debug!("{LOG_PREFIX} update_local_settings:start");
diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rs
index e43e63062b..6bd2537f8e 100644
--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs
+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs
@@ -8,6 +8,7 @@ pub mod savings;
pub mod schemas;
pub mod tools;
+use crate::core::runtime::DispatchCtx;
use tinyjuice_bus::names::methods;
use tinyjuice_bus::types::{AgentTokenjuiceCompression, CompressorKind};
@@ -439,7 +440,7 @@ pub(crate) mod module_stub;
mod repl_module_tests;
/// Run a typed query inside TinyJuice; cached originals stay inside the module.
-pub async fn query(
+pub async fn query(ctx: &DispatchCtx,
request: tinyjuice_bus::wire::QueryRequest,
) -> Result<tinyjuice_bus::wire::QueryResponse, String> {
let config = ctx.load_config().await?;
@@ -458,7 +459,7 @@ pub(crate) async fn query_for_config(
}
/// Extract HTML through the compiled module independently of compression settings.
-pub async fn extract_html(html: String) -> Result<String, String> {
+pub async fn extract_html(ctx: &DispatchCtx, html: String) -> Result<String, String> {
let config = ctx.load_config().await?;
let response: tinyjuice_bus::wire::HtmlResponse = client(&config)
.call("tinyjuice", methods::EXTRACT_HTML, (html,))
diff --git a/crates/openhuman-core/src/integrations/composio/action_tool.rs b/crates/openhuman-core/src/integrations/composio/action_tool.rs
index b6d526d183..9dc42b9b2a 100644
--- a/crates/openhuman-core/src/integrations/composio/action_tool.rs
+++ b/crates/openhuman-core/src/integrations/composio/action_tool.rs
@@ -28,6 +28,7 @@
//! tool migration in
//! [`super::tools::ComposioExecuteTool`].
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use async_trait::async_trait;
@@ -162,7 +163,7 @@ impl ComposioActionTool {
/// The live config for one call: a reload anchored to the spawn-time
/// snapshot when there is one, else the core's read path.
- async fn live_config(&self) -> Result<Config, String> {
+ async fn live_config(&self, ctx: &DispatchCtx) -> Result<Config, String> {
match self.config.as_deref() {
Some(snapshot) => super::tools::live_composio_config(snapshot).await,
None => ctx.load_config().await,
diff --git a/crates/openhuman-core/src/integrations/composio/bus/config_changed_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/config_changed_subscriber.rs
index 645c48f263..847c11483a 100644
--- a/crates/openhuman-core/src/integrations/composio/bus/config_changed_subscriber.rs
+++ b/crates/openhuman-core/src/integrations/composio/bus/config_changed_subscriber.rs
@@ -1,6 +1,7 @@
//! Drops and eagerly re-warms the integrations cache when the user flips
//! Composio between backend and direct mode.
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use tinybus::EventHandler;
@@ -62,7 +63,7 @@ impl EventHandler<DomainEvent> for ComposioConfigChangedSubscriber {
ops::invalidate_connected_integrations_cache();
tokio::spawn(async move {
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
tracing::debug!(
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.rs
index 9feaa9aa0b..00e5e27127 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
@@ -3,6 +3,7 @@
//! onboarding) fetches the account profile for toolkits with a native
//! identity provider.
+use crate::core::runtime::DispatchCtx;
use std::time::Duration;
use async_trait::async_trait;
@@ -93,7 +94,7 @@ impl EventHandler<DomainEvent> for ComposioConnectionCreatedSubscriber {
}
}
-async fn on_connection_created(toolkit: String, connection_id: String) {
+async fn on_connection_created(ctx: &DispatchCtx, toolkit: String, connection_id: String) {
let config = match ctx.load_config().await {
Ok(c) => c,
Err(e) => {
diff --git a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs
index 70899c3a97..68d687eb5f 100644
--- a/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs
+++ b/crates/openhuman-core/src/integrations/composio/bus/trigger_subscriber.rs
@@ -1,5 +1,6 @@
//! Logs and (when enabled) triages `ComposioTriggerReceived` events.
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use tinybus::EventHandler;
@@ -82,7 +83,7 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
// let the event through rather than silently dropping it. The
// existing env-var / config triage flags below remain the
// backend-mode gates.
- if let Ok(config) = ctx.load_config().await {
+ if let Ok(config) = DispatchCtx::ambient().load_config().await {
if config.composio.mode == crate::config::schema::COMPOSIO_MODE_DIRECT {
tracing::info!(
toolkit = %toolkit,
@@ -94,7 +95,7 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
}
if let Some(store) = trigger_history::global() {
- match ctx.load_config().await {
+ match DispatchCtx::ambient().load_config().await {
Ok(config) => {
let event = super::super::types::ComposioTriggerEvent {
toolkit: toolkit.clone(),
@@ -128,7 +129,7 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
// remains a global emergency kill-switch that works even when the
// config file is corrupt. Fail-open on load error: if we can't read
// the config we let triage run rather than silently drop events.
- match ctx.load_config().await {
+ match DispatchCtx::ambient().load_config().await {
Ok(config) => {
if config.composio.triage_disabled {
tracing::debug!(
diff --git a/crates/openhuman-core/src/integrations/composio/ops/direct_mode.rs b/crates/openhuman-core/src/integrations/composio/ops/direct_mode.rs
index 6e4f770316..83de45bc56 100644
--- a/crates/openhuman-core/src/integrations/composio/ops/direct_mode.rs
+++ b/crates/openhuman-core/src/integrations/composio/ops/direct_mode.rs
@@ -1,5 +1,6 @@
//! Direct mode (BYO API key) ops.
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
use crate::core::Outcome;
@@ -71,7 +72,7 @@ pub async fn composio_get_mode(config: &Config) -> OpResult<Outcome<serde_json::
/// (optionally) flip `config.composio.mode` over to `"direct"`.
///
/// **Logging redacts the key** — only its length and presence are recorded.
-pub async fn composio_set_api_key(
+pub async fn composio_set_api_key(ctx: &DispatchCtx,
config: &Config,
api_key: &str,
activate_direct: bool,
@@ -131,7 +132,7 @@ pub async fn composio_set_api_key(
/// Clear the stored direct-mode API key and reset
/// `config.composio.mode` back to `"backend"`.
-pub async fn composio_clear_api_key(config: &Config) -> OpResult<Outcome<serde_json::Value>> {
+pub async fn composio_clear_api_key(ctx: &DispatchCtx, config: &Config) -> OpResult<Outcome<serde_json::Value>> {
tracing::debug!("[composio-direct] clear_api_key");
crate::security::credentials::clear_composio_api_key(config)
.await
diff --git a/crates/openhuman-core/src/integrations/task_sources/bus.rs b/crates/openhuman-core/src/integrations/task_sources/bus.rs
index 12d29ab736..5734d8413a 100644
--- a/crates/openhuman-core/src/integrations/task_sources/bus.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/bus.rs
@@ -5,6 +5,7 @@
//! `ConnectionCreated` fetch so freshly-connected work shows up without
//! waiting for the next periodic tick.
+use crate::core::runtime::DispatchCtx;
use std::sync::{Arc, OnceLock};
use async_trait::async_trait;
@@ -62,7 +63,7 @@ impl EventHandler<DomainEvent> for TaskSourcesConnectionSubscriber {
/// loaded inside it — so an agent whose own config disables task sources is
/// skipped even when the process config enables them, and the other way
/// round.
-async fn fire_in_scope(provider: ProviderSlug, toolkit: &str, connection_id: &str) {
+async fn fire_in_scope(ctx: &DispatchCtx, provider: ProviderSlug, toolkit: &str, connection_id: &str) {
let config = match ctx.load_config().await {
Ok(config) => config,
Err(e) => {
diff --git a/crates/openhuman-core/src/integrations/task_sources/periodic.rs b/crates/openhuman-core/src/integrations/task_sources/periodic.rs
index d75a7db6d9..40a946260a 100644
--- a/crates/openhuman-core/src/integrations/task_sources/periodic.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/periodic.rs
@@ -8,6 +8,7 @@
//! process-global map, and errors are logged and swallowed so the loop
//! never unwinds.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -111,7 +112,7 @@ async fn run_loop() {
/// Run a single scheduler tick. `pub(crate)` so tests can drive ticks
/// without the real `interval`.
-pub(crate) async fn run_one_tick() -> Result<(), String> {
+pub(crate) async fn run_one_tick(ctx: &DispatchCtx, ) -> Result<(), String> {
let config = ctx.load_config()
.await
.map_err(|e| format!("load_config: {e}"))?;
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index 5916105ddf..65bec34f31 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -17,6 +17,7 @@
//! Turns are not ingested from the bus: the session host calls the lifecycle
//! hooks itself, under the session's own config (`lifecycle::hooks`).
+use crate::core::runtime::DispatchCtx;
use std::sync::{Arc, OnceLock};
use async_trait::async_trait;
@@ -57,7 +58,7 @@ impl EventHandler<DomainEvent> for PendingDeletionsSubscriber {
if kind == "cleared" {
return;
}
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
tracing::debug!(error = %error, "[memory:bus] config unavailable; deletions wait");
@@ -96,7 +97,7 @@ impl EventHandler<DomainEvent> for SystemJobsSubscriber {
if job != SOURCES_SYNC_JOB && job != BACKGROUND_JOB {
return;
}
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
tracing::debug!(error = %error, job = %job, "[memory:bus] config unavailable");
diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rs
index 4b9df781bf..0f08c45eef 100644
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@ -34,7 +34,7 @@ fn finish<T: Serialize>(result: MemoryResult<T>) -> Result<Value, String> {
to_json(result.map_err(String::from)?)
}
-async fn load() -> Result<Config, String> {
+async fn load(ctx: &DispatchCtx, ) -> Result<Config, String> {
ctx.load_config().await
}
diff --git a/crates/openhuman-core/src/platform/socket/ops.rs b/crates/openhuman-core/src/platform/socket/ops.rs
index a899d8e2bb..e3a75eccd4 100644
--- a/crates/openhuman-core/src/platform/socket/ops.rs
+++ b/crates/openhuman-core/src/platform/socket/ops.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use crate::platform::socket::models::SocketState;
use super::SocketManager;
@@ -49,7 +50,7 @@ async fn connect_with_session_using(
Ok(manager.get_state())
}
-pub async fn connect_with_session(manager: &SocketManager) -> Result<SocketState, String> {
+pub async fn connect_with_session(ctx: &DispatchCtx, manager: &SocketManager) -> Result<SocketState, String> {
log::info!("[socket:rpc] connect_with_session — resolving credentials");
let config = std::sync::Arc::new(ctx.load_config().await?);
let api_url = crate::backend::require_base_url(&config.api_url)?;
diff --git a/crates/openhuman-core/src/platform/update/ops.rs b/crates/openhuman-core/src/platform/update/ops.rs
index f40c1a3359..4f3c0edf77 100644
--- a/crates/openhuman-core/src/platform/update/ops.rs
+++ b/crates/openhuman-core/src/platform/update/ops.rs
@@ -1,5 +1,6 @@
//! JSON-RPC / CLI controller surface for the update domain.
+use crate::core::runtime::DispatchCtx;
use std::path::PathBuf;
use serde_json::Value;
@@ -9,7 +10,7 @@ use crate::core::Outcome;
use crate::platform::update;
use crate::platform::update::types::{UpdateApplyResult, UpdateInfo, UpdateRunResult, VersionInfo};
-async fn load_update_policy() -> Result<UpdateConfig, String> {
+async fn load_update_policy(ctx: &DispatchCtx, ) -> Result<UpdateConfig, String> {
ctx.load_config()
.await
.map(|cfg| cfg.update)
diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs
index 683fb0291a..51b4e9ee1d 100644
--- a/crates/openhuman-core/src/sandbox/ops.rs
+++ b/crates/openhuman-core/src/sandbox/ops.rs
@@ -1,6 +1,7 @@
//! Sandbox backend operations — policy resolution, backend creation, and
//! routed execution.
+use crate::core::runtime::DispatchCtx;
use super::docker;
use super::types::{
ElevatedOp, SandboxBackendHandle, SandboxBackendKind, SandboxExecRequest, SandboxExecResult,
@@ -45,7 +46,7 @@ pub fn sandbox_off_value(value: Option<&str>) -> bool {
/// Whether a command tool must use the sandbox execution path. An explicit
/// backend in the active config is an operator requirement even when the
/// agent definition uses the usual `SandboxMode::None` default.
-pub async fn command_requires_sandbox(sandbox_mode: Option<SandboxMode>) -> Result<bool, String> {
+pub async fn command_requires_sandbox(ctx: &DispatchCtx, sandbox_mode: Option<SandboxMode>) -> Result<bool, String> {
if crate::core::runtime::is_saas() {
// Every SaaS command must enter the per-user container path, including
// language tools whose agent definition does not request a sandbox.
@@ -73,7 +74,7 @@ pub async fn command_requires_sandbox(sandbox_mode: Option<SandboxMode>) -> Resu
/// Resolve the policy for a command tool before building its command line.
/// SaaS always uses the user's container; other hosts apply the operator's
/// backend selection while retaining an agent-level sandbox requirement.
-pub(crate) async fn resolve_command_policy(
+pub(crate) async fn resolve_command_policy(ctx: &DispatchCtx,
action_dir: &Path,
state_dir: &Path,
) -> Result<SandboxPolicy, String> {
@@ -222,7 +223,7 @@ pub(crate) fn local_status_for_jail(
}
}
-pub async fn create_sandbox_backend(policy: &SandboxPolicy) -> SandboxBackendHandle {
+pub async fn create_sandbox_backend(ctx: &DispatchCtx, policy: &SandboxPolicy) -> SandboxBackendHandle {
if policy.backend != SandboxBackendKind::Docker {
return create_sandbox_backend_with_config(policy, &crate::config::Config::default())
.await
@@ -298,7 +299,7 @@ pub async fn execute_in_sandbox(
/// [`execute_in_sandbox`] that feeds `meter` with the command's output as it
/// streams (the native backends; Docker reports elapsed time only), for the
/// shell tool's progress line.
-pub(crate) async fn execute_in_sandbox_metered(
+pub(crate) async fn execute_in_sandbox_metered(ctx: &DispatchCtx,
policy: &SandboxPolicy,
command: &str,
working_dir: &Path,
diff --git a/crates/openhuman-core/src/search/bus.rs b/crates/openhuman-core/src/search/bus.rs
index 2c0e76baeb..9f0891830e 100644
--- a/crates/openhuman-core/src/search/bus.rs
+++ b/crates/openhuman-core/src/search/bus.rs
@@ -5,6 +5,7 @@
//! Without this subscriber a login would only reach it on the next search
//! call, and a logout would leave the old credential in the module until then.
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use tinybus::EventHandler;
@@ -28,7 +29,7 @@ impl EventHandler<DomainEvent> for CredentialRefreshSubscriber {
let DomainEvent::CredentialChanged { kind } = event else {
return;
};
- let config = match ctx.load_config().await {
+ let config = match DispatchCtx::ambient().load_config().await {
Ok(config) => config,
Err(error) => {
tracing::warn!(kind = %kind, %error, "[search][bus] config unavailable; skipping refresh");
diff --git a/crates/openhuman-core/src/search/tools.rs b/crates/openhuman-core/src/search/tools.rs
index 1b8e0e828f..76aa8e7137 100644
--- a/crates/openhuman-core/src/search/tools.rs
+++ b/crates/openhuman-core/src/search/tools.rs
@@ -8,6 +8,7 @@
//! agent's config carries host-pinned search keys, which make it the config
//! the call runs under.
+use crate::core::runtime::DispatchCtx;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
@@ -116,7 +117,7 @@ impl TinySearchTool {
&self.spec
}
- async fn live_config(&self) -> anyhow::Result<Config> {
+ async fn live_config(&self, ctx: &DispatchCtx) -> anyhow::Result<Config> {
match &self.config {
Some(config) => Ok(config.as_ref().clone()),
None => ctx.load_config()
diff --git a/crates/openhuman-core/src/security/credentials/bus.rs b/crates/openhuman-core/src/security/credentials/bus.rs
index c7209084dc..5ecf5d4192 100644
--- a/crates/openhuman-core/src/security/credentials/bus.rs
+++ b/crates/openhuman-core/src/security/credentials/bus.rs
@@ -23,6 +23,7 @@
//! `OPENHUMAN-TAURI-1T` (5,414 Sentry events from one user's
//! cron-driven LLM calls after session expiry).
+use crate::core::runtime::DispatchCtx;
use crate::core::events::DomainEvent;
use crate::cron::scheduler_gate;
use async_trait::async_trait;
@@ -63,7 +64,7 @@ impl EventHandler<DomainEvent> for SessionExpiredSubscriber {
impl SessionExpiredSubscriber {
/// [`EventHandler::handle`] with the process mode passed in, so the SaaS
/// early return is testable without the process-wide mode lock.
- pub(crate) async fn handle_with(&self, saas: bool, event: &DomainEvent) {
+ pub(crate) async fn handle_with(&self, ctx: &DispatchCtx, saas: bool, event: &DomainEvent) {
let DomainEvent::SessionExpired { source, reason } = event else {
return;
};
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index e61cdb859f..de0347979e 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -9,6 +9,7 @@
//! user's directory, persist the profile, rebind its process globals, start
//! the credential-gated services, open the scheduler gate and scope Sentry.
+use crate::core::runtime::DispatchCtx;
use serde::Deserialize;
use serde_json::{json, Value};
@@ -505,7 +506,7 @@ pub async fn clear_credential(
/// teardown, user-dir deactivation, service stop, rebind to the signed-out
/// workspace, and Sentry / identity clear. Callers hold
/// [`CREDENTIAL_MUTATION_LOCK`].
-async fn clear_session_credential(config: &Config) -> Result<Outcome<bool>, String> {
+async fn clear_session_credential(ctx: &DispatchCtx, config: &Config) -> Result<Outcome<bool>, String> {
let mut logs = Vec::new();
crate::cron::scheduler_gate::set_signed_out(true);
#[cfg(feature = "web3")]
diff --git a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
index 9785dc8a1b..58d4b622b5 100644
--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
@@ -7,6 +7,7 @@
//! installed or removed. They know nothing about *how* the credential was
//! obtained — that is the host's business.
+use crate::core::runtime::DispatchCtx;
use crate::config::{
default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir,
write_active_user_id, Config,
@@ -109,7 +110,7 @@ pub(super) fn deactivate_user_scope() -> Result<(), String> {
/// The config that reflects the current `active_user.toml` — reloaded after an
/// activation so credentials, keys and workspaces land in the user-scoped
/// location — or `fallback` when the reload fails.
-pub(super) async fn reload_config_or(_fallback: &Config) -> Result<Config, String> {
+pub(super) async fn reload_config_or(ctx: &DispatchCtx, _fallback: &Config) -> Result<Config, String> {
ctx.load_config()
.await
.map_err(|error| error.to_string())
diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rs
index 1454461242..5a52ca0985 100644
--- a/crates/openhuman-core/src/security/credentials/session_support.rs
+++ b/crates/openhuman-core/src/security/credentials/session_support.rs
@@ -1,5 +1,6 @@
//! Session/auth helpers used by RPC and [`crate::core_server::helpers`].
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
use super::profiles::{AuthProfile, AuthProfileKind, TokenSet};
@@ -65,7 +66,7 @@ pub fn is_local_session_token(token: &str) -> bool {
/// credential. A backend-only route may report a missing session or 401 while
/// this credential remains valid; those errors must not broadcast sign-out.
/// A failed lookup leaves the ordinary session-expiry path in place.
-pub async fn current_session_is_local() -> bool {
+pub async fn current_session_is_local(ctx: &DispatchCtx, ) -> bool {
let Ok(config) = ctx.load_config().await else {
return false;
};
diff --git a/crates/openhuman-core/src/security/devices/bus.rs b/crates/openhuman-core/src/security/devices/bus.rs
index a5e11819b7..96eaa9a322 100644
--- a/crates/openhuman-core/src/security/devices/bus.rs
+++ b/crates/openhuman-core/src/security/devices/bus.rs
@@ -7,6 +7,7 @@
//! - Persisting the `PairedDevice` record after a successful handshake.
//! - Publishing `DomainEvent::DevicePaired / DevicePeerOnline / DevicePeerOffline`.
+use crate::core::runtime::DispatchCtx;
use std::sync::{Arc, OnceLock};
use crate::core::bus::BUS;
@@ -176,7 +177,7 @@ fn handle_peer_offline(channel_id: &str) {
/// Handle an incoming `tunnel:frame` — first frame from the device contains its
/// X25519 public key sealed to the core's public key. After successful decryption
/// we derive the shared secret and persist the `PairedDevice`.
-async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
+async fn handle_tunnel_frame(ctx: &DispatchCtx, channel_id: &str, payload_b64: &str) {
log::debug!(
"[devices/bus] tunnel:frame channel_id={} payload_len={}",
channel_id,
diff --git a/crates/openhuman-core/src/security/devices/owner.rs b/crates/openhuman-core/src/security/devices/owner.rs
index b0257d2e95..427dc06fc7 100644
--- a/crates/openhuman-core/src/security/devices/owner.rs
+++ b/crates/openhuman-core/src/security/devices/owner.rs
@@ -13,6 +13,7 @@
//!
//! `None` means the `local` scope (a single-user host, or no backend).
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
@@ -62,7 +63,7 @@ pub(super) type OwnerLookupFailed = crate::storage::agents::LookupFailed;
/// Whether the current scope holds `channel_id` as a live (not revoked)
/// paired device. The configuration is loaded inside the scope: in SaaS mode
/// loading it needs an acting agent, which the tunnel task does not have.
-async fn has_live_device(channel_id: &str) -> Result<bool, String> {
+async fn has_live_device(ctx: &DispatchCtx, channel_id: &str) -> Result<bool, String> {
let config = ctx.load_config()
.await
.map_err(|error| format!("load config: {error}"))?;
@@ -73,7 +74,7 @@ async fn has_live_device(channel_id: &str) -> Result<bool, String> {
/// Whether the current scope holds `channel_id` as a revoked device (a missing
/// row is not revoked).
-async fn is_revoked(channel_id: &str) -> Result<bool, String> {
+async fn is_revoked(ctx: &DispatchCtx, channel_id: &str) -> Result<bool, String> {
let config = ctx.load_config()
.await
.map_err(|error| format!("load config: {error}"))?;
diff --git a/crates/openhuman-core/src/security/ops.rs b/crates/openhuman-core/src/security/ops.rs
index ffb147d3ea..2662b5dd81 100644
--- a/crates/openhuman-core/src/security/ops.rs
+++ b/crates/openhuman-core/src/security/ops.rs
@@ -1,5 +1,6 @@
//! JSON-RPC / CLI controller surface for security policy introspection.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use crate::config::Config;
@@ -24,7 +25,7 @@ pub fn security_policy_info_for_config(config: &Config) -> Outcome<serde_json::V
Outcome::single_log(payload, "security_policy_info computed from active config")
}
-pub async fn load_and_get_security_policy_info() -> Result<Outcome<serde_json::Value>, String> {
+pub async fn load_and_get_security_policy_info(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
let config = ctx.load_config().await?;
Ok(security_policy_info_for_config(&config))
}
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index f32fcb3002..73eae612a2 100644
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@ -1,6 +1,7 @@
//! Create, read, update, and delete operations for conversation threads and
//! their messages.
+use crate::core::runtime::DispatchCtx;
use super::support::{
counts, envelope, message_to_record, record_to_message, run_to_completion, thread_to_summary,
workspace_dir,
@@ -151,7 +152,7 @@ pub async fn transcript_search(
}
/// Appends a message to a conversation thread.
-pub async fn message_append(
+pub async fn message_append(ctx: &DispatchCtx,
request: AppendConversationMessageRequest,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
let origin = crate::core::runtime::CoreContext::current_turn_origin();
@@ -404,7 +405,7 @@ pub async fn delete_after(
/// [`run_to_completion`] task, so a caller that disconnects mid-delete cannot
/// leave the thread gone from the store with its sessions, sub-agents and turn
/// snapshot still live.
-pub async fn thread_delete(
+pub async fn thread_delete(ctx: &DispatchCtx,
request: DeleteConversationThreadRequest,
) -> Result<Outcome<ApiEnvelope<DeleteConversationThreadResponse>>, String> {
let config = ctx.load_config()
diff --git a/crates/openhuman-core/src/threads/store/bus.rs b/crates/openhuman-core/src/threads/store/bus.rs
index 8c49a5cbdd..e0cbe1f459 100644
--- a/crates/openhuman-core/src/threads/store/bus.rs
+++ b/crates/openhuman-core/src/threads/store/bus.rs
@@ -21,6 +21,7 @@
//! promise, and this file's behaviour is untouched by the move — which matters,
//! because it decides the id under which channel turns are persisted.
+use crate::core::runtime::DispatchCtx;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock, RwLock};
@@ -347,7 +348,7 @@ struct ChannelTurnDescriptor<'a> {
source: &'a str,
}
-async fn persist_channel_turn(
+async fn persist_channel_turn(ctx: &DispatchCtx,
workspace_dir: &Path,
descriptor: ChannelTurnDescriptor<'_>,
) -> Result<(), String> {
diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rs
index 9a0f1682e0..f4e136543e 100644
--- a/crates/openhuman-core/src/tools/impl/network/host.rs
+++ b/crates/openhuman-core/src/tools/impl/network/host.rs
@@ -5,6 +5,7 @@
//! `[http_request]` defaults, TinyJuice for page extraction, and (with the
//! `web3` feature) the x402 payment flow.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
#[cfg(feature = "web3")]
@@ -290,7 +291,7 @@ mod x402 {
.ok_or_else(|| {
"402 response is missing a valid PAYMENT-REQUIRED header".to_string()
})?;
- let config = ctx.load_config()
+ let config = DispatchCtx::ambient().load_config()
.await
.map_err(|error| format!("x402 payment failed: {error}"))?;
declined_when_wallet_off(&config)?;
diff --git a/crates/openhuman-core/src/tools/impl/presentation/mod.rs b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
index 4fadb0acd0..510a19f52e 100644
--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs
@@ -27,6 +27,7 @@
//! #3026 Files panel, and the orchestrator grounding rule in #3029
//! continue to work without change.
+use crate::core::runtime::DispatchCtx;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -82,7 +83,7 @@ impl ImageInspector for ModuleImageInspector<'_> {
let config = match self.config {
Some(config) => config,
None => {
- loaded = ctx.load_config()
+ loaded = DispatchCtx::ambient().load_config()
.await
.map_err(|error| format!("config unavailable: {error}"))?;
&loaded
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index c7e6e6f81c..29d85e9042 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::shell_description::{command_param_description, shell_description};
#[cfg(feature = "modules")]
use super::shell_support::container_environment;
@@ -334,7 +335,7 @@ impl ShellTool {
}
async fn run_with_security_in_context(
- &self,
+ &self, ctx: &DispatchCtx,
command: &str,
requested_timeout: Option<u64>,
context: Option<&dyn ToolRunContext>,
diff --git a/crates/openhuman-core/src/tools/schemas/web_search.rs b/crates/openhuman-core/src/tools/schemas/web_search.rs
index 0dd3c8f1f5..1062f17955 100644
--- a/crates/openhuman-core/src/tools/schemas/web_search.rs
+++ b/crates/openhuman-core/src/tools/schemas/web_search.rs
@@ -29,7 +29,7 @@ fn optional_text(params: &Map<String, Value>, key: &str) -> Option<String> {
}
/// Run one role tool and shape the response for RPC callers.
-async fn run_role_tool(
+async fn run_role_tool(ctx: &DispatchCtx,
tool: &'static str,
arguments: Value,
method: &str,
diff --git a/crates/openhuman-core/src/web3/module_tools.rs b/crates/openhuman-core/src/web3/module_tools.rs
index cd8b5f6de4..70b6ff3f54 100644
--- a/crates/openhuman-core/src/web3/module_tools.rs
+++ b/crates/openhuman-core/src/web3/module_tools.rs
@@ -1,5 +1,6 @@
//! Agent tool adapters that route Web3 operations through the TinyWallet bus.
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use serde_json::Value;
use tinytools::{Tool, ToolCallOptions, ToolExposure, ToolResult};
@@ -60,7 +61,7 @@ impl Tool for Web3ModuleTool {
impl Web3ModuleTool {
/// 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> {
diff --git a/crates/openhuman-core/src/web3/wallet/execution.rs b/crates/openhuman-core/src/web3/wallet/execution.rs
index 48f9719f8b..fa628d85ad 100644
--- a/crates/openhuman-core/src/web3/wallet/execution.rs
+++ b/crates/openhuman-core/src/web3/wallet/execution.rs
@@ -2,6 +2,7 @@
//! This host supplies configuration, custody, transport and approvals; wallet
//! algorithms and user-scoped service state remain in the compiled module.
+use crate::core::runtime::DispatchCtx;
use crate::config::rpc as config_rpc;
use crate::core::Outcome;
use crate::modules::{wallet as wallet_module, wallet_service};
@@ -19,7 +20,7 @@ use tinywallet_bus::wire::{EvmNetwork, WalletNetworkDefaults};
use super::ops::WalletChain;
/// Default row for every supported network, with the host's endpoints.
-pub async fn network_defaults() -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {
+pub async fn network_defaults(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {
let config = ctx.load_config().await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
@@ -38,7 +39,7 @@ pub async fn network_defaults() -> Result<Outcome<Vec<WalletNetworkDefaults>>, S
}
/// Every asset the wallet catalogues.
-pub async fn supported_assets() -> Result<Outcome<Vec<SupportedAsset>>, String> {
+pub async fn supported_assets(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<SupportedAsset>>, String> {
let config = ctx.load_config().await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
@@ -57,7 +58,7 @@ pub async fn supported_assets() -> Result<Outcome<Vec<SupportedAsset>>, String>
}
/// Which chains have an account and a provider.
-pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {
+pub async fn chain_status(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<ChainStatus>>, String> {
let config = ctx.load_config().await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
@@ -76,7 +77,7 @@ pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {
}
/// Live native balances.
-pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {
+pub async fn balances(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<BalanceInfo>>, String> {
let config = ctx.load_config().await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
@@ -95,7 +96,7 @@ pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {
}
/// Validate a transfer and store a quote for it.
-pub async fn prepare_transfer(
+pub async fn prepare_transfer(ctx: &DispatchCtx,
params: PrepareTransferParams,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
) -> Result<Outcome<PreparedTransaction>, String> {
@@ -110,7 +111,7 @@ pub async fn prepare_transfer(
}
/// Confirm and execute a prepared transfer.
-pub async fn execute_prepared(
+pub async fn execute_prepared(ctx: &DispatchCtx,
params: ExecutePreparedParams,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
) -> Result<Outcome<ExecutionResult>, String> {
@@ -125,7 +126,7 @@ pub async fn execute_prepared(
}
/// Check the on-chain lifecycle state of a broadcast transaction.
-pub async fn tx_status(
+pub async fn tx_status(ctx: &DispatchCtx,
chain: WalletChain,
evm_network: Option<EvmNetwork>,
hash: &str,
@@ -153,7 +154,7 @@ pub async fn tx_status(
}
/// Fetch the receipt of a broadcast transaction.
-pub async fn tx_receipt(
+pub async fn tx_receipt(ctx: &DispatchCtx,
chain: WalletChain,
evm_network: Option<EvmNetwork>,
hash: &str,
@@ -181,7 +182,7 @@ pub async fn tx_receipt(
}
/// Look up the raw transaction payload by hash.
-pub async fn lookup_tx(
+pub async fn lookup_tx(ctx: &DispatchCtx,
chain: WalletChain,
evm_network: Option<EvmNetwork>,
hash: &str,
@@ -209,7 +210,7 @@ pub async fn lookup_tx(
}
/// Encode ERC-20 transfer calldata in the loaded wallet module.
-pub async fn encode_erc20_transfer(to_address: &str, amount_raw: &str) -> Result<String, String> {
+pub async fn encode_erc20_transfer(ctx: &DispatchCtx, to_address: &str, amount_raw: &str) -> Result<String, String> {
let config = ctx.load_config().await?;
wallet_module::encode_erc20_transfer(&config, to_address, amount_raw)
.await
diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs
index 97b66f6e63..cf06c00370 100644
--- a/crates/openhuman-core/src/web3/wallet/ops.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops.rs
@@ -7,6 +7,7 @@
mod state;
mod types;
+use crate::core::runtime::DispatchCtx;
use types::StoredWalletState;
pub(crate) use types::WalletSecretMaterial;
pub use types::{
@@ -37,7 +38,7 @@ fn supported_word_counts() -> String {
}
/// Generate recovery material through the attested wallet module.
-pub async fn generate_recovery_phrase(
+pub async fn generate_recovery_phrase(ctx: &DispatchCtx,
word_count: u8,
) -> Result<Outcome<GeneratedRecoveryPhrase>, String> {
tinywallet_bus::validate_mnemonic_word_count(word_count).map_err(|error| error.to_string())?;
@@ -59,7 +60,7 @@ pub async fn generate_recovery_phrase(
/// The returned BIP-39 seed is used only for OpenHuman's existing generic
/// storage-key KDF; mnemonic parsing and all chain derivation remain in the
/// confidential module operation.
-pub async fn derive_recovery_material(
+pub async fn derive_recovery_material(ctx: &DispatchCtx,
mnemonic: String,
) -> Result<Outcome<WalletRecoveryMaterial>, String> {
let word_count = mnemonic.split_whitespace().count();
@@ -114,7 +115,7 @@ pub async fn derive_recovery_material(
}
/// Check whether a phrase is valid BIP-39 input without deriving account data.
-pub async fn validate_recovery_phrase(
+pub async fn validate_recovery_phrase(ctx: &DispatchCtx,
mnemonic: String,
) -> Result<Outcome<RecoveryPhraseValidation>, String> {
use crate::modules::wallet::WalletCallError;
@@ -200,7 +201,7 @@ fn validate_setup(params: &WalletSetupParams) -> Result<Vec<WalletAccount>, Stri
Ok(normalized)
}
-pub async fn status() -> Result<Outcome<WalletStatus>, String> {
+pub async fn status(ctx: &DispatchCtx, ) -> Result<Outcome<WalletStatus>, String> {
let config = ctx.load_config().await?;
let _guard = WALLET_STATE_FILE_LOCK.lock();
let status = to_status(&config, load_stored_wallet_state_unlocked(&config)?);
@@ -218,7 +219,7 @@ pub async fn status() -> Result<Outcome<WalletStatus>, String> {
))
}
-pub async fn setup(params: WalletSetupParams) -> Result<Outcome<WalletStatus>, String> {
+pub async fn setup(ctx: &DispatchCtx, params: WalletSetupParams) -> Result<Outcome<WalletStatus>, String> {
let config = ctx.load_config().await?;
let accounts = validate_setup(&params)?;
let encrypted_mnemonic = params
@@ -270,7 +271,7 @@ pub async fn setup(params: WalletSetupParams) -> Result<Outcome<WalletStatus>, S
/// This is a read-only operation — it never writes to disk or the keychain.
/// The plaintext phrase is returned only in the RPC response and must be kept
/// in transient React state on the frontend; it must never be logged or persisted.
-pub async fn reveal_recovery_phrase() -> Result<Outcome<RevealRecoveryPhraseResult>, String> {
+pub async fn reveal_recovery_phrase(ctx: &DispatchCtx, ) -> Result<Outcome<RevealRecoveryPhraseResult>, String> {
debug!("{LOG_PREFIX} reveal_recovery_phrase ENTRY");
let config = ctx.load_config().await.map_err(|e| {
@@ -348,7 +349,7 @@ pub async fn reveal_recovery_phrase() -> Result<Outcome<RevealRecoveryPhraseResu
))
}
-pub(crate) async fn secret_material(chain: WalletChain) -> Result<WalletSecretMaterial, String> {
+pub(crate) async fn secret_material(ctx: &DispatchCtx, chain: WalletChain) -> Result<WalletSecretMaterial, String> {
debug!(
"{LOG_PREFIX} secret_material loading config chain={}",
chain.as_str()