Skip to content

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

refactor(runtime): thread DispatchCtx through config and prompt loading

Steven Enamakelc4eda26fee37
diff --git a/crates/openhuman-core/src/agent/artifacts/schemas.rs b/crates/openhuman-core/src/agent/artifacts/schemas.rs
index 4b38c11c0c..2bcde8473a 100644
--- a/crates/openhuman-core/src/agent/artifacts/schemas.rs
+++ b/crates/openhuman-core/src/agent/artifacts/schemas.rs
@@ -253,9 +253,9 @@ fn artifact_id_input(comment: &'static str) -> FieldSchema {
}
}
-fn handle_list_artifacts(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_artifacts(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let offset = read_optional_u64(&params, "offset")?
.map(|raw| {
usize::try_from(raw).map_err(|_| "offset is too large for usize".to_string())
@@ -277,17 +277,17 @@ fn handle_list_artifacts(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
})
}
-fn handle_get_artifact(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_artifact(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let artifact_id = read_required::<String>(&params, "artifact_id")?;
to_json(crate::agent::artifacts::ops::ai_get_artifact(&config, artifact_id.trim()).await?)
})
}
-fn handle_delete_artifact(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_delete_artifact(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let artifact_id = read_required::<String>(&params, "artifact_id")?;
to_json(
crate::agent::artifacts::ops::ai_delete_artifact(&config, artifact_id.trim()).await?,
@@ -295,9 +295,9 @@ fn handle_delete_artifact(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_regenerate(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_regenerate(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let artifact_id = read_required::<String>(&params, "artifact_id")?;
let thread_id = read_required::<String>(&params, "thread_id")?;
let client_id = read_required::<String>(&params, "client_id")?;
diff --git a/crates/openhuman-core/src/agent/attachments/mod.rs b/crates/openhuman-core/src/agent/attachments/mod.rs
index 3786cf3b51..565d25fc93 100644
--- a/crates/openhuman-core/src/agent/attachments/mod.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod.rs
@@ -1,6 +1,7 @@
//! Durable user uploads in the acting workspace. Provider resolution never
//! changes the original file or writes inline media into session records.
+use crate::core::runtime::DispatchCtx;
use std::path::{Component, Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -426,7 +427,7 @@ pub(crate) async fn stage(
/// Explicit image forwarding for delegation. A filename mentioned in prose
/// grants no read; only the typed argument or a legacy image marker does.
-pub(crate) async fn delegation_prompt(
+pub(crate) async fn delegation_prompt(ctx: &DispatchCtx,
prompt: &str,
args: &serde_json::Value,
workspace: Option<&tinytools::WorkspaceDescriptor>,
@@ -454,7 +455,7 @@ pub(crate) async fn delegation_prompt(
) {
anyhow::bail!("local attachment reads are disabled for external channel input");
}
- let mut config = crate::config::rpc::load_config_with_timeout()
+ let mut config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(anyhow::Error::msg)?;
if let Some(workspace) = workspace {
@@ -468,7 +469,7 @@ pub(crate) async fn delegation_prompt(
}
/// Validate a vision task's explicit references before constructing inference.
-pub(crate) async fn has_resolvable_image(
+pub(crate) async fn has_resolvable_image(ctx: &DispatchCtx,
prompt: &str,
workspace: Option<&tinytools::WorkspaceDescriptor>,
origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
@@ -487,7 +488,7 @@ pub(crate) async fn has_resolvable_image(
if paths.is_empty() {
return Ok(false);
}
- let mut config = crate::config::rpc::load_config_with_timeout()
+ let mut config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(anyhow::Error::msg)?;
if matches!(
diff --git a/crates/openhuman-core/src/agent/context_breakdown.rs b/crates/openhuman-core/src/agent/context_breakdown.rs
index cf2fb78069..9782dee20f 100644
--- a/crates/openhuman-core/src/agent/context_breakdown.rs
+++ b/crates/openhuman-core/src/agent/context_breakdown.rs
@@ -11,6 +11,7 @@
//! model route, or tool config invalidates the cache instead of serving a
//! stale breakdown.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use std::sync::Mutex;
@@ -90,7 +91,7 @@ static REPORT_CACHE: Lazy<Mutex<HashMap<String, (u64, PromptSizeReport)>>> =
/// Builds (or reuses a cached) [`PromptSizeReport`] for `agent_id` under the
/// given config, invalidating the cache entry when the config fingerprint
/// changed since the last build.
-async fn cached_report(agent_id: &str, config: &Config) -> Result<PromptSizeReport, String> {
+async fn cached_report(ctx: &DispatchCtx, agent_id: &str, config: &Config) -> Result<PromptSizeReport, String> {
let fingerprint = config_fingerprint(config);
if let Some((cached_fingerprint, report)) = REPORT_CACHE
.lock()
@@ -115,7 +116,7 @@ async fn cached_report(agent_id: &str, config: &Config) -> Result<PromptSizeRepo
config_path_override: Some(config.config_path.clone()),
model_override: None,
};
- let report = PromptSizeReport::build(options)
+ let report = PromptSizeReport::build(&ctx, options)
.await
.map_err(|e| format!("failed to build prompt-size report for {agent_id}: {e}"))?;
@@ -178,10 +179,10 @@ fn tools_section(tools: &[ToolSize]) -> ContextSection {
/// Builds the `agent.context_breakdown` response: the agent's rendered
/// prompt sections, one rolled-up `tools` section, and (when `thread_id` is
/// given) a `history` section.
-pub async fn context_breakdown(
+pub async fn context_breakdown(ctx: &DispatchCtx,
params: ContextBreakdownParams,
) -> Result<Outcome<ContextBreakdownResponse>, String> {
- let config = crate::config::rpc::load_config_with_timeout().await?;
+ let config = crate::config::rpc::load_config_with_timeout(&ctx).await?;
let agent_id = params
.agent_id
.as_deref()
@@ -190,7 +191,7 @@ pub async fn context_breakdown(
.unwrap_or(DEFAULT_AGENT_ID)
.to_string();
- let report = cached_report(&agent_id, &config).await?;
+ let report = cached_report(&ctx, &agent_id, &config).await?;
let mut sections: Vec<ContextSection> =
report.sections.iter().map(section_from_prompt).collect();
diff --git a/crates/openhuman-core/src/agent/debug/mod.rs b/crates/openhuman-core/src/agent/debug/mod.rs
index d75c42c476..31dfec2e22 100644
--- a/crates/openhuman-core/src/agent/debug/mod.rs
+++ b/crates/openhuman-core/src/agent/debug/mod.rs
@@ -12,6 +12,7 @@
//! * [`dump_agent_prompt`] — dump a single agent by id.
//! * [`dump_all_agent_prompts`] — dump every registered agent in one call.
+use crate::core::runtime::DispatchCtx;
use std::path::PathBuf;
use anyhow::{anyhow, Context, Result};
@@ -87,7 +88,7 @@ pub struct DumpedPrompt {
/// Render and return the system prompt for a single agent via the
/// real [`OpenHumanSessionHost::from_config_for_agent`] construction path.
-pub async fn dump_agent_prompt(options: DumpPromptOptions) -> Result<DumpedPrompt> {
+pub async fn dump_agent_prompt(ctx: &DispatchCtx, options: DumpPromptOptions) -> Result<DumpedPrompt> {
let config = load_dump_config(
options.workspace_dir_override.clone(),
options.config_path_override.clone(),
@@ -101,14 +102,14 @@ pub async fn dump_agent_prompt(options: DumpPromptOptions) -> Result<DumpedPromp
AgentDefinitionRegistry::init_global(&config.workspace_dir)
.context("initialising AgentDefinitionRegistry for prompt dump")?;
- render_via_session(&config, &options.agent_id).await
+ render_via_session(&ctx, &config, &options.agent_id).await
}
/// Dump every registered agent's system prompt in one shot.
///
/// The synthetic `fork` archetype is skipped (byte-stable replay, no
/// standalone prompt). Order follows [`AgentDefinitionRegistry::list`].
-pub async fn dump_all_agent_prompts(
+pub async fn dump_all_agent_prompts(ctx: &DispatchCtx,
workspace_dir_override: Option<PathBuf>,
config_path_override: Option<PathBuf>,
model_override: Option<String>,
@@ -131,7 +132,7 @@ pub async fn dump_all_agent_prompts(
let mut results = Vec::with_capacity(ids.len());
for id in ids {
- let dumped = render_via_session(&config, &id)
+ let dumped = render_via_session(&ctx, &config, &id)
.await
.with_context(|| format!("rendering prompt for agent `{id}`"))?;
results.push(dumped);
@@ -174,7 +175,7 @@ async fn load_dump_config(
/// Build a real [`Agent`] via `from_config_for_agent`, populate live
/// connected integrations, and render the turn-1 system prompt.
-async fn render_via_session(config: &Config, agent_id: &str) -> Result<DumpedPrompt> {
+async fn render_via_session(ctx: &DispatchCtx, config: &Config, agent_id: &str) -> Result<DumpedPrompt> {
let mut agent = OpenHumanSessionHost::from_config_for_agent(config, agent_id)
.with_context(|| format!("building session agent for `{agent_id}`"))?;
@@ -188,7 +189,7 @@ async fn render_via_session(config: &Config, agent_id: &str) -> Result<DumpedPro
agent.refresh_delegation_tools();
let text = agent
- .build_system_prompt()
+ .build_system_prompt(&ctx)
.with_context(|| format!("rendering system prompt for `{agent_id}`"))?;
Ok(session_dump(&agent, agent_id, text))
diff --git a/crates/openhuman-core/src/agent/debug/prompt_size.rs b/crates/openhuman-core/src/agent/debug/prompt_size.rs
index 7637257f37..536eb82aa6 100644
--- a/crates/openhuman-core/src/agent/debug/prompt_size.rs
+++ b/crates/openhuman-core/src/agent/debug/prompt_size.rs
@@ -28,6 +28,7 @@
//! [`EST_BYTES_PER_TOKEN`] into a claim of accuracy — it is a divisor, not a
//! tokenizer.
+use crate::core::runtime::DispatchCtx;
use anyhow::Result;
use super::{dump_agent_prompt, DumpPromptOptions, DumpedPrompt};
@@ -86,8 +87,8 @@ pub struct PromptSizeReport {
impl PromptSizeReport {
/// Build the report for one agent by rendering its real turn-1 prompt.
- pub async fn build(options: DumpPromptOptions) -> Result<Self> {
- let dumped = dump_agent_prompt(options).await?;
+ pub async fn build(ctx: &DispatchCtx, options: DumpPromptOptions) -> Result<Self> {
+ let dumped = dump_agent_prompt(&ctx, options).await?;
Ok(Self::from_dump(&dumped))
}
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index b68220c0d1..82f7c19c79 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -26,6 +26,7 @@
//! context-window summarization step (`tinyagents::summarize`) ahead of the
//! deterministic front-trim.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashSet;
use std::sync::Arc;
@@ -44,7 +45,7 @@ use tinytools::Tool;
/// `on_progress` is `Some`, the run streams and mirrors progress onto
/// `AgentProgress`; pass `None` for a fire-and-forget final-text turn.
#[allow(clippy::too_many_arguments)]
-pub(crate) async fn run_channel_turn_via_graph(
+pub(crate) async fn run_channel_turn_via_graph(ctx: &DispatchCtx,
source: TurnModelSource,
history: &mut Vec<TranscriptMessage>,
tools_registry: Arc<Vec<Box<dyn Tool>>>,
@@ -102,7 +103,7 @@ pub(crate) async fn run_channel_turn_via_graph(
anyhow::bail!("attachments are disabled for this channel input");
}
if attachment_config.is_none() {
- let mut config = crate::config::rpc::load_config_with_timeout()
+ let mut config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(anyhow::Error::msg)?;
config.multimodal = multimodal.clone();
diff --git a/crates/openhuman-core/src/agent/library/ops.rs b/crates/openhuman-core/src/agent/library/ops.rs
index d0fec20e79..96c7ddc343 100644
--- a/crates/openhuman-core/src/agent/library/ops.rs
+++ b/crates/openhuman-core/src/agent/library/ops.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use crate::agent::harness::host_definition::{AgentDefinition, AgentDefinitionRegistry};
use crate::config::rpc as config_rpc;
use tinyagents_definition::{
@@ -6,10 +7,10 @@ use tinyagents_definition::{
use super::types::{AgentDefinitionDisplay, AgentDefinitionModel, AgentDefinitionSource};
-pub async fn list_definition_metadata() -> Result<Vec<AgentDefinitionDisplay>, String> {
+pub async fn list_definition_metadata(ctx: &DispatchCtx, ) -> Result<Vec<AgentDefinitionDisplay>, String> {
tracing::debug!("[rpc][agent_library][entry] list_definitions");
if AgentDefinitionRegistry::global().is_none() {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
AgentDefinitionRegistry::init_global(&config.workspace_dir)
.map_err(|e| format!("failed to initialise AgentDefinitionRegistry: {e}"))?;
}
diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rs
index 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/agent_teams/schemas.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
index 6c71004f42..1af509c9e2 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
@@ -253,11 +253,11 @@ fn schema_for(function: &str) -> ControllerSchema {
}
}
-fn handle_create(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_create(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] create.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] create.config_failed err={err}");
})?;
let lead = require_str(&params, "leadAgentId")?;
@@ -278,11 +278,11 @@ fn handle_create(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list.config_failed err={err}");
})?;
let request: AgentTeamListRequest = if params.is_empty() {
@@ -304,11 +304,11 @@ fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] get.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] get.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -320,11 +320,11 @@ fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
})
}
-fn handle_assign_task(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_assign_task(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] assign_task.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] assign_task.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -347,11 +347,11 @@ fn handle_assign_task(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll
})
}
-fn handle_claim_task(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_claim_task(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] claim_task.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] claim_task.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -366,11 +366,11 @@ fn handle_claim_task(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_message_member(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_message_member(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] message_member.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] message_member.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -394,11 +394,11 @@ fn handle_message_member(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
})
}
-fn handle_list_messages(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_messages(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list_messages.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list_messages.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -414,11 +414,11 @@ fn handle_list_messages(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_complete_task(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_complete_task(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] complete_task.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] complete_task.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -438,11 +438,11 @@ fn handle_complete_task(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_shutdown_member(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_shutdown_member(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] shutdown_member.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] shutdown_member.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -455,11 +455,11 @@ fn handle_shutdown_member(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_close(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_close(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] close.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] close.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
@@ -472,11 +472,11 @@ fn handle_close(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
})
}
-fn handle_start_member(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_start_member(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] start_member.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] start_member.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
diff --git a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
index c30db20372..52eb0a58be 100644
--- a/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/command_center/schemas.rs
@@ -86,11 +86,11 @@ fn schema_for(function: &str) -> ControllerSchema {
}
}
-fn handle_agent_work_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_agent_work_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.entry");
- let config = config_rpc::load_config_with_timeout()
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.inspect_err(|err| {
log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.config_failed err={err}");
@@ -112,11 +112,11 @@ fn handle_agent_work_list(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_agent_work_control(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_agent_work_control(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.entry");
- let config = config_rpc::load_config_with_timeout()
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.inspect_err(|err| {
log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.config_failed err={err}");
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
index c871e012bd..7133ec4a36 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use serde_json::json;
use serde_json::Value;
@@ -149,7 +150,7 @@ pub(crate) async fn execute_archetype_delegation(
/// Typed-harness counterpart that preserves a live parent for the blocking
/// archetype child.
-pub(crate) async fn execute_archetype_delegation_with_live_parent(
+pub(crate) async fn execute_archetype_delegation_with_live_parent(ctx: &DispatchCtx,
agent_id: &str,
tool_name: &str,
args: serde_json::Value,
@@ -176,6 +177,7 @@ pub(crate) async fn execute_archetype_delegation_with_live_parent(
}
let prompt = render_structured_handoff(&raw_prompt, &args);
let prompt = match crate::agent::attachments::delegation_prompt(
+ &ctx,
&prompt,
&args,
tool_context
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
index 20aee7b8e8..669241a928 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
@@ -55,6 +55,7 @@
//! [`ArchetypeDelegationTool`]: super::ArchetypeDelegationTool
//! [`ToolExposure::Hidden`]: tinytools::ToolExposure::Hidden
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use serde_json::{json, Value};
@@ -242,7 +243,7 @@ impl Tool for CollapsedDelegationTool {
run_context.thread_id = tool_context
.and_then(ToolRunContext::thread_id)
.map(ToOwned::to_owned);
- execute_collapsed_delegation(&self.targets, args, tool_context, run_context).await
+ execute_collapsed_delegation(&DispatchCtx::ambient(), &self.targets, args, tool_context, run_context).await
}
}
@@ -313,19 +314,19 @@ pub(crate) fn dispatch_targets_from_schema(schema: &Value) -> Result<Vec<Delegat
}
/// Execute a collapsed hand-off with an explicit child run carrier.
-pub(crate) async fn execute_collapsed_delegation(
+pub(crate) async fn execute_collapsed_delegation(ctx: &DispatchCtx,
targets: &[DelegateTarget],
args: Value,
tool_context: Option<&dyn ToolRunContext>,
run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> anyhow::Result<ToolResult> {
- execute_collapsed_delegation_with_live_parent(targets, args, tool_context, run_context, None)
+ execute_collapsed_delegation_with_live_parent(&ctx, targets, args, tool_context, run_context, None)
.await
}
/// Typed-harness counterpart that preserves the exact parent run for a
/// blocking child rather than recreating a synthetic root from host data.
-pub(crate) async fn execute_collapsed_delegation_with_live_parent(
+pub(crate) async fn execute_collapsed_delegation_with_live_parent(ctx: &DispatchCtx,
targets: &[DelegateTarget],
args: Value,
tool_context: Option<&dyn ToolRunContext>,
@@ -364,6 +365,7 @@ pub(crate) async fn execute_collapsed_delegation_with_live_parent(
}
let prompt = render_structured_handoff(&raw_prompt, &args);
let prompt = match crate::agent::attachments::delegation_prompt(
+ &ctx,
&prompt,
&args,
tool_context
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs
index 84848528ef..42fa57aec9 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;
@@ -165,7 +166,7 @@ impl Tool for DelegateGraphTool {
run_context.thread_id = tool_context
.and_then(ToolRunContext::thread_id)
.map(ToOwned::to_owned);
- self.execute_with_parent_context(args, tool_context, run_context)
+ self.execute_with_parent_context(&DispatchCtx::ambient(), args, tool_context, run_context)
.await
}
}
@@ -173,12 +174,12 @@ impl Tool for DelegateGraphTool {
impl DelegateGraphTool {
/// Execute the concrete durable graph with an explicit child carrier.
pub(crate) async fn execute_with_parent_context(
- &self,
+ &self, ctx: &DispatchCtx,
args: serde_json::Value,
tool_context: Option<&dyn ToolRunContext>,
run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> anyhow::Result<ToolResult> {
- self.execute_with_live_parent_context(args, tool_context, run_context, None)
+ self.execute_with_live_parent_context(&ctx, args, tool_context, run_context, None)
.await
}
@@ -186,7 +187,7 @@ impl DelegateGraphTool {
/// path. The graph's static stage callback then derives direct children
/// from it without dropping lineage.
pub(crate) async fn execute_with_live_parent_context(
- &self,
+ &self, ctx: &DispatchCtx,
args: serde_json::Value,
tool_context: Option<&dyn ToolRunContext>,
run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
@@ -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(&ctx).await {
Ok(cfg) => Arc::new(cfg),
Err(e) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
index cd9fd71d3a..c5942b6da4 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
@@ -1,5 +1,6 @@
//! Subagent dispatch logic shared by all agent delegation tools.
+use crate::core::runtime::DispatchCtx;
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
use crate::agent::progress::AgentProgress;
use crate::agent::subagent_host::{
@@ -154,7 +155,7 @@ pub(crate) enum DispatchMode {
/// Dispatch one inline child against the caller's actual TinyAgents parent
/// when the typed tool boundary has one. Standalone callers retain the
/// explicit-carrier fallback above because no live parent exists for them.
-pub(crate) async fn dispatch_subagent_with_live_parent(
+pub(crate) async fn dispatch_subagent_with_live_parent(ctx: &DispatchCtx,
agent_id: &str,
tool_name: &str,
prompt: &str,
@@ -251,6 +252,7 @@ pub(crate) async fn dispatch_subagent_with_live_parent(
if agent_id == "vision_agent" {
match crate::agent::attachments::has_resolvable_image(
+ &ctx,
prompt,
parent_workspace_descriptor.as_ref(),
run_context.origin.as_ref(),
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.rs
index 49ca90f001..15ce017c7e 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;
@@ -28,7 +29,7 @@ use tinyagents_orchestration::workflow::WorkflowDefinition;
/// per phase, persists it, then `tokio::spawn`s the engine loop. The returned
/// [`WorkflowRun`] is the freshly-created row (status `Running`); callers poll
/// `workflow_run_get` to observe progress.
-pub async fn start_workflow_run(
+pub async fn start_workflow_run(ctx: &DispatchCtx,
config: &Config,
definition_id: &str,
input: Value,
@@ -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(&ctx).await {
Ok(task_config) => {
crate::agent::turn_origin::with_inherited_origin(
inherited_origin,
@@ -165,7 +166,7 @@ pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<Workf
/// phase whose dependencies are satisfied. Returns the run row (now `Running`),
/// or an error if the run is unknown / already terminal-complete / its
/// definition no longer exists.
-pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRun> {
+pub async fn resume_workflow_run(ctx: &DispatchCtx, config: &Config, id: &str) -> Result<WorkflowRun> {
log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.entry run={id}");
let run = get_workflow_run(config, id)?.ok_or_else(|| anyhow!("unknown workflow run: {id}"))?;
@@ -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(&ctx).await {
Ok(task_config) => {
crate::agent::turn_origin::with_inherited_origin(
inherited_origin,
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/schemas.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/schemas.rs
index e858c937d5..cd5e377de4 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/schemas.rs
@@ -143,11 +143,11 @@ fn handle_list_definitions(_ctx: DispatchCtx, _params: Map<String, Value>) -> Co
})
}
-fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.config_failed err={err}");
})?;
let request: WorkflowRunListRequest = if params.is_empty() {
@@ -171,11 +171,11 @@ fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.config_failed err={err}");
})?;
let id = params
@@ -193,11 +193,11 @@ fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
})
}
-fn handle_start(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_start(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.config_failed err={err}");
})?;
let definition_id = params
@@ -212,6 +212,7 @@ fn handle_start(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
.map(str::to_string);
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.definition={definition_id}");
let run = super::engine::start_workflow_run(
+ &ctx,
&config,
&definition_id,
input,
@@ -228,11 +229,11 @@ fn handle_start(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
})
}
-fn handle_stop(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_stop(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.config_failed err={err}");
})?;
let id = params
@@ -250,11 +251,11 @@ fn handle_stop(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn handle_resume(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_resume(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.config_failed err={err}");
})?;
let id = params
@@ -262,7 +263,7 @@ fn handle_resume(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
.and_then(|v| v.as_str())
.ok_or_else(|| "missing required param: id".to_string())?;
log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.id={id}");
- let run = super::engine::resume_workflow_run(&config, id).await.map_err(|e| {
+ let run = super::engine::resume_workflow_run(&ctx, &config, id).await.map_err(|e| {
let s = e.to_string();
log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.error id={id} err={s}");
s
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs b/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
index d4b386a719..aaa81be7d1 100644
--- a/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/worktree_schemas.rs
@@ -114,8 +114,8 @@ fn schema_for(function: &str) -> ControllerSchema {
/// Resolve the project repo root every worktree op anchors on — the agent's
/// `action_dir` from the loaded config.
-async fn repo_root(cid: &str) -> Result<PathBuf, String> {
- let config = config_rpc::load_config_with_timeout()
+async fn repo_root(ctx: &DispatchCtx, cid: &str) -> Result<PathBuf, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.inspect_err(|err| {
log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] config_failed err={err}");
@@ -145,40 +145,40 @@ fn require_managed_worktree_path(params: &Map<String, Value>) -> Result<PathBuf,
Ok(path)
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] list.entry");
- let root = repo_root(&cid).await?;
+ let root = repo_root(&ctx, &cid).await?;
list_view(&root, &cid)
})
}
-fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.entry");
- let root = repo_root(&cid).await?;
+ let root = repo_root(&ctx, &cid).await?;
let path = require_managed_worktree_path(&params)?;
status_view(&root, &path, &cid)
})
}
-fn handle_diff(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_diff(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.entry");
- let root = repo_root(&cid).await?;
+ let root = repo_root(&ctx, &cid).await?;
let path = require_managed_worktree_path(&params)?;
diff_view(&root, &path, &cid)
})
}
-fn handle_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.entry");
- let root = repo_root(&cid).await?;
+ let root = repo_root(&ctx, &cid).await?;
let path = require_managed_worktree_path(&params)?;
let force = params
.get("force")
diff --git a/crates/openhuman-core/src/agent/progress_tracing/export.rs b/crates/openhuman-core/src/agent/progress_tracing/export.rs
index afa79bc38c..db75885024 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/export.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/export.rs
@@ -1,6 +1,7 @@
//! Handing finished spans to their sink(s): the local NDJSON/log exporter and
//! the remote Langfuse usage-data push.
+use crate::core::runtime::DispatchCtx;
use crate::config::schema::AgentTracingConfig;
use crate::config::Config;
@@ -132,7 +133,7 @@ pub(crate) async fn export_run_trace_from_journal(
/// Export one completed child turn as a separate trace in its conversation.
/// The backend stamps the authenticated user onto the trace, while the child
/// run's original parent/root ids remain in trace metadata for navigation.
-pub(crate) async fn export_subagent_journal_trace(
+pub(crate) async fn export_subagent_journal_trace(ctx: &DispatchCtx,
config: &Config,
journal_run_id: &str,
thread_id: Option<&str>,
@@ -151,7 +152,7 @@ pub(crate) async fn export_subagent_journal_trace(
);
return;
}
- let observations = match crate::agent::tinyagents::journal::read_run_events(journal_run_id, 0)
+ let observations = match crate::agent::tinyagents::journal::read_run_events(&ctx, journal_run_id, 0)
.await
{
Ok(observations) if !observations.is_empty() => observations,
diff --git a/crates/openhuman-core/src/agent/prompts/connected_identities.rs b/crates/openhuman-core/src/agent/prompts/connected_identities.rs
index 783f165c3f..8c5bbc02b7 100644
--- a/crates/openhuman-core/src/agent/prompts/connected_identities.rs
+++ b/crates/openhuman-core/src/agent/prompts/connected_identities.rs
@@ -4,6 +4,7 @@
//! export-focused while the runtime fetch logic lives in a small,
//! testable unit.
+use crate::core::runtime::DispatchCtx;
/// Render persisted provider identities (if available) as a compact
/// `## Connected Identities` section.
///
@@ -17,18 +18,18 @@
/// `block_in_place` + current-runtime-handle bridge. Best-effort: no runtime, a
/// single-threaded runtime, or a config-load/driver failure all render an
/// empty section rather than panicking or blocking a prompt on a memory read.
-pub fn render_connected_identities() -> String {
+pub fn render_connected_identities(ctx: &DispatchCtx, ) -> String {
let Ok(handle) = tokio::runtime::Handle::try_current() else {
return String::new();
};
if handle.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread {
return String::new();
}
- tokio::task::block_in_place(|| handle.block_on(render_section()))
+ tokio::task::block_in_place(|| handle.block_on(render_section(&ctx)))
}
-async fn render_section() -> String {
- let config = match crate::config::rpc::load_config_with_timeout().await {
+async fn render_section(ctx: &DispatchCtx, ) -> String {
+ let config = match crate::config::rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(error) => {
tracing::debug!(%error, "[prompts] render_connected_identities: config load failed");
diff --git a/crates/openhuman-core/src/agent/registry/ops.rs b/crates/openhuman-core/src/agent/registry/ops.rs
index f272efed3f..4666e963fa 100644
--- a/crates/openhuman-core/src/agent/registry/ops.rs
+++ b/crates/openhuman-core/src/agent/registry/ops.rs
@@ -1,5 +1,6 @@
//! Config-backed operations for the user-facing agent registry.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
@@ -12,23 +13,23 @@ use super::types::{AgentRegistryEntry, AgentRegistryPatch, AgentRegistrySource,
const ORCHESTRATOR_AGENT_ID: &str = "orchestrator";
-pub async fn list_agents(include_disabled: bool) -> Result<Vec<AgentRegistryEntry>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn list_agents(ctx: &DispatchCtx, include_disabled: bool) -> Result<Vec<AgentRegistryEntry>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
Ok(merge_entries(
&config.agent_registry.entries,
include_disabled,
))
}
-pub async fn get_agent(id: &str) -> Result<Option<AgentRegistryEntry>, String> {
+pub async fn get_agent(ctx: &DispatchCtx, id: &str) -> Result<Option<AgentRegistryEntry>, String> {
let id = id.trim();
- Ok(list_agents(true)
+ Ok(list_agents(&ctx, true)
.await?
.into_iter()
.find(|agent| agent.id == id))
}
-pub async fn upsert_custom_agent(
+pub async fn upsert_custom_agent(ctx: &DispatchCtx,
mut entry: AgentRegistryEntry,
) -> Result<AgentRegistryEntry, String> {
entry.source = AgentRegistrySource::Custom;
@@ -41,7 +42,7 @@ pub async fn upsert_custom_agent(
));
}
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
match config
.agent_registry
.entries
@@ -58,7 +59,7 @@ pub async fn upsert_custom_agent(
Ok(entry)
}
-pub async fn update_agent(
+pub async fn update_agent(ctx: &DispatchCtx,
id: &str,
patch: AgentRegistryPatch,
) -> Result<AgentRegistryEntry, String> {
@@ -68,7 +69,7 @@ pub async fn update_agent(
}
let defaults = default_agents();
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
let entry = match config
.agent_registry
.entries
@@ -102,8 +103,9 @@ pub async fn update_agent(
Ok(updated)
}
-pub async fn set_agent_enabled(id: &str, enabled: bool) -> Result<AgentRegistryEntry, String> {
+pub async fn set_agent_enabled(ctx: &DispatchCtx, id: &str, enabled: bool) -> Result<AgentRegistryEntry, String> {
update_agent(
+ &ctx,
id,
AgentRegistryPatch {
enabled: Some(enabled),
@@ -113,13 +115,13 @@ pub async fn set_agent_enabled(id: &str, enabled: bool) -> Result<AgentRegistryE
.await
}
-pub async fn remove_agent(id: &str) -> Result<bool, String> {
+pub async fn remove_agent(ctx: &DispatchCtx, id: &str) -> Result<bool, String> {
let id = id.trim();
if id.is_empty() {
return Err("id is required".to_string());
}
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
let before = config.agent_registry.entries.len();
config.agent_registry.entries.retain(|agent| agent.id != id);
let removed = config.agent_registry.entries.len() < before;
@@ -144,8 +146,8 @@ pub async fn remove_agent(id: &str) -> Result<bool, String> {
/// live in a separate set and are intentionally not included — the picker
/// surfaces the stable built-in surface only. Sorted + deduped by name for a
/// stable picker UI.
-pub async fn available_tools() -> Result<Vec<AgentToolInfo>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn available_tools(ctx: &DispatchCtx, ) -> Result<Vec<AgentToolInfo>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
AgentDefinitionRegistry::init_global(&config.workspace_dir)
.map_err(|e| format!("failed to initialise AgentDefinitionRegistry: {e}"))?;
let agent = OpenHumanSessionHost::from_config_for_agent(&config, ORCHESTRATOR_AGENT_ID)
diff --git a/crates/openhuman-core/src/agent/registry/rpc.rs b/crates/openhuman-core/src/agent/registry/rpc.rs
index 4e81a475ff..d76b69a193 100644
--- a/crates/openhuman-core/src/agent/registry/rpc.rs
+++ b/crates/openhuman-core/src/agent/registry/rpc.rs
@@ -1,5 +1,6 @@
//! RPC payloads and handlers for the agent registry domain.
+use crate::core::runtime::DispatchCtx;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -21,10 +22,10 @@ pub struct ListResponse {
pub agents: Vec<AgentRegistryEntry>,
}
-pub async fn list_rpc(req: ListRequest) -> Result<Outcome<ListResponse>, String> {
+pub async fn list_rpc(ctx: &DispatchCtx, req: ListRequest) -> Result<Outcome<ListResponse>, String> {
Ok(Outcome::new(
ListResponse {
- agents: ops::list_agents(req.include_disabled).await?,
+ agents: ops::list_agents(&ctx, req.include_disabled).await?,
},
vec![],
))
@@ -38,12 +39,12 @@ pub struct AvailableToolsResponse {
pub tools: Vec<AgentToolInfo>,
}
-pub async fn available_tools_rpc(
+pub async fn available_tools_rpc(ctx: &DispatchCtx,
_req: AvailableToolsRequest,
) -> Result<Outcome<AvailableToolsResponse>, String> {
Ok(Outcome::new(
AvailableToolsResponse {
- tools: ops::available_tools().await?,
+ tools: ops::available_tools(&ctx).await?,
},
vec![],
))
@@ -59,10 +60,10 @@ pub struct GetResponse {
pub agent: Option<AgentRegistryEntry>,
}
-pub async fn get_rpc(req: GetRequest) -> Result<Outcome<GetResponse>, String> {
+pub async fn get_rpc(ctx: &DispatchCtx, req: GetRequest) -> Result<Outcome<GetResponse>, String> {
Ok(Outcome::new(
GetResponse {
- agent: ops::get_agent(&req.id).await?,
+ agent: ops::get_agent(&ctx, &req.id).await?,
},
vec![],
))
@@ -116,10 +117,10 @@ impl CreateCustomRequest {
}
}
-pub async fn create_custom_rpc(req: CreateCustomRequest) -> Result<Outcome<AgentResponse>, String> {
+pub async fn create_custom_rpc(ctx: &DispatchCtx, req: CreateCustomRequest) -> Result<Outcome<AgentResponse>, String> {
Ok(Outcome::new(
AgentResponse {
- agent: ops::upsert_custom_agent(req.into_entry()).await?,
+ agent: ops::upsert_custom_agent(&ctx, req.into_entry()).await?,
},
vec![],
))
@@ -135,10 +136,10 @@ pub struct AgentResponse {
pub agent: AgentRegistryEntry,
}
-pub async fn upsert_custom_rpc(req: UpsertCustomRequest) -> Result<Outcome<AgentResponse>, String> {
+pub async fn upsert_custom_rpc(ctx: &DispatchCtx, req: UpsertCustomRequest) -> Result<Outcome<AgentResponse>, String> {
Ok(Outcome::new(
AgentResponse {
- agent: ops::upsert_custom_agent(req.agent).await?,
+ agent: ops::upsert_custom_agent(&ctx, req.agent).await?,
},
vec![],
))
@@ -151,10 +152,10 @@ pub struct UpdateRequest {
pub patch: AgentRegistryPatch,
}
-pub async fn update_rpc(req: UpdateRequest) -> Result<Outcome<AgentResponse>, String> {
+pub async fn update_rpc(ctx: &DispatchCtx, req: UpdateRequest) -> Result<Outcome<AgentResponse>, String> {
Ok(Outcome::new(
AgentResponse {
- agent: ops::update_agent(&req.id, req.patch).await?,
+ agent: ops::update_agent(&ctx, &req.id, req.patch).await?,
},
vec![],
))
@@ -166,10 +167,10 @@ pub struct SetEnabledRequest {
pub enabled: bool,
}
-pub async fn set_enabled_rpc(req: SetEnabledRequest) -> Result<Outcome<AgentResponse>, String> {
+pub async fn set_enabled_rpc(ctx: &DispatchCtx, req: SetEnabledRequest) -> Result<Outcome<AgentResponse>, String> {
Ok(Outcome::new(
AgentResponse {
- agent: ops::set_agent_enabled(&req.id, req.enabled).await?,
+ agent: ops::set_agent_enabled(&ctx, &req.id, req.enabled).await?,
},
vec![],
))
@@ -185,10 +186,10 @@ pub struct RemoveResponse {
pub removed: bool,
}
-pub async fn remove_rpc(req: RemoveRequest) -> Result<Outcome<RemoveResponse>, String> {
+pub async fn remove_rpc(ctx: &DispatchCtx, req: RemoveRequest) -> Result<Outcome<RemoveResponse>, String> {
Ok(Outcome::new(
RemoveResponse {
- removed: ops::remove_agent(&req.id).await?,
+ removed: ops::remove_agent(&ctx, &req.id).await?,
},
vec![],
))
diff --git a/crates/openhuman-core/src/agent/registry/schemas.rs b/crates/openhuman-core/src/agent/registry/schemas.rs
index 548f8bcd0a..5c502ff9b2 100644
--- a/crates/openhuman-core/src/agent/registry/schemas.rs
+++ b/crates/openhuman-core/src/agent/registry/schemas.rs
@@ -214,59 +214,59 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::ListRequest>(Value::Object(params))?;
- to_json(rpc::list_rpc(req).await?)
+ to_json(rpc::list_rpc(&ctx, req).await?)
})
}
-fn handle_available_tools(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_available_tools(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::AvailableToolsRequest>(Value::Object(params))?;
- to_json(rpc::available_tools_rpc(req).await?)
+ to_json(rpc::available_tools_rpc(&ctx, req).await?)
})
}
-fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::GetRequest>(Value::Object(params))?;
- to_json(rpc::get_rpc(req).await?)
+ to_json(rpc::get_rpc(&ctx, req).await?)
})
}
-fn handle_create_custom(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_create_custom(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::CreateCustomRequest>(Value::Object(params))?;
- to_json(rpc::create_custom_rpc(req).await?)
+ to_json(rpc::create_custom_rpc(&ctx, req).await?)
})
}
-fn handle_upsert_custom(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_upsert_custom(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::UpsertCustomRequest>(Value::Object(params))?;
- to_json(rpc::upsert_custom_rpc(req).await?)
+ to_json(rpc::upsert_custom_rpc(&ctx, req).await?)
})
}
-fn handle_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::UpdateRequest>(Value::Object(params))?;
- to_json(rpc::update_rpc(req).await?)
+ to_json(rpc::update_rpc(&ctx, req).await?)
})
}
-fn handle_set_enabled(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_set_enabled(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::SetEnabledRequest>(Value::Object(params))?;
- to_json(rpc::set_enabled_rpc(req).await?)
+ to_json(rpc::set_enabled_rpc(&ctx, req).await?)
})
}
-fn handle_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let req = parse_value::<rpc::RemoveRequest>(Value::Object(params))?;
- to_json(rpc::remove_rpc(req).await?)
+ to_json(rpc::remove_rpc(&ctx, req).await?)
})
}
diff --git a/crates/openhuman-core/src/agent/schemas.rs b/crates/openhuman-core/src/agent/schemas.rs
index caac889ec8..3223d17e24 100644
--- a/crates/openhuman-core/src/agent/schemas.rs
+++ b/crates/openhuman-core/src/agent/schemas.rs
@@ -260,10 +260,10 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_chat(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_chat(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<AgentChatParams>(params)?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::rpc::agent_chat(
&mut config,
@@ -283,10 +283,10 @@ fn handle_chat(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn handle_chat_simple(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_chat_simple(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<AgentChatParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::rpc::agent_chat_simple(
&config,
@@ -304,9 +304,9 @@ fn handle_server_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> Contr
Box::pin(async { to_json(config_rpc::agent_server_status()) })
}
-fn handle_list_definitions(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_definitions(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let defs = crate::agent::library::list_definition_metadata().await?;
+ let defs = crate::agent::library::list_definition_metadata(&ctx).await?;
Ok(serde_json::json!({ "definitions": defs }))
})
}
@@ -356,7 +356,7 @@ struct TriageEvaluateParams {
dry_run: Option<bool>,
}
-fn handle_triage_evaluate(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_triage_evaluate(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<TriageEvaluateParams>(params)?;
@@ -421,7 +421,7 @@ fn handle_triage_evaluate(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
"[rpc][agent] running triage pipeline"
);
- let outcome = crate::agent::triage::run_triage(&envelope)
+ let outcome = crate::agent::triage::run_triage(&ctx, &envelope)
.await
.map_err(|e| format!("triage evaluation failed: {e}"))?;
@@ -577,7 +577,7 @@ fn local_catalog_models_from_config(
.collect()
}
-fn handle_registry_snapshot(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_registry_snapshot(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
use tinyagents_registry::{ComponentKind, ComponentMetadata, RegistrySnapshot};
@@ -588,7 +588,7 @@ fn handle_registry_snapshot(_ctx: DispatchCtx, _params: Map<String, Value>) -> C
// any entry whose provider is a local runtime (ollama, lmstudio, mlx, …)
// is overlaid as a free, runtime-profiled catalog entry so local models
// appear in the one projection alongside priced vendor rows.
- let local_models = match config_rpc::load_config_with_timeout().await {
+ let local_models = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => local_catalog_models_from_config(&config),
Err(err) => {
tracing::debug!(
@@ -687,11 +687,11 @@ fn handle_registry_snapshot(_ctx: DispatchCtx, _params: Map<String, Value>) -> C
})
}
-fn handle_context_breakdown(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_context_breakdown(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p =
deserialize_params::<crate::agent::context_breakdown::ContextBreakdownParams>(params)?;
- to_json(crate::agent::context_breakdown::context_breakdown(p).await?)
+ to_json(crate::agent::context_breakdown::context_breakdown(&ctx, p).await?)
})
}
diff --git a/crates/openhuman-core/src/agent/session_db/schemas.rs b/crates/openhuman-core/src/agent/session_db/schemas.rs
index 5531444bbc..332cf355c3 100644
--- a/crates/openhuman-core/src/agent/session_db/schemas.rs
+++ b/crates/openhuman-core/src/agent/session_db/schemas.rs
@@ -95,11 +95,11 @@ fn new_correlation_id() -> String {
uuid::Uuid::new_v4().simple().to_string()[..8].to_string()
}
-fn handle_run_ledger_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_ledger_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] list.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] list.config_failed err={err}");
})?;
let request: AgentRunListRequest = if params.is_empty() {
@@ -125,11 +125,11 @@ fn handle_run_ledger_list(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_run_ledger_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_ledger_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] get.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] get.config_failed err={err}");
})?;
let id = params
@@ -149,11 +149,11 @@ fn handle_run_ledger_get(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
})
}
-fn handle_run_ledger_events(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_ledger_events(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] events.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "run_ledger_rpc", "[run_ledger_rpc][{cid}] events.config_failed err={err}");
})?;
let request: RunEventListRequest =
diff --git a/crates/openhuman-core/src/agent/session_host/orphaned_head_resume_tests.rs b/crates/openhuman-core/src/agent/session_host/orphaned_head_resume_tests.rs
index 89a7d12293..3a8925c644 100644
--- a/crates/openhuman-core/src/agent/session_host/orphaned_head_resume_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/orphaned_head_resume_tests.rs
@@ -1,6 +1,7 @@
//! #6721: a thread whose persisted head opens on orphaned `tool` rows heals on
//! its next turn. Split from `runtime_adapter_tests.rs` for the layout gate.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use tinyinference_llm::message::Message;
@@ -18,14 +19,14 @@ fn a_resumed_orphaned_tool_head_is_repaired_before_the_request() {
.enable_all()
.build()
.expect("test runtime")
- .block_on(resumed_orphaned_tool_head_is_repaired_before_the_request());
+ .block_on(resumed_orphaned_tool_head_is_repaired_before_the_request(&DispatchCtx::process_default()));
})
.expect("test thread")
.join()
.expect("test thread panicked");
}
-async fn resumed_orphaned_tool_head_is_repaired_before_the_request() {
+async fn resumed_orphaned_tool_head_is_repaired_before_the_request(ctx: &DispatchCtx, ) {
const NUDGE: &str = "The last call failed validation. Fix the arguments and retry.";
// Run the production path: the app always installs the builtin agent
// definitions (core/jsonrpc.rs), which routes a root turn through the
@@ -117,7 +118,7 @@ async fn resumed_orphaned_tool_head_is_repaired_before_the_request() {
.collect::<Vec<_>>(),
["call_orphan_a", "call_orphan_b"],
);
- assert!(host.resume_bound_session().await.unwrap());
+ assert!(host.resume_bound_session(&ctx).await.unwrap());
let decoded = host
.runtime_session
.as_ref()
@@ -135,7 +136,7 @@ async fn resumed_orphaned_tool_head_is_repaired_before_the_request() {
let committed_history = host.runtime_session.as_ref().unwrap().history().to_vec();
let mut resumed_again = new_host();
resumed_again.set_thread_id(Some("thread-orphaned-head"));
- assert!(resumed_again.resume_bound_session().await.unwrap());
+ assert!(resumed_again.resume_bound_session(&ctx).await.unwrap());
assert_eq!(
resumed_again.runtime_session.as_ref().unwrap().history(),
committed_history.as_slice(),
diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs
index e43f2ca88b..efda981db9 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;
@@ -173,20 +174,20 @@ impl OpenHumanTurnPrelude {
rebuilt
}
- pub(super) async fn refresh_turn_boundary(&self, cold: bool) -> anyhow::Result<()> {
+ pub(super) async fn refresh_turn_boundary(&self, ctx: &DispatchCtx, cold: bool) -> anyhow::Result<()> {
// Hydrate on the first turn of *this session instance*, not only on a
// brand-new thread. A resumed thread is never `cold`, and a session
// rebuilt after a restart is seeded from an empty cache — gating the fetch on
// `cold` left it with zero integrations, no deferred Composio
// actions, and no `tool_search` bridge for the whole thread.
// `refresh_cold_integrations` is a no-op once hydrated.
- self.refresh_cold_integrations().await;
+ self.refresh_cold_integrations(&ctx).await;
#[cfg(feature = "mcp")]
self.refresh_connected_mcp_tools().await;
#[cfg(feature = "mcp")]
self.refresh_configured_mcp_tools().await;
if !cold {
- self.refresh_dynamic_announcements().await;
+ self.refresh_dynamic_announcements(&ctx).await;
}
// Integration changes are authority changes, not only display
// announcements. Refresh the delegation executable set and rebuild
@@ -350,7 +351,7 @@ impl OpenHumanTurnPrelude {
)
}
- pub(super) async fn refresh_cold_integrations(&self) {
+ pub(super) async fn refresh_cold_integrations(&self, ctx: &DispatchCtx) {
let should_fetch = !self
.mutable
.lock()
@@ -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(&ctx)
.await
.ok()
.map(Arc::new),
@@ -395,11 +396,11 @@ impl OpenHumanTurnPrelude {
apply_cold_hydration(&mut mutable, connected, authoritative, mcp_servers);
}
- pub(super) async fn refresh_dynamic_announcements(&self) {
+ pub(super) async fn refresh_dynamic_announcements(&self, ctx: &DispatchCtx) {
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(&ctx)
.await
.ok()
.map(Arc::new),
diff --git a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
index 300973d762..2d6f88ff40 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
@@ -2,6 +2,7 @@
//! that wrap [`OpenHumanSessionHost::turn`] with prompt-injection enforcement, telemetry
//! events, and error sanitisation.
+use crate::core::runtime::DispatchCtx;
use super::super::types::OpenHumanSessionHost;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
@@ -39,7 +40,7 @@ impl OpenHumanSessionHost {
/// context (chat surface, copilot flag, flow run). The context is handed to
/// this turn alone.
pub async fn run_single_with_approval(
- &mut self,
+ &mut self, ctx: &DispatchCtx,
message: &str,
origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
approval: crate::security::approval::ApprovalTurnContext,
@@ -99,7 +100,7 @@ impl OpenHumanSessionHost {
});
match self
- .turn_with_approval(message, origin.as_ref(), approval)
+ .turn_with_approval(&ctx, message, origin.as_ref(), approval)
.await
{
Ok(response) => {
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index 1376d07dc3..33fb31b722 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
@@ -599,7 +600,7 @@ async fn production_turn_path_wires_an_artifact_store_outside_the_project() {
.build()
.expect("session build");
- host.ensure_runtime_session()
+ host.ensure_runtime_session(&DispatchCtx::process_default())
.expect("ensure runtime session");
let state = host
@@ -641,7 +642,7 @@ async fn artifact_store_stays_in_the_workspace_without_a_descriptor() {
.build()
.expect("session build");
- host.ensure_runtime_session()
+ host.ensure_runtime_session(&DispatchCtx::process_default())
.expect("ensure runtime session");
let state = host
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index f98a81a27f..8b9aeed9dd 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -16,6 +16,7 @@ mod transcript;
mod turn;
pub(super) use turn::begin_turn_resume;
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use anyhow::Result;
@@ -221,7 +222,7 @@ impl OpenHumanTurnPrelude {
.unwrap_or_else(std::sync::PoisonError::into_inner) = surface;
}
- async fn prepare(&self, cold: bool) -> Result<TurnPreparation> {
+ async fn prepare(&self, ctx: &DispatchCtx, cold: bool) -> Result<TurnPreparation> {
let tools = {
let surface = self
.tool_surface
@@ -254,7 +255,7 @@ impl OpenHumanTurnPrelude {
.map_err(|error| anyhow::anyhow!(error.to_string()))?
};
let prefix = if cold {
- let tiered = self.build_system_prompt_tiered()?;
+ let tiered = self.build_system_prompt_tiered(&ctx)?;
Some(super::prefix_snapshot::tiered_prefix_snapshot(&tiered))
} else {
None
@@ -265,7 +266,7 @@ impl OpenHumanTurnPrelude {
})
}
- fn build_system_prompt_tiered(&self) -> Result<crate::agent::prompts::TieredPrompt> {
+ fn build_system_prompt_tiered(&self, ctx: &DispatchCtx) -> Result<crate::agent::prompts::TieredPrompt> {
use crate::agent::prompts::{PromptContext, PromptTool};
let surface = self
.tool_surface
@@ -332,7 +333,7 @@ impl OpenHumanTurnPrelude {
visible_tool_names: &visible_tool_names,
tool_call_format: self.tool_dispatcher.tool_call_format(),
connected_integrations: &mutable.connected_integrations,
- connected_identities_md: crate::agent::prompts::render_connected_identities(),
+ connected_identities_md: crate::agent::prompts::render_connected_identities(&ctx),
user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
personality_roster: vec![],
agents_md_global: agents_md.global,
@@ -528,8 +529,8 @@ impl OpenHumanTurnPrelude {
}
}
- async fn finalize_after_durable_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
- self.memory_post_turn(receipt);
+ async fn finalize_after_durable_commit(&self, ctx: &DispatchCtx, receipt: &CommitReceipt<OpenHumanRunContext>) {
+ self.memory_post_turn(&ctx, receipt);
}
}
@@ -577,7 +578,7 @@ impl OpenHumanSessionHost {
/// intentionally has no raw transcript rows because its source is a
/// role/content log rather than an authoritative transcript.
pub fn seed_resume_from_messages(
- &mut self,
+ &mut self, ctx: &DispatchCtx,
mut messages: Vec<(String, String)>,
current_user_message: &str,
) -> Result<()> {
@@ -592,7 +593,7 @@ impl OpenHumanSessionHost {
if messages.is_empty() {
return Ok(());
}
- self.ensure_runtime_session()?;
+ self.ensure_runtime_session(&ctx)?;
let history = messages
.into_iter()
.map(|(role, text)| match role.as_str() {
@@ -613,7 +614,7 @@ impl OpenHumanSessionHost {
self.turn_with_origin(user_message, None).await
}
- pub(in crate::agent::session_host) fn ensure_runtime_session(&mut self) -> Result<()> {
+ pub(in crate::agent::session_host) fn ensure_runtime_session(&mut self, ctx: &DispatchCtx) -> Result<()> {
if self.runtime_session.is_some() {
return Ok(());
}
@@ -837,7 +838,7 @@ impl OpenHumanSessionHost {
post_commit::await_pending(pending_post_commit).await;
let new_session = !view.resumed && view.history.is_empty();
prelude
- .refresh_turn_boundary(new_session)
+ .refresh_turn_boundary(&ctx, new_session)
.await
.map_err(|error| {
tinyagents_runtime::RuntimeError::Driver(error.to_string())
@@ -871,6 +872,7 @@ impl OpenHumanSessionHost {
// calls) would otherwise be inlined into this
// already-large hook future.
Box::pin(prelude.memory_pre_turn(
+ &ctx,
view.history,
view.committed_turns,
view.history.last().filter(|last| **last == request.input),
@@ -880,7 +882,7 @@ impl OpenHumanSessionHost {
options.run_context.data.memory_turn = memory_turn;
request.input = user_message_from_text(&enriched);
let mut preparation =
- prelude.prepare(new_session).await.map_err(|error| {
+ prelude.prepare(&ctx, new_session).await.map_err(|error| {
tinyagents_runtime::RuntimeError::Driver(error.to_string())
})?;
prelude.refresh_permanent_prefix(&mut preparation, view.prefix);
@@ -964,6 +966,7 @@ impl OpenHumanSessionHost {
let channel = channel.clone();
Box::pin(async move {
post_commit::finalize_committed_turn(
+ &ctx,
&state,
&post_turn_hooks,
post_commit::TurnIdentity {
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.rs
index 0f2aca7794..be6ec57a5d 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;
@@ -72,11 +73,11 @@ pub(super) fn in_prompt_window(
impl OpenHumanTurnPrelude {
/// The config memory runs under: the session's own, else the
/// workspace's on disk.
- async fn memory_config(&self) -> Option<Arc<crate::config::Config>> {
+ async fn memory_config(&self, ctx: &DispatchCtx) -> Option<Arc<crate::config::Config>> {
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(&ctx, &self.workspace_dir)
.await
.map(Arc::new)
.map_err(|error| {
@@ -93,7 +94,7 @@ impl OpenHumanTurnPrelude {
/// logged as observed from its sender
/// ([`crate::memory::lifecycle::sender::channel_actor`]).
pub(super) async fn memory_pre_turn(
- &self,
+ &self, ctx: &DispatchCtx,
history: &[Message],
committed_turns: usize,
current: Option<&Message>,
@@ -106,7 +107,7 @@ impl OpenHumanTurnPrelude {
.pending_user_text
.clone()?;
let thread_id = self.thread_id.clone()?;
- let config = self.memory_config().await?;
+ let config = self.memory_config(&ctx).await?;
// The identity the turn's run context carries: the host environment's
// (a team member's), narrowed to this agent.
let acting = self.host_env.memory_identity.clone().unwrap_or_default();
@@ -154,7 +155,7 @@ impl OpenHumanTurnPrelude {
/// Logs the committed reply (spawned; never delays the commit) and
/// publishes `ConversationTurnCommitted`.
- pub(super) fn memory_post_turn(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
+ pub(super) fn memory_post_turn(&self, ctx: &DispatchCtx, receipt: &CommitReceipt<OpenHumanRunContext>) {
let (user_text, pending) = {
let mut mutable = self
.mutable
@@ -199,7 +200,7 @@ impl OpenHumanTurnPrelude {
let prelude = self.clone();
let profile_context = pending.profile_context.clone();
let work = async move {
- let Some(config) = prelude.memory_config().await else {
+ let Some(config) = prelude.memory_config(&ctx).await else {
return;
};
hooks::post_turn(
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit.rs
index 919fb1c98e..2f94d39e3b 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit.rs
@@ -21,6 +21,7 @@
//!
//! Each step is timed under the `[session-runtime] post-commit` log prefix.
+use crate::core::runtime::DispatchCtx;
use std::future::Future;
use std::time::{Duration, Instant};
@@ -125,7 +126,7 @@ pub(super) struct TurnIdentity {
/// The session's `after_commit` hook body, in the order described in the
/// module docs: caller-visible state, then `TurnCompleted`, then the cheap
/// finalize steps, with goal accounting deferred to a fenced background task.
-pub(super) async fn finalize_committed_turn(
+pub(super) async fn finalize_committed_turn(ctx: &DispatchCtx,
state: &std::sync::Mutex<super::OpenHumanSessionState>,
post_turn_hooks: &[std::sync::Arc<dyn crate::agent::hooks::PostTurnHook>],
identity: TurnIdentity,
@@ -217,7 +218,7 @@ pub(super) async fn finalize_committed_turn(
.await;
if let Some(prelude) = prelude {
let started = std::time::Instant::now();
- prelude.finalize_after_durable_commit(&receipt).await;
+ prelude.finalize_after_durable_commit(&ctx, &receipt).await;
tracing::debug!(
elapsed_ms = elapsed_ms(started),
"[session-runtime] post-commit: finalize hooks done"
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/tool_rules_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/tool_rules_tests.rs
index a330b03b4a..19d70f1501 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/tool_rules_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/tool_rules_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
fn config_with_rules(tmp: &tempfile::TempDir) -> crate::config::Config {
@@ -47,7 +48,7 @@ fn a_session_composes_the_operator_and_definition_layers() {
/// A text-dialect session over the per-thread goal tools under `rules`,
/// returning its rendered prompt and declared tool names.
-async fn goal_session_prompt(rules: serde_json::Value) -> (String, Vec<String>) {
+async fn goal_session_prompt(ctx: &DispatchCtx, rules: serde_json::Value) -> (String, Vec<String>) {
let _ = crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global_builtins();
let action_dir = tempfile::tempdir().expect("tempdir");
let config = crate::config::Config {
@@ -64,7 +65,7 @@ async fn goal_session_prompt(rules: serde_json::Value) -> (String, Vec<String>)
.build()
.expect("session build");
host.set_thread_id(Some("thread-1"));
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&ctx).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -73,11 +74,11 @@ async fn goal_session_prompt(rules: serde_json::Value) -> (String, Vec<String>)
.clone()
.expect("prelude");
let prompt = prelude
- .build_system_prompt_tiered()
+ .build_system_prompt_tiered(&ctx)
.expect("system prompt")
.text;
let declared = prelude
- .prepare(true)
+ .prepare(&ctx, true)
.await
.expect("tool surface")
.tools
@@ -94,13 +95,13 @@ async fn goal_session_prompt(rules: serde_json::Value) -> (String, Vec<String>)
/// declared tool list the harness admits calls from.
#[tokio::test]
async fn a_rule_hidden_tool_leaves_the_rendered_prompt_but_stays_declared() {
- let (control, _) = goal_session_prompt(serde_json::json!({})).await;
+ let (control, _) = goal_session_prompt(&DispatchCtx::process_default(), serde_json::json!({})).await;
assert!(
control.contains("goal_complete"),
"the fixture surfaces goal_complete"
);
- let (prompt, declared) = goal_session_prompt(serde_json::json!({ "rules": [
+ let (prompt, declared) = goal_session_prompt(&DispatchCtx::process_default(), serde_json::json!({ "rules": [
{ "effect": "hide", "match": { "name": "goal_complete" } },
] }))
.await;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_juice_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_juice_tests.rs
index 14f880210f..b50acc7cf7 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_juice_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_juice_tests.rs
@@ -1,5 +1,6 @@
//! Frozen Juice declarations and executors survive configuration changes.
+use crate::core::runtime::DispatchCtx;
use super::*;
#[tokio::test]
@@ -58,7 +59,7 @@ async fn a_resumed_thread_keeps_recorded_juice_specs_and_executors_when_repl_is_
let mut host =
crate::agent::OpenHumanSessionHost::from_config_for_agent(&current_config, "summarizer")
.expect("summarizer session");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -77,7 +78,7 @@ async fn a_resumed_thread_keeps_recorded_juice_specs_and_executors_when_repl_is_
.len(),
recorded_specs.len()
);
- prelude.refresh_turn_boundary(false).await.expect("refresh");
+ prelude.refresh_turn_boundary(&DispatchCtx::process_default(), false).await.expect("refresh");
let surface_names = {
let surface = prelude.tool_surface.lock().expect("tool surface");
(
@@ -99,7 +100,7 @@ async fn a_resumed_thread_keeps_recorded_juice_specs_and_executors_when_repl_is_
surface.visible_tool_names.clone(),
)
};
- let prepared = prelude.prepare(false).await.expect("prepared surface");
+ let prepared = prelude.prepare(&DispatchCtx::process_default(), false).await.expect("prepared surface");
let prepared = prepared.tools.expect("prepared tool snapshot");
for recorded_spec in &recorded_specs {
@@ -179,7 +180,7 @@ async fn resumed_juice_snapshot_does_not_add_live_repl_declarations() {
let mut host = crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "summarizer")
.expect("summarizer session");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -188,9 +189,9 @@ async fn resumed_juice_snapshot_does_not_add_live_repl_declarations() {
.clone()
.expect("prelude");
prelude.adopt_recorded_tools(Some(&recorded));
- prelude.refresh_turn_boundary(false).await.expect("refresh");
+ prelude.refresh_turn_boundary(&DispatchCtx::process_default(), false).await.expect("refresh");
let prepared = prelude
- .prepare(false)
+ .prepare(&DispatchCtx::process_default(), false)
.await
.expect("prepared surface")
.tools
@@ -214,11 +215,11 @@ async fn resumed_juice_snapshot_does_not_add_live_repl_declarations() {
let empty = ToolSnapshot::new(Vec::new()).expect("empty recorded snapshot");
prelude.adopt_recorded_tools(Some(&empty));
prelude
- .refresh_turn_boundary(false)
+ .refresh_turn_boundary(&DispatchCtx::process_default(), false)
.await
.expect("refresh empty");
let prepared = prelude
- .prepare(false)
+ .prepare(&DispatchCtx::process_default(), false)
.await
.expect("prepared empty snapshot")
.tools
@@ -263,7 +264,7 @@ async fn juice_off_turn_loads_no_module_and_passes_tool_output_through() {
let mut host = crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "summarizer")
.expect("summarizer session");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let context_mw = host
.runtime_state
.lock()
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
index 30d5a5ee25..0a5aa8b6ca 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs
@@ -1,5 +1,6 @@
//! Tests for the turn prelude's tool surface across a resumed thread.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use tinyagents_runtime::ToolSnapshot;
@@ -117,7 +118,7 @@ fn clearing_progress_releases_warm_prelude_sender() {
let mut host =
crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.expect("orchestrator");
- host.ensure_runtime_session().expect("warm runtime");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("warm runtime");
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
host.set_on_progress(Some(tx));
@@ -205,7 +206,7 @@ fn connected_mcp_actions_enter_search_and_leave_on_disconnect() {
let mut host =
crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.expect("orchestrator");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -271,7 +272,7 @@ async fn resumed_mcp_snapshot_survives_a_cold_catalog_and_keeps_its_frozen_spec(
let mut host =
crate::agent::OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.expect("orchestrator");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -291,7 +292,7 @@ async fn resumed_mcp_snapshot_survives_a_cold_catalog_and_keeps_its_frozen_spec(
.expect("cold refresh");
let cold = prelude
- .prepare(false)
+ .prepare(&DispatchCtx::process_default(), false)
.await
.expect("prepared cold surface")
.tools
@@ -330,7 +331,7 @@ async fn resumed_mcp_snapshot_survives_a_cold_catalog_and_keeps_its_frozen_spec(
.refresh_delegation_tool_surface()
.expect("refresh from recovered catalog");
let recovered = prelude
- .prepare(false)
+ .prepare(&DispatchCtx::process_default(), false)
.await
.expect("prepared recovered surface")
.tools
@@ -378,7 +379,7 @@ async fn desktop_browser_setting_keeps_deferred_tools_in_fresh_and_resumed_surfa
.iter()
.any(|spec| spec.name == name));
}
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let prelude = host
.runtime_state
.lock()
@@ -386,14 +387,14 @@ async fn desktop_browser_setting_keeps_deferred_tools_in_fresh_and_resumed_surfa
.prelude
.clone()
.expect("prelude");
- let fresh = prelude.prepare(true).await.expect("fresh tool surface");
+ let fresh = prelude.prepare(&DispatchCtx::process_default(), true).await.expect("fresh tool surface");
let fresh = fresh.tools.expect("fresh tools");
for name in ["browser", "browser_open"] {
assert!(fresh.specs().iter().any(|spec| spec.name == name), "{name}");
}
prelude.adopt_recorded_tools(Some(&fresh));
prelude.refresh_delegation_tool_surface().unwrap();
- let resumed = prelude.prepare(false).await.expect("resumed tool surface");
+ let resumed = prelude.prepare(&DispatchCtx::process_default(), false).await.expect("resumed tool surface");
for name in ["browser", "browser_open"] {
assert!(
resumed
@@ -439,7 +440,7 @@ async fn a_resumed_orchestrator_keeps_the_integration_actions_it_was_sent() {
.agent_definition_name("orchestrator")
.build()
.expect("session build");
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&DispatchCtx::process_default()).expect("runtime session");
let state = host
.runtime_state
@@ -527,7 +528,7 @@ const SURFACED_GOAL_TOOL: &str = "goal_complete";
/// A text-dialect (XML) session over the real per-thread goal tools, optionally
/// bound to a chat thread, with its runtime session already initialised.
-fn text_dialect_host(
+fn text_dialect_host(ctx: &DispatchCtx,
thread_id: Option<&str>,
) -> (crate::agent::OpenHumanSessionHost, tempfile::TempDir) {
let _ = crate::agent::harness::host_definition::AgentDefinitionRegistry::init_global_builtins();
@@ -544,12 +545,12 @@ fn text_dialect_host(
.build()
.expect("session build");
host.set_thread_id(thread_id);
- host.ensure_runtime_session().expect("runtime session");
+ host.ensure_runtime_session(&ctx).expect("runtime session");
(host, action_dir)
}
/// Render the first-turn system prompt and declared tool list of `host`.
-async fn prompt_and_declared_tools(
+async fn prompt_and_declared_tools(ctx: &DispatchCtx,
host: &crate::agent::OpenHumanSessionHost,
) -> (String, ToolSnapshot) {
let prelude = host
@@ -559,9 +560,9 @@ async fn prompt_and_declared_tools(
.prelude
.clone()
.expect("prelude");
- let tiered = prelude.build_system_prompt_tiered().expect("system prompt");
+ let tiered = prelude.build_system_prompt_tiered(&ctx).expect("system prompt");
let snapshot = prelude
- .prepare(true)
+ .prepare(&ctx, true)
.await
.expect("tool surface")
.tools
@@ -584,15 +585,15 @@ fn assert_no_goal_tools(prompt: &str, snapshot: &ToolSnapshot) {
/// answer "unregistered tool" when called.
#[tokio::test]
async fn text_dialect_prompt_omits_thread_goal_tools_without_a_thread() {
- let (host, _dir) = text_dialect_host(None);
- let (prompt, snapshot) = prompt_and_declared_tools(&host).await;
+ let (host, _dir) = text_dialect_host(&DispatchCtx::process_default(), None);
+ let (prompt, snapshot) = prompt_and_declared_tools(&DispatchCtx::process_default(), &host).await;
assert_no_goal_tools(&prompt, &snapshot);
}
#[tokio::test]
async fn text_dialect_prompt_lists_thread_goal_tools_on_a_thread() {
- let (host, _dir) = text_dialect_host(Some("thread-goals"));
- let (prompt, snapshot) = prompt_and_declared_tools(&host).await;
+ let (host, _dir) = text_dialect_host(&DispatchCtx::process_default(), Some("thread-goals"));
+ let (prompt, snapshot) = prompt_and_declared_tools(&DispatchCtx::process_default(), &host).await;
assert!(
prompt.contains(SURFACED_GOAL_TOOL),
"{SURFACED_GOAL_TOOL} missing from the prompt"
@@ -611,20 +612,20 @@ async fn text_dialect_prompt_lists_thread_goal_tools_on_a_thread() {
/// surface (no goal tools) must not be contradicted by a later thread id.
#[tokio::test]
async fn a_thread_bound_after_session_init_is_refused_and_keeps_goal_tools_out() {
- let (mut host, _dir) = text_dialect_host(None);
+ let (mut host, _dir) = text_dialect_host(&DispatchCtx::process_default(), None);
host.set_thread_id(Some("late-thread"));
assert_eq!(host.thread_id(), None, "late thread id must be refused");
assert_eq!(host.session_id(), None, "no durable identity was minted");
- let (prompt, snapshot) = prompt_and_declared_tools(&host).await;
+ let (prompt, snapshot) = prompt_and_declared_tools(&DispatchCtx::process_default(), &host).await;
assert_no_goal_tools(&prompt, &snapshot);
}
#[tokio::test]
async fn rebinding_the_same_thread_after_session_init_is_a_no_op() {
- let (mut host, _dir) = text_dialect_host(Some("same-thread"));
+ let (mut host, _dir) = text_dialect_host(&DispatchCtx::process_default(), Some("same-thread"));
host.set_thread_id(Some("same-thread"));
assert_eq!(host.thread_id(), Some("same-thread"));
- let (prompt, _snapshot) = prompt_and_declared_tools(&host).await;
+ let (prompt, _snapshot) = prompt_and_declared_tools(&DispatchCtx::process_default(), &host).await;
assert!(prompt.contains(SURFACED_GOAL_TOOL));
}
@@ -661,7 +662,7 @@ async fn newly_connected_action_cannot_shadow_a_permanent_source() {
.agent_definition_name("orchestrator")
.build()
.unwrap();
- host.ensure_runtime_session().unwrap();
+ host.ensure_runtime_session(&DispatchCtx::process_default()).unwrap();
let prelude = host.runtime_state.lock().unwrap().prelude.clone().unwrap();
prelude.refresh_delegation_tool_surface().unwrap();
let before = prelude
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
index 0d02903552..90453ff770 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use anyhow::Result;
use tinyagents_runtime::{ResumeMode, SessionTurnRequest, TurnOptions};
@@ -22,12 +23,12 @@ impl OpenHumanSessionHost {
/// flow run it belongs to. It rides this turn's run context only, so it is
/// never left behind on the session for a later turn to inherit.
pub async fn turn_with_approval(
- &mut self,
+ &mut self, ctx: &DispatchCtx,
user_message: &str,
origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
approval: crate::security::approval::ApprovalTurnContext,
) -> Result<String> {
- self.ensure_runtime_session()?;
+ self.ensure_runtime_session(&ctx)?;
let staged = super::attachment_input::stage_turn(self, user_message, origin).await?;
let mut context = OpenHumanRunContext::new().with_host_env(&self.host_env);
context.untrusted_input_turn = self.untrusted_input;
diff --git a/crates/openhuman-core/src/agent/session_host/session_api.rs b/crates/openhuman-core/src/agent/session_host/session_api.rs
index 7ddb4b8257..cb7a527bd8 100644
--- a/crates/openhuman-core/src/agent/session_host/session_api.rs
+++ b/crates/openhuman-core/src/agent/session_host/session_api.rs
@@ -7,6 +7,7 @@
//! identity, [`super::runtime::accessors`]), reading one back, and listing the
//! generations a long conversation has accumulated.
+use crate::core::runtime::DispatchCtx;
use anyhow::Result;
use tinyagents_runtime::{ResumeMode, TurnOptions};
@@ -24,11 +25,11 @@ impl OpenHumanSessionHost {
/// Returns whether history was loaded. `false` means the session has no
/// durable identity bound (no thread), has nothing persisted yet, or has
/// already run a turn.
- pub async fn resume_bound_session(&mut self) -> Result<bool> {
+ pub async fn resume_bound_session(&mut self, ctx: &DispatchCtx) -> Result<bool> {
let Some(session) = self.session.clone() else {
return Ok(false);
};
- self.ensure_runtime_session()?;
+ self.ensure_runtime_session(&ctx)?;
let mut context = OpenHumanRunContext::new();
context.thread_id = self.thread_id.clone();
diff --git a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs
index 4c4c7edc03..c5686b92b2 100644
--- a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs
@@ -14,6 +14,7 @@
//! Regenerate only when deliberately adding a scenario:
//! `OH_REGEN_SESSION_COMPAT=1 cargo test -p openhuman --lib regenerate_session_compat -- --ignored`.
+use crate::core::runtime::DispatchCtx;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -277,12 +278,12 @@ fn normalize_clock(value: &mut Value) {
}
/// Everything the model observes after resuming a scenario.
-async fn snapshot(scenario: &'static Scenario) -> Value {
- snapshot_with(scenario, "").await
+async fn snapshot(ctx: &DispatchCtx, scenario: &'static Scenario) -> Value {
+ snapshot_with(&ctx, scenario, "").await
}
/// [`snapshot`] over the `variant` generation of the scenario's head fixture.
-pub(super) async fn snapshot_with(scenario: &'static Scenario, variant: &str) -> Value {
+pub(super) async fn snapshot_with(ctx: &DispatchCtx, scenario: &'static Scenario, variant: &str) -> Value {
let root = tempfile::tempdir().expect("tempdir");
let next = model(
vec![ModelResponse::assistant("next reply")],
@@ -298,7 +299,7 @@ pub(super) async fn snapshot_with(scenario: &'static Scenario, variant: &str) ->
place_fixture(root.path(), scenario, &stem, variant);
assert!(
- host.resume_bound_session().await.expect("resume"),
+ host.resume_bound_session(&ctx).await.expect("resume"),
"{}: fixture must resume",
scenario.name
);
@@ -341,7 +342,7 @@ pub(super) fn golden(name: &str) -> Value {
fn every_committed_transcript_resumes_to_the_recorded_model_view() {
for scenario in SCENARIOS {
run_async(async move {
- let got = snapshot(scenario).await;
+ let got = snapshot(&DispatchCtx::process_default(), scenario).await;
let want = golden(scenario.name);
assert_eq!(
got, want,
@@ -399,7 +400,7 @@ async fn capture_turns(name: &str, native: bool, responses: Vec<ModelResponse>,
copy_session(root.path(), &stem, &fixture(&format!("{name}.jsonl")));
}
-async fn capture_all() {
+async fn capture_all(ctx: &DispatchCtx, ) {
std::fs::create_dir_all(FIXTURE_DIR).expect("fixture dir");
let text = |s: &str| response(vec![ContentBlock::Text(s.into())], Vec::new());
@@ -561,7 +562,7 @@ async fn capture_all() {
}
for scenario in SCENARIOS {
- let snapshot = snapshot(scenario).await;
+ let snapshot = snapshot(&ctx, scenario).await;
std::fs::write(
fixture(&format!("{}.golden.json", scenario.name)),
serde_json::to_string_pretty(&snapshot).expect("golden") + "\n",
@@ -576,24 +577,24 @@ fn regenerate_session_compat() {
if std::env::var("OH_REGEN_SESSION_COMPAT").as_deref() != Ok("1") {
return;
}
- run_async(capture_all());
+ run_async(capture_all(&DispatchCtx::process_default()));
}
/// Archived declarations survive replay, but retired executors never return.
#[cfg(feature = "voice")]
#[test]
fn resumed_thread_with_retired_podcast_tool_remains_usable() {
- assert_retired_tool_replay(true);
+ assert_retired_tool_replay(&DispatchCtx::process_default(), true);
}
#[cfg(feature = "voice")]
#[test]
fn latest_agent_session_with_retired_podcast_tool_remains_usable() {
- assert_retired_tool_replay(false);
+ assert_retired_tool_replay(&DispatchCtx::process_default(), false);
}
#[cfg(feature = "voice")]
-fn assert_retired_tool_replay(identity_bound: bool) {
+fn assert_retired_tool_replay(ctx: &DispatchCtx, identity_bound: bool) {
run_async(async move {
const RETIRED: &str = "audio_generate_podcast";
struct ArchivedAudioTool;
@@ -671,12 +672,12 @@ fn assert_retired_tool_replay(identity_bound: bool) {
};
if identity_bound {
assert!(resumed
- .resume_bound_session()
+ .resume_bound_session(&ctx)
.await
.expect("resume archive"));
} else {
resumed
- .ensure_runtime_session()
+ .ensure_runtime_session(&ctx)
.expect("cold runtime session");
assert!(matches!(
resumed.turn_resume_mode(),
diff --git a/crates/openhuman-core/src/agent/session_host/transcript_resume_stable_tests.rs b/crates/openhuman-core/src/agent/session_host/transcript_resume_stable_tests.rs
index abe9f1d2e4..58cd2d53c8 100644
--- a/crates/openhuman-core/src/agent/session_host/transcript_resume_stable_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/transcript_resume_stable_tests.rs
@@ -2,6 +2,7 @@
//! committed fixture neither renames, rewrites nor re-adopts anything, so the
//! transcript stems and bytes on disk are exactly what the old binary left.
+use crate::core::runtime::DispatchCtx;
use std::collections::BTreeMap;
use std::path::Path;
@@ -44,7 +45,7 @@ fn resuming_a_committed_workspace_leaves_every_stem_and_byte_untouched() {
let before = raw_tree(root.path());
assert!(!before.is_empty(), "{}: fixture placed", scenario.name);
- assert!(host.resume_bound_session().await.expect("resume"));
+ assert!(host.resume_bound_session(&DispatchCtx::process_default()).await.expect("resume"));
assert_eq!(
before,
@@ -73,7 +74,7 @@ fn a_legacy_workspace_is_adopted_once_and_the_next_process_resumes_in_place() {
let stem = host.session_id().expect("bound session id");
place_fixture(root.path(), scenario, &stem, "");
legacy_only = raw_tree(root.path());
- assert!(host.resume_bound_session().await.expect("first resume"));
+ assert!(host.resume_bound_session(&DispatchCtx::process_default()).await.expect("first resume"));
after_first = raw_tree(root.path());
}
// Adoption writes the session's own file and modifies no legacy file.
@@ -92,7 +93,7 @@ fn a_legacy_workspace_is_adopted_once_and_the_next_process_resumes_in_place() {
// A fresh process over the same workspace resumes without adopting again.
let next = model(vec![ModelResponse::assistant("unused")], scenario.native);
let mut host = build_host(root.path(), next, scenario.native, &thread);
- assert!(host.resume_bound_session().await.expect("second resume"));
+ assert!(host.resume_bound_session(&DispatchCtx::process_default()).await.expect("second resume"));
assert_eq!(
after_first,
raw_tree(root.path()),
diff --git a/crates/openhuman-core/src/agent/session_host/turn/context.rs b/crates/openhuman-core/src/agent/session_host/turn/context.rs
index a3d8743dbb..170562029f 100644
--- a/crates/openhuman-core/src/agent/session_host/turn/context.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn/context.rs
@@ -1,5 +1,6 @@
//! History, context, and system prompt management.
+use crate::core::runtime::DispatchCtx;
use super::super::types::OpenHumanSessionHost;
use crate::agent::prompts::{PromptContext, PromptTool};
use tinytools::render_tool_policy_boundary;
@@ -9,7 +10,7 @@ use anyhow::Result;
impl OpenHumanSessionHost {
/// Builds the system prompt for the current turn, including tool
/// instructions.
- pub fn build_system_prompt(&self) -> Result<String> {
+ pub fn build_system_prompt(&self, ctx: &DispatchCtx) -> Result<String> {
// `visible_tool_specs` holds shared `Arc<ToolSpec>` leaves. Materialise
// the canonical dialect input for this prompt build.
let visible_specs_owned: Vec<tinytools::ToolSpec> = self
@@ -58,7 +59,7 @@ impl OpenHumanSessionHost {
visible_tool_names: &prompt_visible_tool_names,
tool_call_format: self.tool_dispatcher.tool_call_format(),
connected_integrations: &self.connected_integrations,
- connected_identities_md: crate::agent::prompts::render_connected_identities(),
+ connected_identities_md: crate::agent::prompts::render_connected_identities(&ctx),
user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
personality_roster: vec![], // TODO: build_personality_roster(&workspace_dir)
agents_md_global: agents_md.global,
diff --git a/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs b/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs
index 8cce0c01f6..0210569663 100644
--- a/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs
@@ -16,6 +16,7 @@
//! Regenerate the `.typed` files only when deliberately re-deriving them:
//! `OH_REGEN_SESSION_COMPAT=1 cargo test -p openhuman --lib regenerate_typed_session_compat -- --ignored`.
+use crate::core::runtime::DispatchCtx;
use serde_json::{json, Value};
use tinyagents_session::transcript::{append_tools_record, read_transcript, write_transcript};
use tinyinference_llm::message::ContentBlock;
@@ -111,7 +112,7 @@ fn message_lines(raw: &str) -> Vec<Value> {
fn typed_rewrites_of_the_corpus_resume_to_the_legacy_goldens() {
for name in TYPED_SCENARIOS {
run_async(async move {
- let got = snapshot_with(scenario(name), ".typed").await;
+ let got = snapshot_with(&DispatchCtx::process_default(), scenario(name), ".typed").await;
assert_eq!(
got,
golden(name),
@@ -177,7 +178,7 @@ fn an_old_session_continued_by_this_binary_reloads_identically() {
std::fs::copy(fixture("native_tools.jsonl"), &path).expect("place legacy file");
let legacy_bytes = std::fs::read(&path).expect("legacy bytes");
- assert!(first.resume_bound_session().await.expect("resume"));
+ assert!(first.resume_bound_session(&DispatchCtx::process_default()).await.expect("resume"));
first.turn("keep going").await.expect("continued turn");
let continued_history = serde_json::to_value(
first
@@ -213,7 +214,7 @@ fn an_old_session_continued_by_this_binary_reloads_identically() {
true,
&thread,
);
- assert!(host.resume_bound_session().await.expect("second resume"));
+ assert!(host.resume_bound_session(&DispatchCtx::process_default()).await.expect("second resume"));
host
};
let runtime = second.runtime_session.as_ref().expect("runtime session");
@@ -284,7 +285,7 @@ fn a_live_image_turn_persists_typed_image_parts_and_resumes_identically() {
.contains(png));
let mut second = build_live_image_host(root.path(), live_image_model("unused"), &thread);
- assert!(second.resume_bound_session().await.expect("resume"));
+ assert!(second.resume_bound_session(&DispatchCtx::process_default()).await.expect("resume"));
assert_eq!(
serde_json::to_value(
second
diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rs
index b9f5873748..ac9319e04a 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;
@@ -21,12 +22,12 @@ pub const TINYAGENTS_SESSION_KV_STORE: &str = "openhuman_sessions";
///
/// Best-effort: `None` when the config (hence workspace) cannot be resolved and
/// no store is installed.
-pub async fn session_kv_store() -> Option<Arc<dyn Store>> {
+pub async fn session_kv_store(ctx: &DispatchCtx, ) -> Option<Arc<dyn Store>> {
if let Some(stores) = crate::agent::session_store::current() {
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(&ctx).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/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 8d093aacd5..30bb93fadb 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -5,6 +5,7 @@
//! boundary explicit now: TinyAgents owns the lifecycle and OpenHuman owns the
//! plan, execution details, and translation back to its public DTOs.
+use crate::core::runtime::DispatchCtx;
use std::{
collections::HashMap,
fs::OpenOptions,
@@ -520,6 +521,7 @@ impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for O
options.run_context = execution.prepared.run_context.data.clone();
options.run_context.cancellation = execution.cancellation.clone();
match Box::pin(super::ops::run_subagent_direct(
+ &DispatchCtx::ambient(),
&definition,
&execution
.prepared
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
index 24c6d82ed9..54b493fe20 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;
@@ -112,7 +113,7 @@ use result_cap::apply_max_result_chars;
/// final assistant text. On failure the error is suitable for stringifying
/// into a `tool_result` block — including the two dispatch refusals, whose
/// messages tell the model to summarise rather than delegate again.
-pub(crate) async fn run_subagent_direct(
+pub(crate) async fn run_subagent_direct(ctx: &DispatchCtx,
definition: &AgentDefinition,
task_prompt: &str,
mut options: SubagentRunOptions,
@@ -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(&ctx))
.await
.map(std::sync::Arc::new)
.map_err(|e| e.to_string());
@@ -325,6 +326,7 @@ pub(crate) async fn run_subagent_direct(
let run_result = Box::pin(with_run_depth(RunDepth { depth: attempted_depth, max_depth }, async {
with_file_state_agent_id(task_id.clone(), async {
Box::pin(run_typed_mode(
+ &ctx,
definition,
task_prompt,
&options,
@@ -555,7 +557,7 @@ type LoadedConfig = Result<std::sync::Arc<crate::config::Config>, String>;
/// This mode builds a brand-new, minimized system prompt specifically for the
/// agent's archetype. It filters the parent's tools down to only those allowed
/// by the definition and per-spawn overrides.
-async fn run_typed_mode(
+async fn run_typed_mode(ctx: &DispatchCtx,
definition: &AgentDefinition,
task_prompt: &str,
options: &SubagentRunOptions,
@@ -772,7 +774,7 @@ async fn run_typed_mode(
visible_tool_names: &visible_tool_names,
tool_call_format: prompt_tool_call_format,
connected_integrations: &connected_integrations_for_prompt,
- connected_identities_md: crate::agent::prompts::render_connected_identities(),
+ connected_identities_md: crate::agent::prompts::render_connected_identities(&ctx),
user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
personality_roster: vec![],
agents_md_global: agents_md.global.clone(),
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs b/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
index 0e4ecd5667..50885d9ff0 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
@@ -60,6 +60,7 @@
//! host files into the prompt (and thence to the inference provider); this
//! adapter goes through it rather than reading the files itself.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashSet;
use std::sync::Arc;
use tinytools_agent::dialect::ToolCallFormat;
@@ -204,7 +205,7 @@ impl ContextComposer for OpenHumanContextComposer {
visible_tool_names: &visible_tool_names,
tool_call_format: self.tool_call_format,
connected_integrations: &self.connected_integrations,
- connected_identities_md: render_connected_identities(),
+ connected_identities_md: render_connected_identities(&DispatchCtx::ambient()),
user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
// TODO(phase4): the master agent's personality roster is built
// from the profiles domain (`crate::profiles`); the
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
index b8b815a0f1..fa16f06624 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};
@@ -386,7 +387,7 @@ impl OpenHumanSecurityGate {
decision_for_outcome(&call.tool_name, outcome)
}
async fn authorize_tool_with_facts(
- &self,
+ &self, ctx: &DispatchCtx,
call: &ToolCallRequest,
authorization_context: Option<&serde_json::Value>,
) -> TaResult<GateDecision> {
@@ -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(&ctx, tool).await,
None => false,
};
#[cfg(not(feature = "modules"))]
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_impl.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_impl.rs
index 0875ff229d..3a169f2f4f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_impl.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_impl.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::host::security_gate::{
@@ -31,7 +32,7 @@ impl SecurityGate for OpenHumanSecurityGate {
/// choice. A refusal at any stage is still terminal, and `channel_approved`
/// is carried forward so a later prompting stage does not ask twice.
async fn authorize_tool(&self, call: &ToolCallRequest) -> TaResult<GateDecision> {
- self.authorize_tool_with_facts(call, None).await
+ self.authorize_tool_with_facts(&DispatchCtx::ambient(), call, None).await
}
async fn authorize_tool_with_context(
@@ -39,7 +40,7 @@ impl SecurityGate for OpenHumanSecurityGate {
call: &ToolCallRequest,
context: Option<&serde_json::Value>,
) -> TaResult<GateDecision> {
- self.authorize_tool_with_facts(call, context).await
+ self.authorize_tool_with_facts(&DispatchCtx::ambient(), call, context).await
}
/// Runs OpenHuman's prompt-injection detector over `text`.
diff --git a/crates/openhuman-core/src/agent/tinyagents/journal.rs b/crates/openhuman-core/src/agent/tinyagents/journal.rs
index b8e69ac15a..e34193d216 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};
@@ -94,8 +95,8 @@ pub(crate) fn take_request_journal_run(request_id: &str) -> Option<String> {
/// Resolve the workspace directory the tenant's journal and run-status stores
/// 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()
+async fn resolve_workspace(ctx: &DispatchCtx, ) -> anyhow::Result<PathBuf> {
+ let config = crate::config::ops::load_current_or_init(&ctx)
.await
.map_err(|e| anyhow::anyhow!("[journal] load config for workspace: {e}"))?;
Ok(config.workspace_dir)
@@ -103,8 +104,8 @@ async fn resolve_workspace() -> anyhow::Result<PathBuf> {
/// The journal and run-status stores a turn's events and status go to: the
/// calling tenant's, in the storage backend.
-async fn journal_stores() -> anyhow::Result<(Arc<dyn AppendStore>, DriverStatusStore)> {
- let workspace = resolve_workspace().await?;
+async fn journal_stores(ctx: &DispatchCtx, ) -> anyhow::Result<(Arc<dyn AppendStore>, DriverStatusStore)> {
+ let workspace = resolve_workspace(&ctx).await?;
let stores = crate::agent::session_store::stores_or_ephemeral(&workspace);
let status = crate::agent::session_store::status_store_for(&workspace);
Ok((stores.journal, status))
@@ -182,13 +183,13 @@ impl TurnJournal {
///
/// [`OpenhumanEventBridge`]: crate::agent::tinyagents::observability::OpenhumanEventBridge
/// [`EventSink::with_stream_id`]: tinyagents_harness::events::EventSink::with_stream_id
-pub(crate) async fn attach_turn_journal(
+pub(crate) async fn attach_turn_journal(ctx: &DispatchCtx,
events: &EventSink,
model: &str,
run_id: RunId,
thread_id: Option<ThreadId>,
) -> Option<TurnJournal> {
- let (journal_store, status_store) = match journal_stores().await {
+ let (journal_store, status_store) = match journal_stores(&ctx).await {
Ok(stores) => stores,
Err(err) => {
log::debug!("[journal] skipping journal attach; {err}");
@@ -247,11 +248,11 @@ pub(crate) async fn attach_turn_journal(
/// reconnect mid-run and backfill the timeline from durable state instead of
/// relying on transient `AgentProgress` buffering. Best-effort: a missing store
/// or unknown run yields an empty `Vec`, not an error.
-pub(crate) async fn read_run_events(
+pub(crate) async fn read_run_events(ctx: &DispatchCtx,
run_id: &str,
from_offset: u64,
) -> anyhow::Result<Vec<AgentObservation>> {
- let (journal_store, _) = journal_stores().await?;
+ let (journal_store, _) = journal_stores(&ctx).await?;
let journal = StoreEventJournal::new(journal_store);
journal
.read_from(run_id, from_offset)
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs
index a6e7f8a8e1..0cc10e2170 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;
@@ -75,7 +76,7 @@ impl ApprovalSecurityMiddleware {
.unwrap_or(false)
}
- pub(crate) async fn requires_approval(&self, name: &str, args: &serde_json::Value) -> bool {
+ pub(crate) async fn requires_approval(&self, ctx: &DispatchCtx, name: &str, args: &serde_json::Value) -> bool {
#[cfg(feature = "modules")]
let desktop_approval_disabled = match self
.tool_sets
@@ -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(&ctx, tool.as_ref()).await,
None => false,
};
#[cfg(not(feature = "modules"))]
@@ -106,7 +107,7 @@ impl ApprovalResolver<crate::agent::tinyagents::host::OpenHumanRunContext>
) -> bool {
// Resolve external-effect up front so no tool borrow is held across the
// approval await.
- let has_ext = self.requires_approval(&call.name, &call.arguments).await;
+ let has_ext = self.requires_approval(&DispatchCtx::ambient(), &call.name, &call.arguments).await;
tracing::debug!(
tool = %call.name,
has_external_effect = has_ext,
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
index 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/middleware_approval_guard_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_approval_guard_tests.rs
index 74b6d86520..0ca8c0c982 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_approval_guard_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_approval_guard_tests.rs
@@ -69,10 +69,10 @@ async fn desktop_external_effect_inner() {
assert!(middleware.has_external_effect("desktop_goal", &json!({})));
assert!(
!middleware
- .requires_approval("desktop_goal", &json!({}))
+ .requires_approval(&ctx, "desktop_goal", &json!({}))
.await
);
- assert!(middleware.requires_approval("send_email", &json!({})).await);
+ assert!(middleware.requires_approval(&ctx, "send_email", &json!({})).await);
match previous {
Some(value) => unsafe { std::env::set_var("OPENHUMAN_WORKSPACE", value) },
None => unsafe { std::env::remove_var("OPENHUMAN_WORKSPACE") },
diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs
index 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 SubagentPayloadSummarizer
Ok(Box::new(move |request: GenerateRequest| {
Box::pin(async move {
- let config_loaded = crate::config::ops::load_current_or_init().await;
+ let config_loaded = crate::config::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.rs
index f491562c23..af2a843683 100644
--- a/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/replay/schemas.rs
@@ -221,14 +221,14 @@ 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()
+async fn configured_workspace(ctx: &DispatchCtx, ) -> Result<std::path::PathBuf, String> {
+ let config = crate::config::ops::load_current_or_init(&ctx)
.await
.map_err(|e| format!("failed to load config: {e}"))?;
Ok(config.workspace_dir)
}
-fn handle_run_events(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_events(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let payload: RunEventsParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
@@ -243,7 +243,7 @@ fn handle_run_events(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
limit
);
- let workspace = configured_workspace().await?;
+ let workspace = configured_workspace(&ctx).await?;
let page = read_run_events_page(&workspace, &payload.run_id, payload.offset, limit)
.await
.map_err(|e| format!("read run events failed: {e:#}"))?;
@@ -262,13 +262,13 @@ fn handle_run_events(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_run_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let payload: RunStatusParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
log::debug!("[rpc] openhuman.agent_run_status run_id={}", payload.run_id);
- let workspace = configured_workspace().await?;
+ let workspace = configured_workspace(&ctx).await?;
let status = read_run_status(&workspace, &payload.run_id)
.await
.map_err(|e| format!("read run status failed: {e:#}"))?;
@@ -283,7 +283,7 @@ fn handle_run_status(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_runs_active(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_runs_active(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let payload: RunsActiveParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
@@ -293,7 +293,7 @@ fn handle_runs_active(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll
payload.root_run_id
);
- let workspace = configured_workspace().await?;
+ let workspace = configured_workspace(&ctx).await?;
let runs = list_active_runs(
&workspace,
payload.thread_id.as_deref(),
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index bf8bd4cf91..0673e783ba 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@ -313,7 +313,7 @@ async fn drive_turn(
}
// `session_kv_store` self-gates on the dual-write flag (config default ON +
// env kill switch), returning `None` when disabled or unresolvable.
- if let Some(session_kv) = crate::agent::session_import::live::session_kv_store().await {
+ if let Some(session_kv) = crate::agent::session_import::live::session_kv_store(&ctx).await {
stores.get_or_insert_with(StoreRegistry::new).register(
crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE,
session_kv,
@@ -401,7 +401,7 @@ async fn drive_turn(
.as_ref()
.map(|scope| tinyagents_harness::ids::ThreadId::new(scope.task_id.clone()));
let turn_journal =
- journal::attach_turn_journal(&sink, model, journal_run_id.clone(), journal_thread_id).await;
+ journal::attach_turn_journal(&ctx, &sink, model, journal_run_id.clone(), journal_thread_id).await;
if !is_subagent {
if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {
request_id: Some(request_id),
diff --git a/crates/openhuman-core/src/agent/tools/todo.rs b/crates/openhuman-core/src/agent/tools/todo.rs
index 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 T
let 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.rs
index 05bbad5935..bc7b52012b 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;
@@ -235,7 +236,7 @@ async fn build_triage_parent(
Ok(parent_ctx)
}
-async fn dispatch_target_agent(agent_id: &str, prompt: &str) -> anyhow::Result<String> {
+async fn dispatch_target_agent(ctx: &DispatchCtx, agent_id: &str, prompt: &str) -> anyhow::Result<String> {
#[cfg(test)]
if agent_id.starts_with("missing-agent-") {
return Err(anyhow!(
@@ -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(&ctx)
.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.rs
index 08f116b842..2bd8db6a75 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};
@@ -75,8 +76,8 @@ fn retry_state() -> &'static RetryState {
/// caller does not create another fixed-interval cloud invocation.
/// 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()
+pub async fn run_triage(ctx: &DispatchCtx, envelope: &TriggerEnvelope) -> anyhow::Result<TriageOutcome> {
+ let config = crate::config::ops::load_current_or_init(&ctx)
.await
.context("loading config for triage turn")?;
let cloud = resolve_provider_with_config(&config)
diff --git a/crates/openhuman-core/src/channels/bus/subscriber.rs b/crates/openhuman-core/src/channels/bus/subscriber.rs
index 53e2ffb3dd..be6848e1c5 100644
--- a/crates/openhuman-core/src/channels/bus/subscriber.rs
+++ b/crates/openhuman-core/src/channels/bus/subscriber.rs
@@ -1,4 +1,5 @@
//! Host-owned agent turn orchestration with module-owned progressive delivery.
+use crate::core::runtime::DispatchCtx;
use super::delivery::ModuleProgressiveReply;
use crate::core::events::DomainEvent;
use async_trait::async_trait;
@@ -65,7 +66,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {
}
let session = crate::channels::runtime::session::channel_session();
- let config = match crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => config,
Err(error) => {
tracing::error!("[channel-inbound] failed to load configuration: {error}");
diff --git a/crates/openhuman-core/src/channels/controllers/schemas.rs b/crates/openhuman-core/src/channels/controllers/schemas.rs
index 6bcc7a2c78..b30b316ffe 100644
--- a/crates/openhuman-core/src/channels/controllers/schemas.rs
+++ b/crates/openhuman-core/src/channels/controllers/schemas.rs
@@ -239,9 +239,9 @@ fn handle_describe(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerF
})
}
-fn handle_connect(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_connect(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<ConnectParams>(params)?;
connect_with_config(&config, p).await
})
@@ -259,9 +259,9 @@ async fn connect_with_config(config: &Config, p: ConnectParams) -> Result<Value,
to_json(Outcome::new(outcome.value, logs))
}
-fn handle_disconnect(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_disconnect(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<DisconnectParams>(params)?;
let channel = p.channel.trim();
let mode: ChannelAuthMode = p
@@ -283,9 +283,9 @@ fn handle_disconnect(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = if params.is_empty() {
StatusParams { channel: None }
} else {
@@ -305,24 +305,24 @@ fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_set_default(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_set_default(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<SetDefaultParams>(params)?;
to_json(super::ops::set_default_channel(&mut config, p.channel.trim()).await?)
})
}
-fn handle_get_default(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_default(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::ops::get_default_channel(&config)?)
})
}
-fn handle_test(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_test(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<TestParams>(params)?;
test_with_config(&config, p).await
})
@@ -338,27 +338,27 @@ async fn test_with_config(config: &Config, params: TestParams) -> Result<Value,
)
}
-fn handle_discord_list_guilds(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_discord_list_guilds(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::ops::discord_list_guilds(&config).await?)
})
}
-fn handle_discord_list_channels(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_discord_list_channels(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<DiscordListChannelsParams>(params)?;
to_json(super::ops::discord_list_channels(&config, p.guild_id.trim()).await?)
})
}
fn handle_discord_check_permissions(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<DiscordCheckPermissionsParams>(params)?;
to_json(
super::ops::discord_check_permissions(&config, p.guild_id.trim(), p.channel_id.trim())
@@ -367,9 +367,9 @@ fn handle_discord_check_permissions(
})
}
-fn handle_send_message(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_send_message(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<SendMessageParams>(params)?;
send_with_config(&config, p).await
})
@@ -393,9 +393,9 @@ async fn send_with_config(config: &Config, p: SendMessageParams) -> Result<Value
))
}
-fn handle_send_reaction(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_send_reaction(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<SendReactionParams>(params)?;
let backend = OpenHumanChannelBackend::new(config.clone());
let result = backend
@@ -409,9 +409,9 @@ fn handle_send_reaction(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_create_thread(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_create_thread(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<CreateThreadParams>(params)?;
let backend = OpenHumanChannelBackend::new(config.clone());
let result = backend
@@ -425,9 +425,9 @@ fn handle_create_thread(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_update_thread(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update_thread(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<UpdateThreadParams>(params)?;
let backend = OpenHumanChannelBackend::new(config.clone());
let result = backend
@@ -446,9 +446,9 @@ fn handle_update_thread(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_list_threads(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_threads(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<ListThreadsParams>(params)?;
let backend = OpenHumanChannelBackend::new(config.clone());
let result = backend
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 7e93f972b7..b9b9f1d952 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -1,5 +1,6 @@
//! `channel_relay_inbound`: record a relayed message and run its turn.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use std::sync::Arc;
@@ -23,12 +24,12 @@ use crate::security::SecurityPolicy;
///
/// A message already recorded on its thread (`message_id`) is acknowledged as
/// a duplicate and runs no turn, so a gateway can retry a delivery.
-pub async fn channel_relay_inbound(params: RelayInboundParams) -> Result<Outcome<Value>, String> {
+pub async fn channel_relay_inbound(ctx: &DispatchCtx, params: RelayInboundParams) -> Result<Outcome<Value>, String> {
params.validate()?;
// In SaaS a relayed message must run as its user: with no tenant scope
// there is no workspace, stream or config it may touch.
let tenant = crate::core::runtime::current_tenant().map_err(|error| error.to_string())?;
- let config = crate::config::rpc::load_config_with_timeout().await?;
+ let config = crate::config::rpc::load_config_with_timeout(&ctx).await?;
let identity = crate::modules::channel_controller::prepare_identity(
&crate::modules::client(config.clone()),
tinychannels_bus::module_inbound::PrepareChannelIdentityRequest {
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs
index b84087bf32..be26092262 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs
@@ -207,7 +207,7 @@ async fn invalid_or_repeated_messages_start_no_turn() {
CoreContext::scope(ctx, async {
let mut bad = params("m1", "hello");
bad.chat_id = "a/b".into();
- let err = channel_relay_inbound(bad).await.expect_err("invalid");
+ let err = channel_relay_inbound(&ctx, bad).await.expect_err("invalid");
assert!(err.contains("chat_id"), "{err}");
let p = params("m1", "hello");
@@ -215,7 +215,7 @@ async fn invalid_or_repeated_messages_start_no_turn() {
store::record_inbound(&workspace, &p, &thread)
.await
.unwrap();
- let outcome = channel_relay_inbound(p)
+ let outcome = channel_relay_inbound(&ctx, p)
.await
.expect("duplicate is not an error");
let value = outcome.into_cli_compatible_json().unwrap();
diff --git a/crates/openhuman-core/src/channels/providers/relay/schemas.rs b/crates/openhuman-core/src/channels/providers/relay/schemas.rs
index ed5c812853..2695314c3d 100644
--- a/crates/openhuman-core/src/channels/providers/relay/schemas.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/schemas.rs
@@ -92,11 +92,11 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_relay_inbound(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_relay_inbound(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let params: RelayInboundParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- channel_relay_inbound(params)
+ channel_relay_inbound(&ctx, params)
.await?
.into_cli_compatible_json()
})
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
index 8a942d5227..ce9630ee35 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
@@ -1,5 +1,6 @@
//! Running one channel turn as a host agent.
+use crate::core::runtime::DispatchCtx;
use tokio::sync::mpsc;
use super::posture;
@@ -35,7 +36,7 @@ pub(crate) struct HostChannelTurn {
/// Run `turn` as `host`: its definition and host tools, inside its context,
/// under `turn.origin` and the posture that origin calls for.
-pub(crate) async fn run_host_agent_turn(
+pub(crate) async fn run_host_agent_turn(ctx: &DispatchCtx,
mut host: HostAgent,
turn: HostChannelTurn,
) -> anyhow::Result<AgentTurnResponse> {
@@ -89,7 +90,7 @@ pub(crate) async fn run_host_agent_turn(
// The chat's history is the channel's, so the session holds exactly that
// and never resumes a transcript of its own.
session.clear_history();
- session.seed_resume_from_messages(prior_turns, &message)?;
+ session.seed_resume_from_messages(&ctx, prior_turns, &message)?;
session.set_next_turn_overrides(crate::agent::TurnOverrides {
suppress_transcript_autoload: true,
..Default::default()
@@ -97,7 +98,7 @@ pub(crate) async fn run_host_agent_turn(
session.set_on_progress(progress);
let text = host
- .scope(session.run_single_with_approval(&message, Some(origin), approval))
+ .scope(session.run_single_with_approval(&ctx, &message, Some(origin), approval))
.await?;
Ok(AgentTurnResponse::with_resolved_route(
text,
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index 16fe49d7cf..696f88ed16 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -438,6 +438,7 @@ pub(crate) async fn process_channel_runtime_message(
Box<dyn std::future::Future<Output = anyhow::Result<AgentTurnResponse>> + Send + '_>,
> = match bound_agent {
Some(host) => Box::pin(run_host_agent_turn(
+ &ctx,
*host,
HostChannelTurn {
relay_thread: ctx.relay_thread.clone(),
diff --git a/crates/openhuman-core/src/channels/runtime/session_tests.rs b/crates/openhuman-core/src/channels/runtime/session_tests.rs
index 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/agent.rs b/crates/openhuman-core/src/config/ops/agent.rs
index 165d30ee39..f3f0df8bfc 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,16 +149,16 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_autonomy_settings(&mut config, update).await
}
/// Returns the current `[autonomy]` settings block as JSON (no secrets).
-pub async fn get_autonomy_settings() -> Result<Outcome<serde_json::Value>, String> {
- let config = load_config_with_timeout().await?;
+pub async fn get_autonomy_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let value = serde_json::to_value(&config.autonomy).map_err(|e| e.to_string())?;
Ok(Outcome::single_log(value, "autonomy settings read"))
}
@@ -170,9 +171,9 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
if config.autonomy.auto_approve.iter().any(|t| t == tool_name) {
tracing::debug!(
tool = tool_name,
@@ -264,18 +265,18 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_agent_settings(&mut config, update).await
}
/// 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_agent_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
crate::tools::timeout::set_tool_timeout_secs(config.agent.agent_timeout_secs);
let value = serde_json::json!({
"agent_timeout_secs": config.agent.agent_timeout_secs,
@@ -650,10 +651,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_agent_paths_settings(&mut config, update).await
}
@@ -666,8 +667,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_agent_paths(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
Ok(Outcome::new(
agent_paths_payload(&config),
vec![format!(
diff --git a/crates/openhuman-core/src/config/ops/computer.rs b/crates/openhuman-core/src/config/ops/computer.rs
index 6ae095a87f..9214271165 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,10 +94,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_computer_settings(&mut config, update).await
}
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 e33c32f10a..dcd64270c9 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,8 +148,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn reset_local_data(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let current_openhuman_dir = config_openhuman_dir(&config);
let default_openhuman_dir = default_openhuman_dir();
reset_local_data_for_paths(&current_openhuman_dir, &default_openhuman_dir).await
@@ -164,8 +165,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_data_paths(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let current_openhuman_dir = config_openhuman_dir(&config);
let default_openhuman_dir = default_openhuman_dir();
let active_workspace_marker = active_workspace_marker_path(&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 521c081958..1657afeb09 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,8 +136,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn load_and_get_client_config_snapshot(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let snapshot = client_config_json(&config);
Ok(Outcome::new(
snapshot,
@@ -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> {
- let config = load_config_with_timeout().await?;
+pub async fn load_and_get_config_snapshot(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).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",
@@ -178,7 +179,7 @@ pub async fn get_dashboard_settings() -> Result<Outcome<serde_json::Value>, Stri
"OPENHUMAN: get_dashboard_settings loading config"
);
- let config = load_config_with_timeout().await.map_err(|error| {
+ let config = load_config_with_timeout(&ctx).await.map_err(|error| {
tracing::warn!(
target: "openhuman_core::config",
request_id = %request_id,
diff --git a/crates/openhuman-core/src/config/ops/loader_current_tests.rs b/crates/openhuman-core/src/config/ops/loader_current_tests.rs
index 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/loader_io_chain_tests.rs b/crates/openhuman-core/src/config/ops/loader_io_chain_tests.rs
index b3c57c6c75..e008d521bb 100644
--- a/crates/openhuman-core/src/config/ops/loader_io_chain_tests.rs
+++ b/crates/openhuman-core/src/config/ops/loader_io_chain_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
// Regression for #4950 ("Clear App Data does nothing"). The GUI clear flow
@@ -99,7 +100,7 @@ async fn load_config_with_timeout_rejects_directory_config() {
let prev = std::env::var("OPENHUMAN_WORKSPACE").ok();
std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path().to_str().unwrap());
- let result = load_config_with_timeout().await;
+ let result = load_config_with_timeout(&DispatchCtx::process_default()).await;
match prev {
Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),
diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs
index a0bf801f8d..7d7680b4eb 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,10 +440,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_model_settings(&mut config, update).await
}
@@ -484,10 +485,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_memory_settings(&mut config, update).await
}
@@ -542,10 +543,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_runtime_settings(&mut config, update).await
}
@@ -619,10 +620,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_local_ai_settings(&mut config, update).await
}
@@ -657,16 +658,16 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_composio_trigger_settings(&mut config, update).await
}
/// Reads the current composio trigger-triage settings.
-pub async fn get_composio_trigger_settings() -> Result<Outcome<serde_json::Value>, String> {
- let config = load_config_with_timeout().await?;
+pub async fn get_composio_trigger_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let result = serde_json::json!({
"triage_disabled": config.composio.triage_disabled,
"triage_disabled_toolkits": config.composio.triage_disabled_toolkits,
@@ -687,8 +688,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn load_and_resolve_api_url(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let resolved = resolve_backend_api_url(&config);
Ok(Outcome::new(
serde_json::json!({ "api_url": resolved }),
diff --git a/crates/openhuman-core/src/config/ops/privacy.rs b/crates/openhuman-core/src/config/ops/privacy.rs
index b45d001abc..76c11a7d2f 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,8 +42,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_privacy_mode(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
log::debug!(
"[privacy][rpc] get_privacy_mode -> {:?}",
config.privacy.mode
@@ -95,10 +96,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_privacy_settings(&mut config, update).await
}
diff --git a/crates/openhuman-core/src/config/ops/sandbox.rs b/crates/openhuman-core/src/config/ops/sandbox.rs
index e5e7e4f845..718461be3e 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,8 +17,8 @@ pub struct SandboxSettingsPatch {
pub env_passthrough: Option<Vec<String>>,
}
-pub async fn get_sandbox_settings() -> Result<Outcome<serde_json::Value>, String> {
- let config = load_config_with_timeout().await?;
+pub async fn get_sandbox_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let sandbox = &config.sandbox;
let docker = &config.runtime.docker;
@@ -120,10 +121,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_sandbox_settings(&mut config, update).await
}
diff --git a/crates/openhuman-core/src/config/ops/search.rs b/crates/openhuman-core/src/config/ops/search.rs
index 63a6d87d86..2f4fc154b7 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,10 +310,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_search_settings(&mut config, update).await
}
@@ -390,8 +391,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_search_settings(ctx: &DispatchCtx, ) -> Result<Outcome<Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
Ok(Outcome::new(
search_settings_json(&config),
vec!["search settings read".to_string()],
diff --git a/crates/openhuman-core/src/config/ops/ui.rs b/crates/openhuman-core/src/config/ops/ui.rs
index 6ef6de8b00..8635d72f63 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,10 +163,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_browser_settings(&mut config, update).await
}
@@ -229,10 +230,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_user_timezone(&mut config, timezone).await
}
@@ -246,15 +247,15 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
apply_analytics_settings(&mut config, update).await
}
/// 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> {
@@ -267,7 +268,7 @@ pub async fn workspace_onboarding_flag_resolve(
{
return Err("Invalid onboarding flag name".to_string());
}
- let workspace_dir = match load_config_with_timeout().await {
+ let workspace_dir = match load_config_with_timeout(&ctx).await {
Ok(cfg) => cfg.workspace_dir,
Err(_) => fallback_workspace_dir(),
};
@@ -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,
@@ -308,7 +309,7 @@ pub async fn workspace_onboarding_flag_set(
{
return Err("Invalid onboarding flag name".to_string());
}
- let workspace_dir = match load_config_with_timeout().await {
+ let workspace_dir = match load_config_with_timeout(&ctx).await {
Ok(cfg) => cfg.workspace_dir,
Err(_) => fallback_workspace_dir(),
};
@@ -331,8 +332,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_onboarding_completed(ctx: &DispatchCtx, ) -> Result<Outcome<bool>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
Ok(Outcome::single_log(
config.onboarding_completed,
"onboarding_completed read from config",
@@ -343,9 +344,9 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
let was_completed = config.onboarding_completed;
config.onboarding_completed = value;
@@ -376,8 +377,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_dictation_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let result = json!({
"enabled": config.dictation.enabled,
"hotkey": config.dictation.hotkey,
@@ -393,10 +394,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
if let Some(enabled) = update.enabled {
config.dictation.enabled = enabled;
}
@@ -439,8 +440,8 @@ 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> {
- let config = load_config_with_timeout().await?;
+pub async fn get_voice_server_settings(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout(&ctx).await?;
let result = json!({
"auto_start": config.voice_server.auto_start,
"hotkey": config.voice_server.hotkey,
@@ -460,10 +461,10 @@ 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 = load_config_with_timeout().await?;
+ let mut config = load_config_with_timeout(&ctx).await?;
if let Some(auto_start) = update.auto_start {
config.voice_server.auto_start = auto_start;
}
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.rs
index e4c6635d65..55e4271d69 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,13 +453,13 @@ 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());
// Reload from scratch and confirm the saved value sticks.
- let reloaded = load_config_with_timeout().await.expect("reload");
+ let reloaded = load_config_with_timeout(&DispatchCtx::process_default()).await.expect("reload");
assert_eq!(reloaded.autonomy.max_actions_per_hour, 500);
unsafe {
@@ -559,15 +560,15 @@ 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)");
- let reloaded = load_config_with_timeout().await.expect("reload");
+ let reloaded = load_config_with_timeout(&DispatchCtx::process_default()).await.expect("reload");
let hits = reloaded
.autonomy
.auto_approve
diff --git a/crates/openhuman-core/src/config/schemas/controllers/agent.rs b/crates/openhuman-core/src/config/schemas/controllers/agent.rs
index fa96ab7ef6..968de15297 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 {
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.rs
index 8521ff62fd..3abeb45e6d 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 { 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 { 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.rs
index 6ca50df047..047e18d7fb 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 {
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 {
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.rs
index 4dddde119b..66860d6bd7 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 { 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,19 +31,19 @@ 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 { to_json(config_rpc::get_voice_server_settings(&ctx).await?) })
}
pub(super) fn handle_update_voice_server_settings(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
@@ -60,12 +60,12 @@ 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 setting
// silently wouldn't apply until the next launch.
- match config_rpc::load_config_with_timeout().await {
+ match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => {
log::info!("[config][rpc] voice settings saved; applying live always-on state");
crate::voice::always_on::start_if_enabled(&config).await;
diff --git a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs
index c04b46d7f1..aa20d0c311 100644
--- a/crates/openhuman-core/src/config/schemas/controllers/workspace.rs
+++ b/crates/openhuman-core/src/config/schemas/controllers/workspace.rs
@@ -13,13 +13,14 @@ 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(
+ &ctx,
payload.flag_name,
DEFAULT_ONBOARDING_FLAG_NAME,
)
@@ -29,13 +30,14 @@ 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(
+ &ctx,
payload.flag_name,
DEFAULT_ONBOARDING_FLAG_NAME,
payload.value,
@@ -46,7 +48,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,26 +56,26 @@ 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?)
})
}
pub(super) fn handle_get_user_timezone(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::core::Outcome::single_log(
config_rpc::user_timezone_json(&config),
"user time zone read",
@@ -82,12 +84,12 @@ pub(super) fn handle_get_user_timezone(
}
pub(super) fn handle_get_analytics_settings(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
use crate::core::Outcome;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = serde_json::json!({
"enabled": config.observability.analytics_enabled,
});
@@ -99,10 +101,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 { to_json(config_rpc::get_dashboard_settings(&ctx).await?) })
}
pub(super) fn handle_agent_server_status(
@@ -113,19 +115,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 { 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 +146,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 +161,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 {
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 +185,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 +201,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 +215,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 { 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/tools.rs b/crates/openhuman-core/src/config/tools.rs
index 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 {
true
diff --git a/crates/openhuman-core/src/config/workspace/ops.rs b/crates/openhuman-core/src/config/workspace/ops.rs
index d4f434b65f..d6d1fbd0b9 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,8 +68,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn init_workspace(ctx: &DispatchCtx, force: bool) -> Result<serde_json::Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let workspace_dir = config.workspace_dir.clone();
let mut created_dirs = Vec::new();
diff --git a/crates/openhuman-core/src/config/workspace/ops_tests.rs b/crates/openhuman-core/src/config/workspace/ops_tests.rs
index 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/schemas.rs b/crates/openhuman-core/src/config/workspace/schemas.rs
index 2a3da492e2..4bdc262643 100644
--- a/crates/openhuman-core/src/config/workspace/schemas.rs
+++ b/crates/openhuman-core/src/config/workspace/schemas.rs
@@ -116,9 +116,9 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_file_read(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_file_read(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let filename = read_required::<String>(&params, "filename")?;
let filename = filename.trim();
log::debug!("[workspace][rpc] handle_file_read filename='{filename}'");
@@ -130,9 +130,9 @@ fn handle_file_read(_ctx: DispatchCtx, params: Map<String, Value>) -> Controller
})
}
-fn handle_file_write(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_file_write(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let filename = read_required::<String>(&params, "filename")?;
let contents = read_required::<String>(&params, "contents")?;
let filename = filename.trim();
@@ -149,9 +149,9 @@ fn handle_file_write(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_file_reset(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_file_reset(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let filename = read_required::<String>(&params, "filename")?;
let filename = filename.trim();
log::debug!("[workspace][rpc] handle_file_reset filename='{filename}'");
diff --git a/crates/openhuman-core/src/config/workspace/tools.rs b/crates/openhuman-core/src/config/workspace/tools.rs
index 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/agent_cli.rs b/crates/openhuman-core/src/core/agent_cli.rs
index dfb85de1fd..51335003cf 100644
--- a/crates/openhuman-core/src/core/agent_cli.rs
+++ b/crates/openhuman-core/src/core/agent_cli.rs
@@ -20,6 +20,7 @@
//! any built-in or workspace-custom agent id (e.g. `planner`,
//! `critic`).
+use crate::core::runtime::DispatchCtx;
use anyhow::{anyhow, Result};
use std::path::PathBuf;
@@ -30,16 +31,16 @@ use crate::agent::debug::{
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
/// Entry point for `openhuman agent <subcommand>`.
-pub fn run_agent_command(args: &[String]) -> Result<()> {
+pub fn run_agent_command(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
if args.is_empty() || is_help(&args[0]) {
print_agent_help();
return Ok(());
}
match args[0].as_str() {
- "dump-prompt" => run_dump_prompt(&args[1..]),
+ "dump-prompt" => run_dump_prompt(&ctx, &args[1..]),
"dump-all" => run_dump_all(&args[1..]),
- "prompt-size" => run_prompt_size(&args[1..]),
+ "prompt-size" => run_prompt_size(&ctx, &args[1..]),
"list" => run_list(&args[1..]),
other => Err(anyhow!(
"unknown agent subcommand '{other}'. Run `openhuman agent --help`."
@@ -147,7 +148,7 @@ fn parse_prompt_size_flags(args: &[String]) -> Result<PromptSizeFlags> {
/// With `--agent`, renders one agent. Without it, renders every registered
/// agent through the same `dump_all_agent_prompts` path `dump-all` uses, so
/// the fleet view and the per-agent view cannot disagree.
-fn run_prompt_size(args: &[String]) -> Result<()> {
+fn run_prompt_size(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
let flags = parse_prompt_size_flags(args)?;
init_quiet_logging(flags.verbose);
@@ -176,7 +177,7 @@ fn run_prompt_size(args: &[String]) -> Result<()> {
options.workspace_dir_override = flags.workspace.clone();
options.config_path_override = config_path.clone();
options.model_override = flags.model.clone();
- vec![rt.block_on(PromptSizeReport::build(options))?]
+ vec![rt.block_on(PromptSizeReport::build(&ctx, options))?]
}
None => {
let dumps: Vec<DumpedPrompt> = rt.block_on(async {
@@ -421,7 +422,7 @@ fn parse_dump_flags(args: &[String]) -> Result<DumpFlags> {
Ok(out)
}
-fn run_dump_prompt(args: &[String]) -> Result<()> {
+fn run_dump_prompt(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
let flags = parse_dump_flags(args)?;
let agent = flags.agent.clone().ok_or_else(|| {
anyhow!("--agent <id> is required (e.g. `orchestrator`, `planner`, `critic`)")
@@ -453,7 +454,7 @@ fn run_dump_prompt(args: &[String]) -> Result<()> {
.max_blocking_threads(crate::core::runtime::MAX_BLOCKING_THREADS)
.build()?;
log::debug!("[agent-cli] run_dump_prompt: calling dump_agent_prompt");
- let dumped = rt.block_on(async { dump_agent_prompt(options).await })?;
+ let dumped = rt.block_on(async { dump_agent_prompt(&ctx, options).await })?;
log::debug!(
"[agent-cli] run_dump_prompt: dump returned (tools={}, skill_tools={}, prompt_bytes={})",
dumped.tool_names.len(),
diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rs
index 23a3045356..d96bb7a538 100644
--- a/crates/openhuman-core/src/core/cli.rs
+++ b/crates/openhuman-core/src/core/cli.rs
@@ -43,8 +43,8 @@ Contribute & Star us on GitHub: https://github.com/tinyhumansai/openhuman
///
/// Returns an error if the command fails, parameters are invalid, or if
/// the subcommand/namespace is unknown.
-pub fn run_from_cli_args(args: &[String]) -> Result<()> {
- run_from_cli_args_with(args, None)
+pub fn run_from_cli_args(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
+ run_from_cli_args_with(&ctx, args, None)
}
/// Whether the parsed invocation only asks the CLI to print help.
@@ -78,7 +78,7 @@ pub(crate) fn is_help_only(args: &[String]) -> bool {
/// [`run_from_cli_args`] with a host-supplied boot description for `run` /
/// `serve`; see [`crate::run_core_from_args_with`].
-pub fn run_from_cli_args_with(
+pub fn run_from_cli_args_with(ctx: &DispatchCtx,
args: &[String],
host_boot: Option<crate::core::server_launcher::HostBoot>,
) -> Result<()> {
@@ -108,7 +108,7 @@ pub fn run_from_cli_args_with(
// Match on the first argument to determine the subcommand.
match args[0].as_str() {
"run" | "serve" => super::cli_serve::run_server_command(&args[1..], host_boot),
- "mcp" | "mcp-server" => crate::mcp::server::run_stdio_from_cli(&args[1..]),
+ "mcp" | "mcp-server" => crate::mcp::server::run_stdio_from_cli(&ctx, &args[1..]),
// Keep the historical names as a migration diagnostic now that the
// terminal frontend is its own workspace crate and executable.
"tui" | "chat" => run_moved_tui_diagnostic(),
@@ -118,7 +118,7 @@ pub fn run_from_cli_args_with(
"[cli] dispatching to agent subcommand, args={:?}",
&args[1..]
);
- crate::core::agent_cli::run_agent_command(&args[1..])
+ crate::core::agent_cli::run_agent_command(&ctx, &args[1..])
}
"sentry-test" => run_sentry_test_command(&args[1..]),
// Generic namespace dispatcher: `openhuman <namespace> <function> ...`
diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rs
index b8f57c7189..f0f4d5264d 100644
--- a/crates/openhuman-core/src/core/cli_tests.rs
+++ b/crates/openhuman-core/src/core/cli_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::{
grouped_schemas, is_help_only, load_dotenv_for_cli, parse_function_params, parse_input_value,
parse_launch_options,
@@ -279,7 +280,7 @@ fn mcp_server_alias_reports_disabled_build_when_gate_off() {
fn tui_subcommand_points_to_the_separate_executable() {
let _guard = env_lock();
- let err = crate::core::cli::run_from_cli_args(&["tui".to_string()])
+ let err = crate::core::cli::run_from_cli_args(&DispatchCtx::process_default(), &["tui".to_string()])
.expect_err("`openhuman tui` must point to the standalone terminal client");
let msg = err.to_string();
@@ -298,7 +299,7 @@ fn tui_subcommand_points_to_the_separate_executable() {
fn chat_alias_points_to_the_separate_executable() {
let _guard = env_lock();
- let err = crate::core::cli::run_from_cli_args(&["chat".to_string()])
+ let err = crate::core::cli::run_from_cli_args(&DispatchCtx::process_default(), &["chat".to_string()])
.expect_err("`openhuman chat` must point to the standalone terminal client");
assert!(
diff --git a/crates/openhuman-core/src/core/invoke.rs b/crates/openhuman-core/src/core/invoke.rs
index 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.rs
index dd92524d5f..ca0917b654 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
@@ -14,7 +15,7 @@
/// env override is ignored and a domain event is published so the UI can
/// surface a banner; under CLI / Docker the override is honored (with a
/// noisy log + a domain event so any connected dashboard can flag it).
-pub(crate) async fn bootstrap_core_runtime(
+pub(crate) async fn bootstrap_core_runtime(ctx: &DispatchCtx,
host_kind: crate::core::types::HostKind,
config: Option<crate::config::Config>,
domains: crate::core::runtime::DomainSet,
@@ -69,6 +70,7 @@ pub(crate) async fn bootstrap_core_runtime(
// bootstrap_core_runtime() cannot double-subscribe (and a later, wider
// DomainSet still installs its newly-enabled groups).
super::subscribers::register_domain_subscribers(
+ &ctx,
workspace_dir.clone(),
cfg.clone(),
embedded_core,
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 63eb9e7425..6ffce568fd 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -305,7 +305,7 @@ impl CoreContext {
// background jobs start later, from CoreRuntime::start_services(), after a transport binds
// succeeds.
let runtime_config = config.clone();
- super::bootstrap::bootstrap_core_runtime(host_kind, config, domains).await;
+ super::bootstrap::bootstrap_core_runtime(&ctx, host_kind, config, domains).await;
Ok((ctx, has_operator_token, runtime_config))
}
diff --git a/crates/openhuman-core/src/core/runtime/services.rs b/crates/openhuman-core/src/core/runtime/services.rs
index bf67177af9..1d516ac101 100644
--- a/crates/openhuman-core/src/core/runtime/services.rs
+++ b/crates/openhuman-core/src/core/runtime/services.rs
@@ -256,7 +256,7 @@ pub fn spawn_cron_service(
ctx: std::sync::Arc<crate::core::runtime::CoreContext>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(crate::core::runtime::CoreContext::scope(ctx, async {
- match crate::config::ops::load_config_with_timeout().await {
+ match crate::config::ops::load_config_with_timeout(&ctx).await {
Ok(config) => {
if !config.cron.enabled {
log::info!("[cron] scheduler disabled via config; skipping");
diff --git a/crates/openhuman-core/src/core/runtime/subscribers.rs b/crates/openhuman-core/src/core/runtime/subscribers.rs
index 352c99de1e..150136805f 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
@@ -104,7 +105,7 @@ fn group_first_time(group: crate::core::all::DomainGroup) -> bool {
/// it is enabled after the event bus is ready, so widening the ambient
/// `DomainSet` on a later call (`harness()` → `full()`) still installs the
/// newly-enabled groups without double-subscribing the ones already registered.
-pub(super) fn register_domain_subscribers(
+pub(super) fn register_domain_subscribers(ctx: &DispatchCtx,
workspace_dir: std::path::PathBuf,
config: crate::config::Config,
embedded_core: bool,
@@ -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(&ctx, &config).await;
});
}
diff --git a/crates/openhuman-core/src/core/runtime/subscribers_tests.rs b/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
index 7432a1c953..30d79a7cba 100644
--- a/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/subscribers_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::{group_first_time_when_bus_ready, DomainSubscriberPlan};
use crate::config::test_env::EnvVarGuard;
@@ -198,6 +199,7 @@ async fn tool_timeout_seeds_on_channelless_core_boot() {
// so even `none()` must seed. `embedded_core = true` skips the standalone
// process-exit shutdown subscriber.
super::register_domain_subscribers(
+ &DispatchCtx::process_default(),
tmp.path().to_path_buf(),
config,
true,
diff --git a/crates/openhuman-core/src/core/subsystem/schemas.rs b/crates/openhuman-core/src/core/subsystem/schemas.rs
index ae5b1d1b20..e2071fc81f 100644
--- a/crates/openhuman-core/src/core/subsystem/schemas.rs
+++ b/crates/openhuman-core/src/core/subsystem/schemas.rs
@@ -72,8 +72,8 @@ pub fn schemas(function: &str) -> ControllerSchema {
///
/// Memory is the only occupant today. This is also what
/// [`crate::core::subsystems_cli`] renders as a table.
-pub async fn subsystems_status() -> Vec<SubsystemStatus> {
- match crate::config::rpc::load_config_with_timeout().await {
+pub async fn subsystems_status(ctx: &DispatchCtx, ) -> Vec<SubsystemStatus> {
+ match crate::config::rpc::load_config_with_timeout(&ctx).await {
Ok(config) => vec![crate::memory::status::subsystem_status(&config).await],
Err(error) => {
log::warn!("[subsystems] config unavailable for status: {error}");
@@ -82,9 +82,9 @@ pub async fn subsystems_status() -> Vec<SubsystemStatus> {
}
}
-fn handle_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let rows = subsystems_status().await;
+ let rows = subsystems_status(&ctx).await;
log::debug!("[subsystem] status requested: {} slot(s)", rows.len());
Outcome::new(serde_json::json!({ "subsystems": rows }), vec![]).into_cli_compatible_json()
})
diff --git a/crates/openhuman-core/src/core/subsystems_cli.rs b/crates/openhuman-core/src/core/subsystems_cli.rs
index acfb543e6b..db2802cf61 100644
--- a/crates/openhuman-core/src/core/subsystems_cli.rs
+++ b/crates/openhuman-core/src/core/subsystems_cli.rs
@@ -13,11 +13,12 @@
//! openhuman subsystems status # JSON
//! ```
+use crate::core::runtime::DispatchCtx;
use anyhow::Result;
use crate::core::subsystem::{subsystems_status, SubsystemStatus};
-pub fn run_subsystems_command(args: &[String]) -> Result<()> {
+pub fn run_subsystems_command(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
if args.iter().any(|a| a == "-h" || a == "--help") {
print_help();
return Ok(());
@@ -29,7 +30,7 @@ pub fn run_subsystems_command(args: &[String]) -> Result<()> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
- let rows = rt.block_on(cli_subsystems_status());
+ let rows = rt.block_on(cli_subsystems_status(&ctx));
println!(
"{:<10} {:<14} {:<9} {:<9} {:<9} CAPABILITIES",
@@ -65,8 +66,8 @@ pub fn run_subsystems_command(args: &[String]) -> Result<()> {
/// The slot table for a standalone CLI invocation: the same rows the
/// `subsystems status` RPC returns, resolved from the on-disk config.
-async fn cli_subsystems_status() -> Vec<SubsystemStatus> {
- subsystems_status().await
+async fn cli_subsystems_status(ctx: &DispatchCtx, ) -> Vec<SubsystemStatus> {
+ subsystems_status(&ctx).await
}
fn print_help() {
diff --git a/crates/openhuman-core/src/core/subsystems_cli_tests.rs b/crates/openhuman-core/src/core/subsystems_cli_tests.rs
index 2d5c1b1801..e26c1c3200 100644
--- a/crates/openhuman-core/src/core/subsystems_cli_tests.rs
+++ b/crates/openhuman-core/src/core/subsystems_cli_tests.rs
@@ -1,14 +1,15 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
#[test]
fn help_flag_short_circuits_without_probing_a_driver() {
- run_subsystems_command(&["--help".to_string()]).expect("help succeeds");
- run_subsystems_command(&["-h".to_string()]).expect("short help succeeds");
+ run_subsystems_command(&DispatchCtx::process_default(), &["--help".to_string()]).expect("help succeeds");
+ run_subsystems_command(&DispatchCtx::process_default(), &["-h".to_string()]).expect("short help succeeds");
}
#[test]
fn bare_invocation_renders_the_table() {
- run_subsystems_command(&[]).expect("table renders");
+ run_subsystems_command(&DispatchCtx::process_default(), &[]).expect("table renders");
}
#[test]
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs
index 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/cron/schemas.rs b/crates/openhuman-core/src/cron/schemas.rs
index 5eb382e1df..0897f191c6 100644
--- a/crates/openhuman-core/src/cron/schemas.rs
+++ b/crates/openhuman-core/src/cron/schemas.rs
@@ -282,9 +282,9 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_add(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_add(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let schedule: tinyflows_schedule::types::Schedule = read_required(&params, "schedule")?;
let name = params
@@ -403,41 +403,41 @@ fn handle_add(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
})
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::cron::rpc::cron_list(&config).await?)
})
}
-fn handle_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let job_id = read_required::<String>(&params, "job_id")?;
let patch = read_required::<CronJobPatch>(&params, "patch")?;
to_json(crate::cron::rpc::cron_update(&config, job_id.trim(), patch).await?)
})
}
-fn handle_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let job_id = read_required::<String>(&params, "job_id")?;
to_json(crate::cron::rpc::cron_remove(&config, job_id.trim()).await?)
})
}
-fn handle_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let job_id = read_required::<String>(&params, "job_id")?;
to_json(crate::cron::rpc::cron_run(&config, job_id.trim()).await?)
})
}
-fn handle_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_runs(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let job_id = read_required::<String>(&params, "job_id")?;
let limit = read_optional_u64(&params, "limit")?
.map(|raw| usize::try_from(raw).map_err(|_| "limit is too large for usize".to_string()))
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 5247fbda1d..cae7aecd37 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,12 +39,12 @@ 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();
let t_config = Instant::now();
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// Latch corruption recovery from *this* poll's load, not only from boot.
// `load_config_with_timeout` re-reads config.toml on every snapshot, so a
// config that becomes corrupt after boot is healed here — carrying a fresh
@@ -140,10 +141,10 @@ 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 = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let _guard = APP_STATE_FILE_LOCK.lock();
let mut current = load_stored_app_state_unlocked(&config)?;
diff --git a/crates/openhuman-core/src/desktop/app_state/schemas.rs b/crates/openhuman-core/src/desktop/app_state/schemas.rs
index 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/control/ops.rs b/crates/openhuman-core/src/desktop/control/ops.rs
index e4c5015d90..aa006d1f9e 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,11 +26,11 @@ 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;
}
- crate::config::rpc::load_config_with_timeout()
+ crate::config::rpc::load_config_with_timeout(&ctx)
.await
.is_ok_and(|config| approval_bypass_decision(&config, tool))
}
diff --git a/crates/openhuman-core/src/desktop/control/schemas.rs b/crates/openhuman-core/src/desktop/control/schemas.rs
index a1f4197168..5b44abdeb2 100644
--- a/crates/openhuman-core/src/desktop/control/schemas.rs
+++ b/crates/openhuman-core/src/desktop/control/schemas.rs
@@ -76,9 +76,9 @@ fn schema(function: &'static str) -> ControllerSchema {
}
}
-fn status(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
+fn status(ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("config unavailable: {error}"))?;
crate::core::runtime::components::require_config(&config, "computer")?;
@@ -86,13 +86,13 @@ fn status(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
})
}
-fn set_enabled(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn set_enabled(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let value = params
.get("enabled")
.and_then(Value::as_bool)
.ok_or_else(|| "enabled must be a boolean".to_owned())?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("config unavailable: {error}"))?;
crate::core::runtime::components::require_config(&config, "computer")?;
@@ -101,9 +101,9 @@ fn set_enabled(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn probe(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
+fn probe(ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("config unavailable: {error}"))?;
crate::core::runtime::components::require_config(&config, "computer")?;
@@ -111,9 +111,9 @@ fn probe(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
})
}
-fn pending(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
+fn pending(ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("config unavailable: {error}"))?;
crate::core::runtime::components::require_config(&config, "computer")?;
@@ -121,7 +121,7 @@ fn pending(_ctx: DispatchCtx, _: Map<String, Value>) -> ControllerFuture {
})
}
-fn confirm(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn confirm(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let id = params
.get("confirmation_id")
@@ -132,7 +132,7 @@ fn confirm(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
.get("approve")
.and_then(Value::as_bool)
.ok_or_else(|| "approve must be a boolean".to_owned())?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("config unavailable: {error}"))?;
crate::core::runtime::components::require_config(&config, "computer")?;
diff --git a/crates/openhuman-core/src/desktop/control/tools.rs b/crates/openhuman-core/src/desktop/control/tools.rs
index f91f69ce9d..2c3d6ccc18 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 crate::config::rpc::load_config_with_timeout().await {
+ let live_config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/desktop/dashboard/schemas.rs b/crates/openhuman-core/src/desktop/dashboard/schemas.rs
index 10d5159529..2d87f75172 100644
--- a/crates/openhuman-core/src/desktop/dashboard/schemas.rs
+++ b/crates/openhuman-core/src/desktop/dashboard/schemas.rs
@@ -164,12 +164,12 @@ fn model_health_config_fields() -> Vec<FieldSchema> {
}
fn handle_dashboard_model_health(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
log::debug!("[dashboard] model_health request received");
- let cfg = crate::config::rpc::load_config_with_timeout()
+ let cfg = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|err| {
log::warn!("[dashboard] model_health failed to load config: {err}");
diff --git a/crates/openhuman-core/src/desktop/notifications/rpc.rs b/crates/openhuman-core/src/desktop/notifications/rpc.rs
index bc7eb65535..80a83fb218 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,9 +36,9 @@ 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 = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let req: NotificationIngestRequest = serde_json::from_value(Value::Object(params.clone()))
.map_err(|e| format!("[notification_intel] invalid ingest params: {e}"))?;
@@ -108,7 +109,7 @@ pub async fn handle_ingest(params: Map<String, Value>) -> Result<Value, String>
received_at: ingest_started_at,
};
- match run_triage(&envelope).await {
+ match run_triage(&ctx, &envelope).await {
Ok(TriageOutcome::Decision(triage_run)) => {
let action = triage_run.decision.action.as_str().to_string();
let reason = triage_run.decision.reason.clone();
@@ -257,8 +258,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_list(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider = params
.get("provider")
@@ -294,8 +295,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_mark_read(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = params
.get("id")
@@ -313,8 +314,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_settings_get(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider = params
.get("provider")
.and_then(|v| v.as_str())
@@ -326,8 +327,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_settings_set(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let req: NotificationSettingsUpsertRequest = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("[notification_intel] invalid settings_set params: {e}"))?;
let clamped = NotificationSettings {
@@ -347,8 +348,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_dismiss(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = params
.get("id")
.and_then(|v| v.as_str())
@@ -367,8 +368,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_mark_acted(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = params
.get("id")
.and_then(|v| v.as_str())
@@ -396,8 +397,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_core_list(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let only_unread = params
.get("only_unread")
@@ -420,8 +421,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_core_mark_read(ctx: &DispatchCtx, params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = params
.get("id")
.and_then(|v| v.as_str())
@@ -440,8 +441,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn handle_stats(ctx: &DispatchCtx, _params: Map<String, Value>) -> Result<Value, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
tracing::debug!("[notification_intel] stats requested");
let s = store::stats(&config).map_err(|e| format!("[notification_intel] stats failed: {e}"))?;
diff --git a/crates/openhuman-core/src/desktop/notifications/schemas.rs b/crates/openhuman-core/src/desktop/notifications/schemas.rs
index 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/builder_host.rs b/crates/openhuman-core/src/flows/builder_host.rs
index 72dd1cf945..c0dd2a3955 100644
--- a/crates/openhuman-core/src/flows/builder_host.rs
+++ b/crates/openhuman-core/src/flows/builder_host.rs
@@ -8,6 +8,7 @@
//! [`OverlayNodeKinds`] is the node-kind catalog with this host's caveats
//! appended.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use async_trait::async_trait;
@@ -222,7 +223,7 @@ impl BuilderGates for FlowsHost {
#[async_trait]
impl AgentDirectory for FlowsHost {
async fn list(&self) -> PortResult<Vec<AgentDefinition>> {
- let agents = crate::agent::registry::list_agents(false)
+ let agents = crate::agent::registry::list_agents(&DispatchCtx::ambient(), false)
.await
.map_err(|e| e.to_string())?;
Ok(agents
diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rs
index 3593128a4f..bebca1096d 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 crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
@@ -472,7 +473,7 @@ impl Tool for FlowMemoryRememberTool {
));
}
- let config = match crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => config,
Err(error) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rs
index 4467b1f682..b71b88001a 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!({
@@ -200,7 +201,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(
let approval = ApprovalTurnContext::chat(chat_ctx).with_copilot_stream();
let run = with_origin(
origin.clone(),
- agent.run_single_with_approval(&prompt, Some(origin), approval),
+ agent.run_single_with_approval(&ctx, &prompt, Some(origin), approval),
);
let run =
tokio::time::timeout(std::time::Duration::from_secs(FLOW_BUILD_TIMEOUT_SECS), run);
@@ -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/builder_gates.rs b/crates/openhuman-core/src/flows/ops/builder_gates.rs
index d0a0081e05..d4ef841e7d 100644
--- a/crates/openhuman-core/src/flows/ops/builder_gates.rs
+++ b/crates/openhuman-core/src/flows/ops/builder_gates.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
/// The single canonical definition of the builder hard-gate stack: the
@@ -130,7 +131,7 @@ impl tinyflows::gates::BuilderGateHost for OpenHumanBuilderGateHost<'_> {
use tinyflows::gates::HostGateStage;
Ok(match stage {
HostGateStage::ToolPolicy => validate_upload_paths(graph),
- HostGateStage::AgentReferences => validate_agent_refs(self.config, graph).await,
+ HostGateStage::AgentReferences => validate_agent_refs(&DispatchCtx::ambient(), self.config, graph).await,
HostGateStage::Connections => validate_connection_refs(self.config, graph).await,
HostGateStage::ToolContracts => validate_tool_contracts(self.config, graph).await,
})
@@ -340,7 +341,7 @@ pub(crate) async fn build_builder_proposal(
/// non-harness `agent_ref`s previously triggered one `config_rpc::
/// load_config_with_timeout` per node; an all-`Harness`/no-custom-ref graph
/// still never reads it at all.
-pub(crate) async fn validate_agent_refs(config: &Config, graph: &WorkflowGraph) -> Vec<String> {
+pub(crate) async fn validate_agent_refs(ctx: &DispatchCtx, config: &Config, graph: &WorkflowGraph) -> Vec<String> {
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
use crate::agent::registry::AgentRegistryEntry;
use crate::flows::tinyflows::caps::{route_for_agent_ref, AgentRoute};
@@ -384,7 +385,7 @@ pub(crate) async fn validate_agent_refs(config: &Config, graph: &WorkflowGraph)
}
AgentRoute::RegistryFallback => {
if custom_registry.is_none() {
- custom_registry = Some(crate::agent::registry::list_agents(true).await);
+ custom_registry = Some(crate::agent::registry::list_agents(&ctx, true).await);
}
match custom_registry.as_ref().expect("just populated") {
Ok(entries) => match entries.iter().find(|entry| entry.id == agent_ref) {
diff --git a/crates/openhuman-core/src/flows/ops/discovery.rs b/crates/openhuman-core/src/flows/ops/discovery.rs
index 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/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rs
index 5c94dc082a..04d7f9c34b 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,
@@ -140,7 +141,7 @@ pub(super) async fn finalize_flow_stream(
// left non-terminal makes `threads_turn_state_get` report the turn as still
// running, so re-entering the thread paints a permanent "Thinking..."
// indicator under a reply that already landed.
- if let Ok(config) = crate::config::rpc::load_config_with_timeout().await {
+ if let Ok(config) = crate::config::rpc::load_config_with_timeout(&ctx).await {
let lifecycle = if result.is_ok() {
tinyagents_session::turn_state::TurnLifecycle::Completed
} else {
diff --git a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
index 9bb5bb004e..6b8ef138e4 100644
--- a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
// ── validate_agent_refs (agent-ref resolvability gate, PR #5114) ───────────
@@ -17,7 +18,7 @@ async fn agent_ref_plain_node_without_ref_is_accepted() {
],
"edges": [ { "from_node": "t", "to_node": "a" } ]
}));
- let errors = validate_agent_refs(&config, &g).await;
+ let errors = validate_agent_refs(&DispatchCtx::process_default(), &config, &g).await;
assert!(errors.is_empty(), "{errors:?}");
}
@@ -35,7 +36,7 @@ async fn agent_ref_blank_string_is_treated_as_absent() {
],
"edges": [ { "from_node": "t", "to_node": "a" } ]
}));
- let errors = validate_agent_refs(&config, &g).await;
+ let errors = validate_agent_refs(&DispatchCtx::process_default(), &config, &g).await;
assert!(errors.is_empty(), "{errors:?}");
}
@@ -61,7 +62,7 @@ async fn agent_ref_resolving_to_a_harness_definition_is_accepted() {
],
"edges": [ { "from_node": "t", "to_node": "a" } ]
}));
- let errors = validate_agent_refs(&config, &g).await;
+ let errors = validate_agent_refs(&DispatchCtx::process_default(), &config, &g).await;
assert!(
errors.is_empty(),
"a real harness agent_ref must never be rejected: {errors:?}"
@@ -86,7 +87,7 @@ async fn agent_ref_unknown_is_rejected() {
],
"edges": [ { "from_node": "t", "to_node": "a" } ]
}));
- let errors = validate_agent_refs(&config, &g).await;
+ let errors = validate_agent_refs(&DispatchCtx::process_default(), &config, &g).await;
assert!(!errors.is_empty(), "an unknown agent_ref must be rejected");
assert!(
errors.iter().any(|e| e.contains("no_such_agent_xyz")),
diff --git a/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs b/crates/openhuman-core/src/flows/ops_builder_repair_tests.rs
index 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.rs
index c10faae4ff..23550d5f22 100644
--- a/crates/openhuman-core/src/flows/schemas_handlers.rs
+++ b/crates/openhuman-core/src/flows/schemas_handlers.rs
@@ -1,7 +1,7 @@
use crate::core::runtime::DispatchCtx;
-fn handle_create(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_create(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let name = read_required::<String>(&params, "name")?;
let graph = read_required::<Value>(&params, "graph")?;
let require_approval = params
@@ -44,39 +44,39 @@ fn handle_import(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_duplicate(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_duplicate(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_duplicate(&config, id.trim()).await?)
})
}
-fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_get(&config, id.trim()).await?)
})
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::flows_list(&config).await?)
})
}
-fn handle_list_connections(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_connections(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::flows_list_connections(&config).await?)
})
}
-fn handle_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let name = params
.get("name")
@@ -116,17 +116,17 @@ fn handle_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_delete(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_delete(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_delete(&config, id.trim()).await?)
})
}
-fn handle_set_enabled(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_set_enabled(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let enabled = params
.get("enabled")
@@ -136,9 +136,9 @@ fn handle_set_enabled(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll
})
}
-fn handle_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let input = params.get("input").cloned().unwrap_or(Value::Null);
let inputs = read_declared_inputs(&params)?;
@@ -155,9 +155,9 @@ fn handle_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
})
}
-fn handle_run_detached(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_run_detached(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let input = params.get("input").cloned().unwrap_or(Value::Null);
let inputs = read_declared_inputs(&params)?;
@@ -198,9 +198,9 @@ fn read_declared_inputs(params: &Map<String, Value>) -> Result<Map<String, Value
}
}
-fn handle_resume(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_resume(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let thread_id = read_required::<String>(&params, "thread_id")?;
let approvals: Vec<String> = params
@@ -225,17 +225,17 @@ fn handle_resume(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_cancel_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_cancel_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let run_id = read_required::<String>(&params, "run_id")?;
to_json(ops::flows_cancel_run(&config, run_id.trim()).await?)
})
}
-fn handle_list_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_runs(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let limit = params
.get("limit")
@@ -246,9 +246,9 @@ fn handle_list_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> Controller
})
}
-fn handle_list_all_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_all_runs(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let limit = params
.get("limit")
.and_then(Value::as_u64)
@@ -258,25 +258,25 @@ fn handle_list_all_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> Contro
})
}
-fn handle_get_run(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_run(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let run_id = read_required::<String>(&params, "run_id")?;
to_json(ops::flows_get_run(&config, run_id.trim()).await?)
})
}
-fn handle_prune_runs(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_prune_runs(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_prune_runs(&config, id.trim()).await?)
})
}
-fn handle_build(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_build(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// Optional streaming target: when the copilot passes its chat `thread_id`
// the builder turn streams live text/tool/proposal events into that
// thread (Phase B). Read + strip the transport-only keys before the rest
@@ -288,7 +288,7 @@ fn handle_build(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
let 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?)
})
}
@@ -303,13 +303,13 @@ fn handle_build_cancel(_ctx: DispatchCtx, params: Map<String, Value>) -> Control
})
}
-fn handle_discover(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_discover(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// 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(&params);
- to_json(ops::flows_discover(&config, stream).await?)
+ to_json(ops::flows_discover(&ctx, &config, stream).await?)
})
}
@@ -329,9 +329,9 @@ fn read_flow_stream_target(params: &Map<String, Value>) -> Option<ops::FlowStrea
ops::FlowStreamTarget::from_params(thread_id, request_id)
}
-fn handle_list_suggestions(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_suggestions(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let status = params
.get("status")
.and_then(Value::as_str)
@@ -342,33 +342,33 @@ fn handle_list_suggestions(_ctx: DispatchCtx, params: Map<String, Value>) -> Con
})
}
-fn handle_dismiss_suggestion(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_dismiss_suggestion(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_dismiss_suggestion(&config, id.trim()).await?)
})
}
-fn handle_mark_suggestion_built(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_mark_suggestion_built(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_mark_suggestion_built(&config, id.trim()).await?)
})
}
-fn handle_required_connections(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_required_connections(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let graph = read_required::<Value>(&params, "graph")?;
to_json(ops::flows_required_connections(&config, graph).await?)
})
}
-fn handle_approval_manifest(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_approval_manifest(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = params
.get("id")
.and_then(Value::as_str)
@@ -379,9 +379,9 @@ fn handle_approval_manifest(_ctx: DispatchCtx, params: Map<String, Value>) -> Co
})
}
-fn handle_search_tool_catalog(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_search_tool_catalog(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let query = read_required::<String>(&params, "query")?;
let toolkit = params
.get("toolkit")
@@ -396,17 +396,17 @@ fn handle_search_tool_catalog(_ctx: DispatchCtx, params: Map<String, Value>) ->
})
}
-fn handle_get_tool_contract(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_tool_contract(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let slug = read_required::<String>(&params, "slug")?;
to_json(ops::flows_get_tool_contract(&config, slug.trim()).await?)
})
}
-fn handle_get_history(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_history(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let limit = params
.get("limit")
@@ -417,9 +417,9 @@ fn handle_get_history(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll
})
}
-fn handle_rollback(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_rollback(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let revision_id = read_required::<String>(&params, "revision_id")?;
let expected_version = params
@@ -433,9 +433,9 @@ fn handle_rollback(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerF
})
}
-fn handle_draft_create(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_create(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let name = read_required::<String>(&params, "name")?;
let graph = read_required::<Value>(&params, "graph")?;
let flow_id = params
@@ -454,17 +454,17 @@ fn handle_draft_create(_ctx: DispatchCtx, params: Map<String, Value>) -> Control
})
}
-fn handle_draft_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_draft_get(&config, id.trim())?)
})
}
-fn handle_draft_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let name = params
.get("name")
@@ -485,24 +485,24 @@ fn handle_draft_update(_ctx: DispatchCtx, params: Map<String, Value>) -> Control
})
}
-fn handle_draft_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::flows_draft_list(&config)?)
})
}
-fn handle_draft_delete(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_delete(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::flows_draft_delete(&config, id.trim())?)
})
}
-fn handle_draft_promote(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_draft_promote(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let require_approval = params.get("require_approval").and_then(Value::as_bool);
to_json(ops::flows_draft_promote(&config, id.trim(), require_approval).await?)
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
index f988b1fc3e..14a60a58fe 100644
--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
@@ -8,6 +8,7 @@
#![allow(unused_imports)]
+use crate::core::runtime::DispatchCtx;
use std::borrow::Cow;
use std::sync::Arc;
@@ -266,7 +267,7 @@ impl AgentRunner for OpenHumanAgentRunner {
"[flows] agent_runner: FALLBACK path — persona-shaping single \
completion for a custom registry entry"
);
- self.run_via_registry_fallback(agent_ref, request, conn)
+ self.run_via_registry_fallback(&DispatchCtx::ambient(), agent_ref, request, conn)
.await
}
}
@@ -321,7 +322,7 @@ impl OpenHumanAgentRunner {
/// nodes (the tinyflows engine already fans those out) instead of
/// reaching for a background sub-agent from inside a single node.
async fn run_via_harness(
- &self,
+ &self, ctx: &DispatchCtx,
agent_ref: &str,
request: Value,
conn: Option<&str>,
@@ -452,10 +453,10 @@ impl OpenHumanAgentRunner {
> = if let Some(escalated) = escalated_origin {
Box::pin(turn_origin::with_origin(
escalated,
- agent.run_single_with_approval(&prompt, None, self.approval.clone()),
+ agent.run_single_with_approval(&ctx, &prompt, None, self.approval.clone()),
))
} else {
- Box::pin(agent.run_single_with_approval(&prompt, None, self.approval.clone()))
+ Box::pin(agent.run_single_with_approval(&ctx, &prompt, None, self.approval.clone()))
};
// A host agent's turn reads its own context (config, domains, tool
// groups, session store); the origin task-local is untouched.
@@ -503,13 +504,13 @@ impl OpenHumanAgentRunner {
/// with no harness definition — the pre-Phase-A behavior, kept so custom
/// agents don't regress.
async fn run_via_registry_fallback(
- &self,
+ &self, ctx: &DispatchCtx,
agent_ref: &str,
request: Value,
conn: Option<&str>,
) -> Result<Value> {
// Resolve + validate the requested agent kind against the registry.
- let entry = crate::agent::registry::get_agent(agent_ref)
+ let entry = crate::agent::registry::get_agent(&ctx, agent_ref)
.await
.map_err(EngineError::Capability)?
.ok_or_else(|| {
diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs
index 2fc1a4bed0..f680b4c50b 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;
@@ -143,6 +144,7 @@ impl CodeRunner for OpenHumanCode {
);
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.rs
index 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(&current, project_dir.as_deref(), workspace_dir.as_deref())
diff --git a/crates/openhuman-core/src/hooks/prompt_eval.rs b/crates/openhuman-core/src/hooks/prompt_eval.rs
index 85a26b801c..710ce913f7 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,8 +19,8 @@ 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> {
- let mut config = crate::config::rpc::load_config_with_timeout()
+pub async fn evaluate(ctx: &DispatchCtx, instruction: &str, model: Option<&str>) -> Result<String, String> {
+ let mut config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("loading config for prompt hook: {error}"))?;
if let Some(model) = model {
diff --git a/crates/openhuman-core/src/hooks/schemas.rs b/crates/openhuman-core/src/hooks/schemas.rs
index 5ee5f25712..5c8f7d2b97 100644
--- a/crates/openhuman-core/src/hooks/schemas.rs
+++ b/crates/openhuman-core/src/hooks/schemas.rs
@@ -109,9 +109,9 @@ fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFutu
Box::pin(async move { Ok(describe(super::host::engine().snapshot().await.as_ref())) })
}
-fn handle_reload(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_reload(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
super::ops::init(&config).await;
Ok(describe(super::host::engine().snapshot().await.as_ref()))
})
diff --git a/crates/openhuman-core/src/hooks/shell.rs b/crates/openhuman-core/src/hooks/shell.rs
index 60c84d63ef..01186a7279 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,10 +27,10 @@ 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 crate::config::ops::load_config_with_timeout().await {
+ let config = match crate::config::ops::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(error) => {
log::warn!("[hooks] cannot read config to select the hook shell: {error}");
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 62c36ae8de..496cf5f361 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>,
@@ -202,7 +203,7 @@ pub async fn update_settings(
use crate::config::ops as config_rpc;
use tinyinference_embeddings::format_embedding_signature;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
// Upgrade-in-place for users whose endpoint predates the retained Custom
// profile: if they disable or switch away now, capture the active profile
diff --git a/crates/openhuman-core/src/inference/embedding_host/schemas.rs b/crates/openhuman-core/src/inference/embedding_host/schemas.rs
index bdb17dd4b7..d5cce12ce6 100644
--- a/crates/openhuman-core/src/inference/embedding_host/schemas.rs
+++ b/crates/openhuman-core/src/inference/embedding_host/schemas.rs
@@ -171,9 +171,9 @@ struct TestConnectionParams {
// ── Handlers ───────────────────────────────────────────────
-fn handle_get_settings(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_settings(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::rpc::get_settings(&config).await?)
})
}
@@ -194,34 +194,34 @@ fn handle_update_settings(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_set_api_key(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_set_api_key(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<SetApiKeyParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::rpc::set_api_key(&config, &p.provider, &p.api_key).await?)
})
}
-fn handle_clear_api_key(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_clear_api_key(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<ClearApiKeyParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::rpc::clear_api_key(&config, &p.provider).await?)
})
}
-fn handle_embed(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_embed(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<EmbedParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(super::rpc::embed(&config, &p.inputs).await?)
})
}
-fn handle_test_connection(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_test_connection(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<TestConnectionParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
super::rpc::test_connection(
&config,
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index 127ff43ea6..fed4504755 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@ -1,5 +1,6 @@
//! Agent chat turns: the full tool-using turn and the simple no-tools variant.
+use crate::core::runtime::DispatchCtx;
use crate::agent::OpenHumanSessionHost;
use crate::config::Config;
use crate::core::Outcome;
@@ -366,7 +367,7 @@ async fn agent_chat_for_inner(
/// [`agent_chat_for`], keeping whether the turn stopped at its iteration cap.
/// The `inference.agent_chat` controller answers from this.
#[allow(clippy::too_many_arguments)]
-pub async fn agent_chat_reply_for(
+pub async fn agent_chat_reply_for(ctx: &DispatchCtx,
config: &mut Config,
target: AgentChatTarget<'_>,
message: &str,
@@ -517,7 +518,7 @@ pub async fn agent_chat_reply_for(
{
agent.clear_history();
agent
- .seed_resume_from_messages(seed.to_vec(), message)
+ .seed_resume_from_messages(&ctx, seed.to_vec(), message)
.map_err(|e| e.to_string())?;
agent.set_next_turn_overrides(crate::agent::session_host::TurnOverrides {
suppress_transcript_autoload: true,
@@ -569,7 +570,7 @@ pub async fn agent_chat_reply_for(
// instead of the narrower one it asked for.
let run = crate::agent::turn_origin::with_origin(
effective_agent_chat_origin(),
- agent.run_single_with_approval(message, None, approval),
+ agent.run_single_with_approval(&ctx, message, None, approval),
);
// `untrusted_input` was set on the session above; the turn's run context
// carries it to the security gate, so no extra scope is needed here.
diff --git a/crates/openhuman-core/src/inference/host_runtime/schemas.rs b/crates/openhuman-core/src/inference/host_runtime/schemas.rs
index 32e88edd21..78a065e26e 100644
--- a/crates/openhuman-core/src/inference/host_runtime/schemas.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/schemas.rs
@@ -223,10 +223,10 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_agent_chat(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_agent_chat(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<AgentChatParams>(params)?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
let target = match p.agent_id.as_deref().map(str::trim) {
Some(id) if !id.is_empty() => {
crate::inference::host_runtime::ops::AgentChatTarget::AgentId(id)
@@ -250,10 +250,10 @@ fn handle_agent_chat(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_agent_chat_simple(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_agent_chat_simple(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<AgentChatParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::ops::agent_chat_simple(
&config,
@@ -267,10 +267,10 @@ fn handle_agent_chat_simple(_ctx: DispatchCtx, params: Map<String, Value>) -> Co
})
}
-fn handle_local_ai_transcribe(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_local_ai_transcribe(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<LocalAiTranscribeParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::ops::local_ai_transcribe(&config, p.audio_path.trim())
.await?,
@@ -279,12 +279,12 @@ fn handle_local_ai_transcribe(_ctx: DispatchCtx, params: Map<String, Value>) ->
}
fn handle_local_ai_transcribe_bytes(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<LocalAiTranscribeBytesParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::ops::local_ai_transcribe_bytes(
&config,
@@ -296,10 +296,10 @@ fn handle_local_ai_transcribe_bytes(
})
}
-fn handle_local_ai_tts(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_local_ai_tts(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<LocalAiTtsParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::host_runtime::ops::local_ai_tts(
&config,
diff --git a/crates/openhuman-core/src/inference/ops.rs b/crates/openhuman-core/src/inference/ops.rs
index 9c89ef69c0..46ade64874 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;
@@ -250,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"),
@@ -260,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"),
@@ -272,18 +273,18 @@ 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");
- 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");
// The endpoint, provider or models may have changed: drop the
// cached probe verdict so the next status poll re-probes the
// user's runtime instead of reporting the old endpoint's state.
- match config_rpc::load_config_with_timeout().await {
+ match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => {
let runtime = crate::inference::local_runtime_config(&config);
local_runtime::global(&config).reset_to_idle(&runtime);
diff --git a/crates/openhuman-core/src/inference/ops_tests.rs b/crates/openhuman-core/src/inference/ops_tests.rs
index 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/claude_code_handlers.rs b/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
index 58e5bcf1f3..329a403ad5 100644
--- a/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
+++ b/crates/openhuman-core/src/inference/schemas/claude_code_handlers.rs
@@ -46,12 +46,12 @@ pub(super) fn handle_inference_claude_code_auth_status(
}
pub(super) fn handle_inference_claude_code_settings(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
use tinyagents_harness::providers::claude_code::settings;
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let workspace = config.config_path.parent().unwrap_or(&config.workspace_dir);
let settings = settings::load(workspace);
log::debug!(
@@ -63,13 +63,13 @@ pub(super) fn handle_inference_claude_code_settings(
}
pub(super) fn handle_inference_claude_code_set_full_access(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
use tinyagents_harness::providers::claude_code::settings;
Box::pin(async move {
let p = deserialize_params::<InferenceClaudeCodeSetFullAccessParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let workspace = config.config_path.parent().unwrap_or(&config.workspace_dir);
let settings = settings::ClaudeCodeSettings {
full_access: p.enabled,
diff --git a/crates/openhuman-core/src/inference/schemas/oauth_handlers.rs b/crates/openhuman-core/src/inference/schemas/oauth_handlers.rs
index fbe2ae16d6..0235df1d76 100644
--- a/crates/openhuman-core/src/inference/schemas/oauth_handlers.rs
+++ b/crates/openhuman-core/src/inference/schemas/oauth_handlers.rs
@@ -16,21 +16,21 @@ pub(super) struct InferenceOpenAiOAuthCompleteParams {
}
pub(super) fn handle_inference_openai_oauth_start(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_openai_oauth_start(&config).await?)
})
}
pub(super) fn handle_inference_openai_oauth_complete(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload = deserialize_params::<InferenceOpenAiOAuthCompleteParams>(params)?;
to_json(
crate::inference::rpc::inference_openai_oauth_complete(
@@ -43,31 +43,31 @@ pub(super) fn handle_inference_openai_oauth_complete(
}
pub(super) fn handle_inference_openai_oauth_import_codex_cli(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_openai_oauth_import_codex_cli(&config).await?)
})
}
pub(super) fn handle_inference_openai_oauth_status(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_openai_oauth_status(&config).await?)
})
}
pub(super) fn handle_inference_openai_oauth_disconnect(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_openai_oauth_disconnect(&config).await?)
})
}
diff --git a/crates/openhuman-core/src/inference/schemas/prompt_handlers.rs b/crates/openhuman-core/src/inference/schemas/prompt_handlers.rs
index cf079b7b8d..bd610d96f3 100644
--- a/crates/openhuman-core/src/inference/schemas/prompt_handlers.rs
+++ b/crates/openhuman-core/src/inference/schemas/prompt_handlers.rs
@@ -42,23 +42,23 @@ pub(super) struct InferenceAnalyzeSentimentParams {
}
pub(super) fn handle_inference_summarize(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferenceSummarizeParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_summarize(&config, &p.text, p.max_tokens).await?)
})
}
pub(super) fn handle_inference_prompt(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferencePromptParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::rpc::inference_prompt(&config, &p.prompt, p.max_tokens, p.no_think)
.await?,
@@ -67,12 +67,12 @@ pub(super) fn handle_inference_prompt(
}
pub(super) fn handle_inference_vision_prompt(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferenceVisionPromptParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::rpc::inference_vision_prompt(
&config,
@@ -86,12 +86,12 @@ pub(super) fn handle_inference_vision_prompt(
}
pub(super) fn handle_inference_test_provider_model(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferenceTestChatModelParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::inference::rpc::inference_test_provider_model(
&config,
@@ -105,12 +105,12 @@ pub(super) fn handle_inference_test_provider_model(
}
pub(super) fn handle_inference_analyze_sentiment(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferenceAnalyzeSentimentParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_analyze_sentiment(&config, &p.message).await?)
})
}
diff --git a/crates/openhuman-core/src/inference/schemas/settings_handlers.rs b/crates/openhuman-core/src/inference/schemas/settings_handlers.rs
index 39f89e475a..f5884817e4 100644
--- a/crates/openhuman-core/src/inference/schemas/settings_handlers.rs
+++ b/crates/openhuman-core/src/inference/schemas/settings_handlers.rs
@@ -82,12 +82,12 @@ pub(super) struct InferenceListModelsParams {
}
pub(super) fn handle_inference_resolve_model(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<InferenceResolveModelParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let resolved =
crate::inference::provider::factory::resolve_model_for_hint(&p.hint, &config);
// Whether the resolved model accepts image input — drives the chat UI's
@@ -105,24 +105,24 @@ pub(super) fn handle_inference_resolve_model(
}
pub(super) fn handle_inference_status(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_status(&config).await?)
})
}
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?)
})
}
@@ -303,11 +303,11 @@ pub(super) fn handle_inference_provider_auth_errors(
}
pub(super) fn handle_inference_diagnostics(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::inference::rpc::inference_diagnostics(&config).await?)
})
}
diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rs
index b8f8783e05..0285f5e168 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,10 +440,10 @@ 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 = crate::config::ops::load_config_with_timeout().await?;
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
query_for_config(&config, request).await
}
@@ -458,8 +459,8 @@ 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> {
- let config = crate::config::ops::load_config_with_timeout().await?;
+pub async fn extract_html(ctx: &DispatchCtx, html: String) -> Result<String, String> {
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
let response: tinyjuice_bus::wire::HtmlResponse = client(&config)
.call("tinyjuice", methods::EXTRACT_HTML, (html,))
.await
diff --git a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs
index 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/inference/tokenjuice/schemas.rs b/crates/openhuman-core/src/inference/tokenjuice/schemas.rs
index 041a25d60f..3914d820cf 100644
--- a/crates/openhuman-core/src/inference/tokenjuice/schemas.rs
+++ b/crates/openhuman-core/src/inference/tokenjuice/schemas.rs
@@ -369,10 +369,10 @@ fn handle_retrieve(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerF
})
}
-fn handle_settings_get(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_settings_get(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("load config: {e}"))?;
let settings = serde_json::to_value(&config.tokenjuice)
@@ -381,7 +381,7 @@ fn handle_settings_get(_ctx: DispatchCtx, _params: Map<String, Value>) -> Contro
})
}
-fn handle_settings_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_settings_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
// Accept either {"patch": {...}} or a bare object of fields.
@@ -392,7 +392,7 @@ fn handle_settings_update(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
let patch: super::config_patch::TokenjuiceSettingsPatch =
serde_json::from_value(patch).map_err(|e| format!("invalid patch: {e}"))?;
- let mut config = crate::config::rpc::load_config_with_timeout()
+ let mut config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("load config: {e}"))?;
patch.apply(&mut config.tokenjuice);
@@ -410,11 +410,11 @@ fn handle_settings_update(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
})
}
-fn handle_savings_stats(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_savings_stats(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
let cache = super::cache_stats().await?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| e.to_string())?;
super::install_from_config(&config).await?;
@@ -429,10 +429,10 @@ fn handle_savings_stats(_ctx: DispatchCtx, _params: Map<String, Value>) -> Contr
})
}
-fn handle_savings_reset(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_savings_reset(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| e.to_string())?;
super::install_from_config(&config).await?;
diff --git a/crates/openhuman-core/src/integrations/composio/action_tool.rs b/crates/openhuman-core/src/integrations/composio/action_tool.rs
index 5f33a080b2..6f95268a03 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,10 +163,10 @@ 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 => config_rpc::load_config_with_timeout().await,
+ None => config_rpc::load_config_with_timeout(&ctx).await,
}
}
}
@@ -239,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(
@@ -249,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)
}
}
@@ -260,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>) {
@@ -308,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.rs
index 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/config_changed_subscriber.rs b/crates/openhuman-core/src/integrations/composio/bus/config_changed_subscriber.rs
index 08edfd670e..22aeef3acb 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 config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&DispatchCtx::ambient()).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 acd4fb3c40..426dddcf67 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,8 +94,8 @@ impl EventHandler<DomainEvent> for ComposioConnectionCreatedSubscriber {
}
}
-async fn on_connection_created(toolkit: String, connection_id: String) {
- let config = match config_rpc::load_config_with_timeout().await {
+async fn on_connection_created(ctx: &DispatchCtx, toolkit: String, connection_id: String) {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(c) => c,
Err(e) => {
tracing::warn!(
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 654a82c126..8bb8e174e5 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) = config_rpc::load_config_with_timeout().await {
+ if let Ok(config) = config_rpc::load_config_with_timeout(&DispatchCtx::ambient()).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 config_rpc::load_config_with_timeout().await {
+ match config_rpc::load_config_with_timeout(&DispatchCtx::ambient()).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 config_rpc::load_config_with_timeout().await {
+ match config_rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => {
if config.composio.triage_disabled {
tracing::debug!(
@@ -183,7 +184,7 @@ impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
// Spawn so the bus dispatch loop stays non-blocking — the
// triage turn is an LLM round-trip that may take seconds.
tokio::spawn(async move {
- match run_triage(&envelope).await {
+ match run_triage(&DispatchCtx::ambient(), &envelope).await {
Ok(TriageOutcome::Decision(run)) => {
// Remote payload: a Composio trigger body is
// attacker-influenceable, so the dispatch parks rather than
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 88d75a02f2..b1f0e8d661 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,
@@ -92,7 +93,7 @@ pub async fn composio_set_api_key(
.map_err(|e| format!("[composio-direct] store_composio_api_key failed: {e}"))?;
let mode_log = if activate_direct {
- let mut cfg_mut = crate::config::rpc::load_config_with_timeout()
+ let mut cfg_mut = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("[composio-direct] reload config failed: {e}"))?;
cfg_mut.composio.mode = crate::config::schema::COMPOSIO_MODE_DIRECT.into();
@@ -131,13 +132,13 @@ 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
.map_err(|e| format!("[composio-direct] clear_composio_api_key failed: {e}"))?;
- let mut cfg_mut = crate::config::rpc::load_config_with_timeout()
+ let mut cfg_mut = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("[composio-direct] reload config failed: {e}"))?;
cfg_mut.composio.mode = crate::config::schema::COMPOSIO_MODE_BACKEND.into();
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.rs
index 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.rs
index e68c2ea695..36efcf927a 100644
--- a/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs
+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs
@@ -13,48 +13,48 @@ use crate::integrations::composio::ops;
use super::util::{read_optional, read_required_non_empty, to_json};
pub(super) fn handle_list_toolkits(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_list_toolkits(&config).await?)
})
}
pub(super) fn handle_list_capabilities(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_list_capabilities(&config).await?)
})
}
pub(super) fn handle_list_agent_ready_toolkits(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_list_agent_ready_toolkits(&config).await?)
})
}
pub(super) fn handle_list_connections(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_list_connections(&config).await?)
})
}
-pub(super) fn handle_authorize(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_authorize(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let toolkit = read_required_non_empty(&params, "toolkit")?;
let extra_params = params.get("extra_params").cloned();
to_json(ops::composio_authorize(&config, &toolkit, extra_params).await?)
@@ -62,44 +62,44 @@ pub(super) fn handle_authorize(_ctx: DispatchCtx, params: Map<String, Value>) ->
}
pub(super) fn handle_delete_connection(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let connection_id = read_required_non_empty(&params, "connection_id")?;
to_json(ops::composio_delete_connection(&config, &connection_id).await?)
})
}
-pub(super) fn handle_get_mode(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_get_mode(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
tracing::debug!("[composio-direct] rpc get_mode entry");
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_get_mode(&config).await?)
})
}
pub(super) fn handle_set_api_key(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
tracing::debug!("[composio-direct] rpc set_api_key entry");
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let api_key = read_required_non_empty(&params, "api_key")?;
let activate_direct = read_optional::<bool>(&params, "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?)
})
}
pub(super) fn handle_clear_api_key(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
tracing::debug!("[composio-direct] rpc clear_api_key entry");
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::composio_clear_api_key(&config).await?)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ to_json(ops::composio_clear_api_key(&ctx, &config).await?)
})
}
diff --git a/crates/openhuman-core/src/integrations/composio/schemas/handlers_identity.rs b/crates/openhuman-core/src/integrations/composio/schemas/handlers_identity.rs
index 1c9cbfcfa9..7f5f4a5c2d 100644
--- a/crates/openhuman-core/src/integrations/composio/schemas/handlers_identity.rs
+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_identity.rs
@@ -12,28 +12,28 @@ use crate::integrations::composio::{contract, ops};
use super::util::{read_required, read_required_non_empty, to_json};
pub(super) fn handle_get_user_profile(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let connection_id = read_required_non_empty(&params, "connection_id")?;
to_json(ops::composio_get_user_profile(&config, &connection_id).await?)
})
}
pub(super) fn handle_refresh_all_identities(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::composio_refresh_all_identities(&config).await?)
})
}
pub(super) fn handle_get_user_scopes(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
@@ -63,7 +63,7 @@ pub(super) fn handle_get_user_scopes(
// never had a failing path, and turning "settings file momentarily
// unreadable" into an RPC error would make the scopes panel fail where
// it used to render the defaults.
- let pref = match config_rpc::load_config_with_timeout().await {
+ let pref = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => ops::load_user_scope_pref(&config, &toolkit).await,
Err(error) => {
tracing::warn!(
@@ -88,7 +88,7 @@ pub(super) fn handle_get_user_scopes(
}
pub(super) fn handle_set_user_scopes(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
@@ -120,7 +120,7 @@ pub(super) fn handle_set_user_scopes(
// client not initialised" rather than reporting a save it had not
// done, and `ops::user_scopes::save` refuses on the same three
// grounds (no driver, no `Graph` family, backend write failure).
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
if let Err(e) = ops::save_user_scope_pref(&config, &toolkit, pref).await {
tracing::error!(
method = "composio.set_user_scopes",
diff --git a/crates/openhuman-core/src/integrations/composio/schemas/handlers_tools.rs b/crates/openhuman-core/src/integrations/composio/schemas/handlers_tools.rs
index 5f2e2d3eb7..92041960bb 100644
--- a/crates/openhuman-core/src/integrations/composio/schemas/handlers_tools.rs
+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_tools.rs
@@ -9,18 +9,18 @@ use crate::integrations::composio::ops;
use super::util::{read_optional, read_required_non_empty, to_json};
-pub(super) fn handle_list_tools(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_list_tools(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let toolkits = read_optional::<Vec<String>>(&params, "toolkits")?;
let tags = read_optional::<Vec<String>>(&params, "tags")?;
to_json(ops::composio_list_tools(&config, toolkits, tags).await?)
})
}
-pub(super) fn handle_execute(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_execute(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let tool = read_required_non_empty(&params, "tool")?;
let arguments = read_optional::<Value>(&params, "arguments")?;
let connection_id = read_optional::<String>(&params, "connection_id")?;
diff --git a/crates/openhuman-core/src/integrations/composio/schemas/handlers_triggers.rs b/crates/openhuman-core/src/integrations/composio/schemas/handlers_triggers.rs
index 4eab5e2e87..da7c3d99b2 100644
--- a/crates/openhuman-core/src/integrations/composio/schemas/handlers_triggers.rs
+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_triggers.rs
@@ -16,11 +16,11 @@ use super::params::{
use super::util::{read_required_non_empty, to_json};
pub(super) fn handle_list_github_repos(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: ListGithubReposParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
to_json(ops::composio_list_github_repos(&config, payload.connection_id).await?)
@@ -28,11 +28,11 @@ pub(super) fn handle_list_github_repos(
}
pub(super) fn handle_create_trigger(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: CreateTriggerParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
let slug = payload.slug.trim();
@@ -52,11 +52,11 @@ pub(super) fn handle_create_trigger(
}
pub(super) fn handle_list_trigger_history(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: TriggerHistoryParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
to_json(ops::composio_list_trigger_history(&config, payload.limit).await?)
@@ -64,11 +64,11 @@ pub(super) fn handle_list_trigger_history(
}
pub(super) fn handle_list_available_triggers(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: ListAvailableTriggersParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
let toolkit = payload.toolkit.trim();
@@ -82,11 +82,11 @@ pub(super) fn handle_list_available_triggers(
}
pub(super) fn handle_list_triggers(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: ListTriggersParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
to_json(ops::composio_list_triggers(&config, payload.toolkit).await?)
@@ -94,11 +94,11 @@ pub(super) fn handle_list_triggers(
}
pub(super) fn handle_enable_trigger(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload: EnableTriggerParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
let connection_id = payload.connection_id.trim();
@@ -117,11 +117,11 @@ pub(super) fn handle_enable_trigger(
}
pub(super) fn handle_disable_trigger(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let trigger_id = read_required_non_empty(&params, "trigger_id")?;
to_json(ops::composio_disable_trigger(&config, &trigger_id).await?)
})
diff --git a/crates/openhuman-core/src/integrations/task_sources/bus.rs b/crates/openhuman-core/src/integrations/task_sources/bus.rs
index 3abffbf4fb..161dbd347a 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,8 +63,8 @@ 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) {
- let config = match config_rpc::load_config_with_timeout().await {
+async fn fire_in_scope(ctx: &DispatchCtx, provider: ProviderSlug, toolkit: &str, connection_id: &str) {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(e) => {
tracing::debug!(error = %e, "[task_sources:bus] load_config failed, skipping scope");
@@ -78,7 +79,7 @@ async fn fire_in_scope(provider: ProviderSlug, toolkit: &str, connection_id: &st
/// Starts a one-shot fetch for every enabled source of `provider` in the
/// current storage scope that the new connection serves.
-async fn fire_for_connection(
+async fn fire_for_connection(ctx: &DispatchCtx,
config: &crate::config::Config,
provider: ProviderSlug,
toolkit: &str,
@@ -115,7 +116,7 @@ async fn fire_for_connection(
// Scoped: the fetch keeps the scope's agent context.
crate::core::runtime::spawn_scoped(async move {
let _ =
- pipeline::run_source_once(&config, &source, FetchReason::ConnectionCreated).await;
+ pipeline::run_source_once(&ctx, &config, &source, FetchReason::ConnectionCreated).await;
});
}
}
diff --git a/crates/openhuman-core/src/integrations/task_sources/ops.rs b/crates/openhuman-core/src/integrations/task_sources/ops.rs
index 8097b069b5..2ba7753281 100644
--- a/crates/openhuman-core/src/integrations/task_sources/ops.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/ops.rs
@@ -5,6 +5,7 @@
//! `ControllerFuture` boundary. Business logic stays here; `schemas.rs`
//! only parses params and delegates.
+use crate::core::runtime::DispatchCtx;
use serde_json::{json, Value};
use crate::config::Config;
@@ -99,18 +100,18 @@ pub async fn remove(config: &Config, id: &str) -> Result<Outcome<Value>, String>
}
/// Manually fetch one source now (`FetchReason::Manual`).
-pub async fn fetch(config: &Config, id: &str) -> Result<Outcome<super::FetchOutcome>, String> {
+pub async fn fetch(ctx: &DispatchCtx, config: &Config, id: &str) -> Result<Outcome<super::FetchOutcome>, String> {
let source = store::get_source(config, id).map_err(|e| e.to_string())?;
- let outcome = pipeline::run_source_once(config, &source, FetchReason::Manual).await;
+ let outcome = pipeline::run_source_once(&ctx, config, &source, FetchReason::Manual).await;
Ok(Outcome::new(outcome, vec![]))
}
/// Manually sync all enabled task sources now.
-pub async fn sync(config: &Config) -> Result<Outcome<Vec<super::FetchOutcome>>, String> {
+pub async fn sync(ctx: &DispatchCtx, config: &Config) -> Result<Outcome<Vec<super::FetchOutcome>>, String> {
let sources = store::list_sources(config).map_err(|e| e.to_string())?;
let mut outcomes = Vec::new();
for source in sources.into_iter().filter(|source| source.enabled) {
- outcomes.push(pipeline::run_source_once(config, &source, FetchReason::Manual).await);
+ outcomes.push(pipeline::run_source_once(&ctx, config, &source, FetchReason::Manual).await);
}
tracing::info!(
source_count = outcomes.len(),
diff --git a/crates/openhuman-core/src/integrations/task_sources/periodic.rs b/crates/openhuman-core/src/integrations/task_sources/periodic.rs
index 734a02df1c..27b8871cff 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,8 +112,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout()
+pub(crate) async fn run_one_tick(ctx: &DispatchCtx, ) -> Result<(), String> {
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("load_config: {e}"))?;
@@ -160,7 +161,7 @@ pub(crate) async fn run_one_tick() -> Result<(), String> {
// Record the attempt up front so a slow/failing fetch doesn't
// re-fire every tick.
record_poll(&source.id);
- let outcome = pipeline::run_source_once(&config, &source, FetchReason::Periodic).await;
+ let outcome = pipeline::run_source_once(&ctx, &config, &source, FetchReason::Periodic).await;
fired += 1;
tracing::debug!(
source_id = %source.id,
diff --git a/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rs b/crates/openhuman-core/src/integrations/task_sources/periodic_tests.rs
index c2aad66e50..194df273de 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");
@@ -195,7 +196,7 @@ async fn manual_fetch_still_returns_the_explanatory_error() {
std::fs::create_dir_all(&config.workspace_dir).expect("workspace");
let s = source("ts-manual-path-xyz", 1800);
- let outcome = pipeline::run_source_once(&config, &s, FetchReason::Manual).await;
+ let outcome = pipeline::run_source_once(&DispatchCtx::process_default(), &config, &s, FetchReason::Manual).await;
let error = outcome
.error
diff --git a/crates/openhuman-core/src/integrations/task_sources/pipeline.rs b/crates/openhuman-core/src/integrations/task_sources/pipeline.rs
index f4d1514df1..180d0f1a04 100644
--- a/crates/openhuman-core/src/integrations/task_sources/pipeline.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/pipeline.rs
@@ -6,6 +6,7 @@
//! call boundary: any error is captured into [`FetchOutcome::error`] so
//! the scheduler loop never unwinds.
+use crate::core::runtime::DispatchCtx;
use chrono::Utc;
use std::collections::HashSet;
@@ -18,7 +19,7 @@ use super::{enrich, route, store};
/// Run a single fetch pass over `source`. Captures errors into the
/// returned [`FetchOutcome`] rather than propagating them.
-pub async fn run_source_once(
+pub async fn run_source_once(ctx: &DispatchCtx,
config: &Config,
source: &TaskSource,
reason: FetchReason,
@@ -36,7 +37,7 @@ pub async fn run_source_once(
"[task_sources:pipeline] fetch pass starting"
);
- match run_inner(config, source, reason, &mut outcome).await {
+ match run_inner(&ctx, config, source, reason, &mut outcome).await {
Ok(()) => {
let status = format!(
"fetched {} routed {} dupes {} pruned {}",
@@ -123,7 +124,7 @@ fn fetch_tasks_unavailable(
}
/// Fetch, process, and reconcile one source pass.
-async fn run_inner(
+async fn run_inner(ctx: &DispatchCtx,
config: &Config,
source: &TaskSource,
_reason: FetchReason,
@@ -184,7 +185,7 @@ async fn run_inner(
// Route first; only mark ingested on success so a routing
// failure retries on the next pass instead of being silently
// dropped.
- if let Err(e) = route::route_enriched(config, source, &enriched).await {
+ if let Err(e) = route::route_enriched(&ctx, config, source, &enriched).await {
tracing::warn!(
source_id = %source.id,
external_id = %enriched.task.external_id,
diff --git a/crates/openhuman-core/src/integrations/task_sources/pipeline_tests.rs b/crates/openhuman-core/src/integrations/task_sources/pipeline_tests.rs
index be4893ef79..dc3cef801a 100644
--- a/crates/openhuman-core/src/integrations/task_sources/pipeline_tests.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/pipeline_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use crate::config::Config;
use crate::integrations::task_sources::store;
@@ -61,7 +62,7 @@ async fn fetch_surfaces_error_for_every_toolkit() {
let config = test_config(&tmp);
let source = add_github_source(&config);
- let outcome = run_source_once(&config, &source, FetchReason::Manual).await;
+ let outcome = run_source_once(&DispatchCtx::process_default(), &config, &source, FetchReason::Manual).await;
assert!(outcome.error.is_some(), "fetch must refuse, not panic");
assert_eq!(outcome.fetched, 0);
assert_eq!(outcome.routed, 0);
@@ -78,8 +79,8 @@ async fn refusal_is_stable_across_repeated_passes() {
let config = test_config(&tmp);
let source = add_github_source(&config);
- let first = run_source_once(&config, &source, FetchReason::Manual).await;
- let second = run_source_once(&config, &source, FetchReason::Manual).await;
+ let first = run_source_once(&DispatchCtx::process_default(), &config, &source, FetchReason::Manual).await;
+ let second = run_source_once(&DispatchCtx::process_default(), &config, &source, FetchReason::Manual).await;
assert!(first.error.is_some());
assert!(second.error.is_some());
assert_eq!(second.routed, 0);
@@ -92,7 +93,7 @@ async fn refusal_records_a_fetch_history_entry() {
let config = test_config(&tmp);
let source = add_github_source(&config);
- let _ = run_source_once(&config, &source, FetchReason::Manual).await;
+ let _ = run_source_once(&DispatchCtx::process_default(), &config, &source, FetchReason::Manual).await;
// `run_source_once` records the failed pass so the UI can show why a
// source has never ingested anything, rather than looking silently idle.
@@ -165,7 +166,7 @@ async fn missing_provider_surfaces_error_in_outcome() {
)
.unwrap();
- let outcome = run_source_once(&config, &source, FetchReason::Manual).await;
+ let outcome = run_source_once(&DispatchCtx::process_default(), &config, &source, FetchReason::Manual).await;
assert!(outcome.error.is_some());
assert_eq!(outcome.routed, 0);
}
diff --git a/crates/openhuman-core/src/integrations/task_sources/route.rs b/crates/openhuman-core/src/integrations/task_sources/route.rs
index 8f023cfdbc..789a6c9db4 100644
--- a/crates/openhuman-core/src/integrations/task_sources/route.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/route.rs
@@ -14,6 +14,7 @@
//! well. That board was rendered nowhere and the `todo` tool is now the
//! session's own list, so the mirror is gone; the ledger is the surface.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use crate::agent::triage::{
@@ -27,7 +28,7 @@ use super::types::{EnrichedTask, SourceTarget, TaskSource};
/// Route an enriched task: for proactive sources dispatch a triage turn;
/// collect-only sources stop at the ledger the caller already wrote.
-pub async fn route_enriched(
+pub async fn route_enriched(ctx: &DispatchCtx,
_config: &Config,
source: &TaskSource,
enriched: &EnrichedTask,
@@ -41,14 +42,14 @@ pub async fn route_enriched(
);
Ok(())
}
- SourceTarget::AgentTodoProactive => dispatch_triage(source, enriched).await,
+ SourceTarget::AgentTodoProactive => dispatch_triage(&ctx, source, enriched).await,
}
}
/// Dispatch a triage turn for a proactive task, gated by scheduler
/// capacity. A gated-off or deferred turn is non-fatal — the task is already
/// in the ledger.
-async fn dispatch_triage(source: &TaskSource, enriched: &EnrichedTask) -> Result<(), String> {
+async fn dispatch_triage(ctx: &DispatchCtx, source: &TaskSource, enriched: &EnrichedTask) -> Result<(), String> {
// Respect background-AI throttling. When the gate denies capacity
// (Off / paused), we keep the card but skip the proactive turn.
let Some(_permit) = scheduler_gate::wait_for_capacity().await else {
@@ -76,7 +77,7 @@ async fn dispatch_triage(source: &TaskSource, enriched: &EnrichedTask) -> Result
payload,
);
- let outcome = run_triage(&envelope)
+ let outcome = run_triage(&ctx, &envelope)
.await
.map_err(|e| format!("[task_sources:route] triage evaluation failed: {e}"))?;
diff --git a/crates/openhuman-core/src/integrations/task_sources/route_tests.rs b/crates/openhuman-core/src/integrations/task_sources/route_tests.rs
index 8e8cd2ab80..ed504ec626 100644
--- a/crates/openhuman-core/src/integrations/task_sources/route_tests.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/route_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use crate::integrations::task_sources::types::{FilterSpec, ProviderSlug};
use crate::integrations::task_sources::NormalizedTask;
@@ -55,7 +56,7 @@ async fn collect_only_target_routes_without_side_effects() {
let config = Config::default();
let src = github_source(SourceTarget::TodoOnly);
- route_enriched(&config, &src, &enriched("123"))
+ route_enriched(&DispatchCtx::process_default(), &config, &src, &enriched("123"))
.await
.expect("collect-only routing is a no-op");
}
diff --git a/crates/openhuman-core/src/integrations/task_sources/schemas.rs b/crates/openhuman-core/src/integrations/task_sources/schemas.rs
index a8f439707d..ee23f8e4f8 100644
--- a/crates/openhuman-core/src/integrations/task_sources/schemas.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/schemas.rs
@@ -407,24 +407,24 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::list(&config).await?)
})
}
-fn handle_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::get(&config, id.trim()).await?)
})
}
-fn handle_add(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_add(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider = read_provider(&params)?;
let filter = read_required::<FilterSpec>(&params, "filter")?;
let name = read_optional::<String>(&params, "name")?;
@@ -448,41 +448,41 @@ fn handle_add(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture
})
}
-fn handle_update(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let patch = read_required::<TaskSourcePatch>(&params, "patch")?;
to_json(ops::update(&config, id.trim(), patch).await?)
})
}
-fn handle_remove(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
to_json(ops::remove(&config, id.trim()).await?)
})
}
-fn handle_fetch(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_fetch(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
- to_json(ops::fetch(&config, id.trim()).await?)
+ to_json(ops::fetch(&ctx, &config, id.trim()).await?)
})
}
-fn handle_sync(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_sync(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- to_json(ops::sync(&config).await?)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ to_json(ops::sync(&ctx, &config).await?)
})
}
-fn handle_list_tasks(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_tasks(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let id = read_required::<String>(&params, "id")?;
let limit = match read_optional::<u64>(&params, "limit")? {
Some(n) => Some(
@@ -495,9 +495,9 @@ fn handle_list_tasks(_ctx: DispatchCtx, params: Map<String, Value>) -> Controlle
})
}
-fn handle_preview_filter(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_preview_filter(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider = read_provider(&params)?;
let filter = read_required::<FilterSpec>(&params, "filter")?;
let connection_id = read_optional::<String>(&params, "connection_id")?;
@@ -506,18 +506,18 @@ fn handle_preview_filter(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
})
}
-fn handle_list_databases(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_databases(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider = read_provider(&params)?;
let connection_id = read_optional::<String>(&params, "connection_id")?;
to_json(ops::list_databases(&config, provider, connection_id).await?)
})
}
-fn handle_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(ops::status(&config).await?)
})
}
diff --git a/crates/openhuman-core/src/integrations/task_sources/tools.rs b/crates/openhuman-core/src/integrations/task_sources/tools.rs
index 3379097a80..fbd45fccf5 100644
--- a/crates/openhuman-core/src/integrations/task_sources/tools.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/tools.rs
@@ -11,6 +11,7 @@
//! mutators — `add`, `update`, `remove` — change ingestion behaviour and
//! cascade history, so they ship default-OFF via `tools/user_filter.rs`.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use async_trait::async_trait;
@@ -183,7 +184,7 @@ impl Tool for TaskSourceFetchTool {
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
log::debug!("[tool][task_sources] fetch invoked");
let id = read_required_str(&args, "id")?;
- emit!(ops::fetch(&self.config, &id).await, "task_source_fetch")
+ emit!(ops::fetch(&DispatchCtx::ambient(), &self.config, &id).await, "task_source_fetch")
}
}
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 682d2b6a38..8b48bea6b0 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -41,6 +41,7 @@
//! embedding builds use `--no-default-features --features "<list>"`. See the
//! `[features]` block in `Cargo.toml` for the full gate list and rationale.
+use crate::core::runtime::DispatchCtx;
// The RPC dispatch chokepoint wraps each handler future in an ambient
// `CoreContext` scope (Phase 2). Combined with the already very deep async type
// stacks in the axum routes that fan out into the tinyagents harness, the extra
@@ -112,7 +113,7 @@ pub use core::types::HostKind;
///
/// Returns an error if command execution fails.
pub fn run_core_from_args(args: &[String]) -> anyhow::Result<()> {
- run_core_from_args_with(args, None)
+ run_core_from_args_with(&ctx, args, None)
}
/// [`run_core_from_args`] with a host-supplied boot description.
@@ -125,7 +126,7 @@ pub fn run_core_from_args(args: &[String]) -> anyhow::Result<()> {
/// # Errors
///
/// Returns an error if command execution fails.
-pub fn run_core_from_args_with(
+pub fn run_core_from_args_with(ctx: &DispatchCtx,
args: &[String],
host_boot: Option<core::server_launcher::HostBoot>,
) -> anyhow::Result<()> {
@@ -138,5 +139,5 @@ pub fn run_core_from_args_with(
{
security::secret_storage::init_master_key().map_err(anyhow::Error::msg)?;
}
- core::cli::run_from_cli_args_with(args, host_boot)
+ core::cli::run_from_cli_args_with(&ctx, args, host_boot)
}
diff --git a/crates/openhuman-core/src/mcp/audit/schemas.rs b/crates/openhuman-core/src/mcp/audit/schemas.rs
index fa74e982eb..2f654605c8 100644
--- a/crates/openhuman-core/src/mcp/audit/schemas.rs
+++ b/crates/openhuman-core/src/mcp/audit/schemas.rs
@@ -81,11 +81,11 @@ fn schema() -> ControllerSchema {
}
}
-fn handle_list(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
log::debug!("[mcp_audit] handle_list enter params={params:?}");
log::trace!("[mcp_audit] handle_list loading config");
- let config = match config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => {
log::trace!(
"[mcp_audit] handle_list config loaded workspace={}",
diff --git a/crates/openhuman-core/src/mcp/audit/schemas_tests.rs b/crates/openhuman-core/src/mcp/audit/schemas_tests.rs
index 54ec78f892..6691d9392c 100644
--- a/crates/openhuman-core/src/mcp/audit/schemas_tests.rs
+++ b/crates/openhuman-core/src/mcp/audit/schemas_tests.rs
@@ -30,7 +30,7 @@ async fn handle_list_returns_persisted_audit_records() {
std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());
}
- let config = config_rpc::load_config_with_timeout()
+ let config = config_rpc::load_config_with_timeout(&DispatchCtx::process_default())
.await
.expect("config");
crate::mcp::audit::record_write(
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs b/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
index 52c565b017..8503a06c30 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
@@ -14,11 +14,11 @@ use super::params::{
// ── Handler implementations ──────────────────────────────────────────────────
pub(super) fn handle_registry_search(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let query = read_optional_string(&params, "query")?;
let transport = read_optional_string(&params, "transport")?;
let page = read_optional_u32(&params, "page")?;
@@ -33,88 +33,88 @@ pub(super) fn handle_registry_search(
}
pub(super) fn handle_registry_get(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let qualified_name = read_required::<String>(&params, "qualified_name")?;
to_json(crate::mcp::registry::ops::mcp_clients_registry_get(&config, qualified_name).await?)
})
}
pub(super) fn handle_installed_list(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let _ = params;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::mcp::registry::ops::mcp_clients_installed_list(&config).await?)
})
}
-pub(super) fn handle_update_env(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_update_env(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
let env = read_required::<std::collections::HashMap<String, String>>(&params, "env")?;
to_json(crate::mcp::registry::ops::mcp_clients_update_env(&config, server_id, env).await?)
})
}
-pub(super) fn handle_uninstall(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_uninstall(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(crate::mcp::registry::ops::mcp_clients_uninstall(&config, server_id).await?)
})
}
pub(super) fn handle_detect_auth(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(crate::mcp::registry::ops::mcp_clients_detect_auth(&config, server_id).await?)
})
}
pub(super) fn handle_oauth_begin(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(crate::mcp::registry::ops::mcp_clients_oauth_begin(&config, server_id).await?)
})
}
-pub(super) fn handle_connect(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_connect(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(crate::mcp::registry::ops::mcp_clients_connect(&config, server_id).await?)
})
}
-pub(super) fn handle_disconnect(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_disconnect(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(crate::mcp::registry::ops::mcp_clients_disconnect(&config, server_id).await?)
})
}
pub(super) fn handle_set_enabled(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
let enabled = read_required::<bool>(&params, "enabled")?;
to_json(
@@ -123,17 +123,17 @@ pub(super) fn handle_set_enabled(
})
}
-pub(super) fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let _ = params;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::mcp::registry::ops::mcp_clients_status(&config).await?)
})
}
-pub(super) fn handle_list_tools(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_list_tools(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let server_id = read_required::<String>(&params, "server_id")?;
to_json(
crate::mcp::registry::ops::mcp_clients_list_tools(
@@ -146,7 +146,7 @@ pub(super) fn handle_list_tools(_ctx: DispatchCtx, params: Map<String, Value>) -
})
}
-pub(super) fn handle_tool_call(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_tool_call(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let server_id = read_required::<String>(&params, "server_id")?;
let tool_name = read_required::<String>(&params, "tool_name")?;
@@ -154,7 +154,7 @@ pub(super) fn handle_tool_call(_ctx: DispatchCtx, params: Map<String, Value>) ->
.get("arguments")
.cloned()
.unwrap_or(Value::Object(Map::new()));
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::mcp::registry::ops::mcp_clients_tool_call(
&config, server_id, tool_name, arguments,
@@ -164,17 +164,17 @@ pub(super) fn handle_tool_call(_ctx: DispatchCtx, params: Map<String, Value>) ->
})
}
-pub(super) fn handle_config_get(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_config_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let _ = params;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::mcp::registry::config_ops::mcp_clients_config_get(&config).await?)
})
}
-pub(super) fn handle_config_set(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(super) fn handle_config_set(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// The whole document is the parameter set: `{ "mcpServers": { … } }`
// is what a user pastes, and wrapping it in another key would make the
// wire shape differ from the file shape for no reason.
@@ -184,25 +184,25 @@ pub(super) fn handle_config_set(_ctx: DispatchCtx, params: Map<String, Value>) -
}
pub(super) fn handle_registry_settings_get(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let _ = params;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::mcp::registry::ops::mcp_clients_registry_settings_get(&config).await?)
})
}
pub(super) fn handle_registry_settings_set(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let smithery_api_key = read_optional::<String>(&params, "smithery_api_key")?;
let mcp_official_base = read_optional::<String>(&params, "mcp_official_base")?;
let mcp_official_token = read_optional::<String>(&params, "mcp_official_token")?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(
crate::mcp::registry::ops::mcp_clients_registry_settings_set(
&mut config,
diff --git a/crates/openhuman-core/src/mcp/server/handler.rs b/crates/openhuman-core/src/mcp/server/handler.rs
index 8c8484cbed..e358368e92 100644
--- a/crates/openhuman-core/src/mcp/server/handler.rs
+++ b/crates/openhuman-core/src/mcp/server/handler.rs
@@ -4,6 +4,7 @@
//! OpenHuman policy and invokes the existing tool/resource implementations;
//! it does not parse protocol messages or own a transport.
+use crate::core::runtime::DispatchCtx;
use serde_json::{Map, Value};
use tinymcp_bus::{ServerHostCall, ServerHostReply, ToolCallError};
@@ -12,10 +13,10 @@ use super::{resources, subagent_depth, tools};
const INSTRUCTIONS: &str = "OpenHuman MCP exposes first-level core integration: inspect the live tool catalog with core.list_tools or core.tool_instructions, inspect subagents with agent.list_subagents, run a standalone subagent with agent.run_subagent, use web_search or web_answer for live web lookups (and searxng_search when self-hosted search is enabled), and use memory.recall (answer with citations), memory.fetch or memory.list to read memory, and memory.learn or memory.forget to change it.";
/// Apply the host-owned part of a validated TinyMCP server callback.
-pub(super) async fn dispatch(call: ServerHostCall) -> ServerHostReply {
+pub(super) async fn dispatch(ctx: &DispatchCtx, call: ServerHostCall) -> ServerHostReply {
match call {
ServerHostCall::ListTools { .. } => {
- let specs = tools::list_tool_specs()
+ let specs = tools::list_tool_specs(&ctx)
.await
.iter()
.map(tools::server_tool_spec)
@@ -42,7 +43,7 @@ pub(super) async fn dispatch(call: ServerHostCall) -> ServerHostReply {
);
let result = subagent_depth::scope(
depth,
- tools::call_tool(&name, Value::Object(arguments), &source_type),
+ tools::call_tool(&ctx, &name, Value::Object(arguments), &source_type),
)
.await;
result.map_or_else(reply_error, |value| ServerHostReply::Success { value })
diff --git a/crates/openhuman-core/src/mcp/server/http.rs b/crates/openhuman-core/src/mcp/server/http.rs
index c1beae4397..97d8c06077 100644
--- a/crates/openhuman-core/src/mcp/server/http.rs
+++ b/crates/openhuman-core/src/mcp/server/http.rs
@@ -1,5 +1,6 @@
//! OpenHuman's thin Streamable HTTP adapter over TinyMCP's server contract.
+use crate::core::runtime::DispatchCtx;
use std::{collections::HashMap, convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};
use axum::{
@@ -69,7 +70,7 @@ fn router(state: HttpState) -> Router {
.with_state(state)
}
-async fn handle_post(State(state): State<HttpState>, headers: HeaderMap, body: Bytes) -> Response {
+async fn handle_post(ctx: &DispatchCtx, State(state): State<HttpState>, headers: HeaderMap, body: Bytes) -> Response {
if let Some(response) = check_auth(&state, &headers) {
return response;
}
@@ -92,6 +93,7 @@ async fn handle_post(State(state): State<HttpState>, headers: HeaderMap, body: B
let session = match session {
Some(session) => session,
None => match ServerSession::open_http(
+ &ctx,
Arc::clone(&state.port),
requested_session_id.clone(),
false,
diff --git a/crates/openhuman-core/src/mcp/server/http_tests.rs b/crates/openhuman-core/src/mcp/server/http_tests.rs
index 3b3712f088..6d0a1339ed 100644
--- a/crates/openhuman-core/src/mcp/server/http_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/http_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use async_trait::async_trait;
use axum::body::to_bytes;
@@ -177,6 +178,7 @@ async fn rejected_http_delete_keeps_session_usable() {
assert!(state.sessions.lock().await.contains_key("wire-session"));
let usable = handle_post(
+ &DispatchCtx::process_default(),
State(state.clone()),
http_test_headers("wire-session", "2025-11-25"),
Bytes::from_static(br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#),
@@ -227,6 +229,7 @@ async fn successful_http_delete_joins_blocked_callback_before_removing_session()
let post_state = State(state.clone());
let post = tokio::spawn(async move {
handle_post(
+ &DispatchCtx::process_default(),
post_state,
http_test_headers("wire-session", "2025-11-25"),
Bytes::from_static(br#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#),
diff --git a/crates/openhuman-core/src/mcp/server/module.rs b/crates/openhuman-core/src/mcp/server/module.rs
index a6fc9db38b..d8e1c91521 100644
--- a/crates/openhuman-core/src/mcp/server/module.rs
+++ b/crates/openhuman-core/src/mcp/server/module.rs
@@ -1,5 +1,6 @@
//! TinyMCP server-protocol adapter over the published bus contract.
+use crate::core::runtime::DispatchCtx;
use std::{
future::Future,
pin::Pin,
@@ -205,12 +206,12 @@ impl ServerSession {
});
}
- pub(super) async fn open(config: &Config) -> Result<Self, ServerError> {
- Self::open_with_port(Self::port_for_config(config)).await
+ pub(super) async fn open(ctx: &DispatchCtx, config: &Config) -> Result<Self, ServerError> {
+ Self::open_with_port(&ctx, Self::port_for_config(config)).await
}
- async fn open_with_port(port: Arc<dyn ServerPort>) -> Result<Self, ServerError> {
- Self::open_with_port_and_dispatch(port, |call| Box::pin(handler::dispatch(call))).await
+ async fn open_with_port(ctx: &DispatchCtx, port: Arc<dyn ServerPort>) -> Result<Self, ServerError> {
+ Self::open_with_port_and_dispatch(port, |call| Box::pin(handler::dispatch(&ctx, call))).await
}
pub(super) async fn open_with_port_and_dispatch<F, Fut>(
@@ -246,7 +247,7 @@ impl ServerSession {
})
}
- pub(super) async fn open_http(
+ pub(super) async fn open_http(ctx: &DispatchCtx,
port: Arc<dyn ServerPort>,
requested_session_id: Option<String>,
known_session: bool,
@@ -270,7 +271,7 @@ impl ServerSession {
.map_err(ServerError::Module)?;
Ok(Self {
port,
- callback_dispatch: Arc::new(|call| Box::pin(handler::dispatch(call))),
+ callback_dispatch: Arc::new(|call| Box::pin(handler::dispatch(&ctx, call))),
id,
next_operation: AtomicU64::new(1),
operation: tokio::sync::Mutex::new(()),
diff --git a/crates/openhuman-core/src/mcp/server/module_tests.rs b/crates/openhuman-core/src/mcp/server/module_tests.rs
index 1689bb022f..7d0e749b52 100644
--- a/crates/openhuman-core/src/mcp/server/module_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/module_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use std::sync::Mutex;
use tinymcp_bus::ServerHostCall;
@@ -130,7 +131,7 @@ impl ServerPort for FixturePort {
#[tokio::test]
async fn server_session_completes_host_resource_callback() {
let port = Arc::new(FixturePort(Mutex::new(PortState::default())));
- let session = ServerSession::open_with_port(port.clone()).await.unwrap();
+ let session = ServerSession::open_with_port(&DispatchCtx::process_default(), port.clone()).await.unwrap();
assert!(!Uuid::parse_str(session.id()).unwrap().is_nil());
let snapshot = session
@@ -162,7 +163,7 @@ async fn retry_after_lost_callback_reply_reuses_operation_and_host_reply() {
lose_first_complete_reply: true,
..PortState::default()
})));
- let session = ServerSession::open_with_port(port.clone()).await.unwrap();
+ let session = ServerSession::open_with_port(&DispatchCtx::process_default(), port.clone()).await.unwrap();
let line = r#"{"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"openhuman://prompts/identity"}}"#;
let first = session
@@ -196,7 +197,7 @@ async fn retry_after_lost_callback_reply_reuses_operation_and_host_reply() {
#[tokio::test]
async fn server_session_cancellation_reaches_module_owner() {
let port = Arc::new(FixturePort(Mutex::new(PortState::default())));
- let session = ServerSession::open_with_port(port.clone()).await.unwrap();
+ let session = ServerSession::open_with_port(&DispatchCtx::process_default(), port.clone()).await.unwrap();
let cancellation = CancellationToken::new();
cancellation.cancel();
@@ -272,7 +273,7 @@ async fn server_session_fails_closed_when_module_is_unavailable() {
..PortState::default()
})));
- let error = match ServerSession::open_with_port(port).await {
+ let error = match ServerSession::open_with_port(&DispatchCtx::process_default(), port).await {
Ok(_) => panic!("unavailable module unexpectedly opened"),
Err(error) => error,
};
diff --git a/crates/openhuman-core/src/mcp/server/stdio.rs b/crates/openhuman-core/src/mcp/server/stdio.rs
index 5c5f96bd57..00e8ae033b 100644
--- a/crates/openhuman-core/src/mcp/server/stdio.rs
+++ b/crates/openhuman-core/src/mcp/server/stdio.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use anyhow::{bail, Result};
// `SocketAddr` + the `http` transport are only reached by the `--transport http`
// arm, which is axum-only and gated with `http-server` (#5048). The stdio arm
@@ -17,7 +18,7 @@ enum McpTransport {
Http,
}
-pub fn run_stdio_from_cli(args: &[String]) -> Result<()> {
+pub fn run_stdio_from_cli(ctx: &DispatchCtx, args: &[String]) -> Result<()> {
let mut verbose = false;
let mut transport = McpTransport::Stdio;
let mut bind_host = "127.0.0.1".to_string();
@@ -85,7 +86,7 @@ pub fn run_stdio_from_cli(args: &[String]) -> Result<()> {
match transport {
McpTransport::Stdio => {
log::debug!("[mcp_server] starting stdio MCP server");
- rt.block_on(run_stdio_module())?;
+ rt.block_on(run_stdio_module(&ctx))?;
}
McpTransport::Http => {
#[cfg(feature = "http-server")]
@@ -115,13 +116,13 @@ pub fn run_stdio_from_cli(args: &[String]) -> Result<()> {
Ok(())
}
-async fn run_stdio_module() -> Result<()> {
+async fn run_stdio_module(ctx: &DispatchCtx, ) -> Result<()> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(anyhow::Error::msg)?;
- let session = ServerSession::open(&config).await?;
+ let session = ServerSession::open(&ctx, &config).await?;
let cancellation = tokio_util::sync::CancellationToken::new();
let result = async {
let mut input = tokio::io::BufReader::new(tokio::io::stdin()).lines();
diff --git a/crates/openhuman-core/src/mcp/server/stdio_tests.rs b/crates/openhuman-core/src/mcp/server/stdio_tests.rs
index 163ccc5267..7ff9faeafb 100644
--- a/crates/openhuman-core/src/mcp/server/stdio_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/stdio_tests.rs
@@ -1,11 +1,12 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
#[test]
fn cli_help_exits_zero() {
- assert!(run_stdio_from_cli(&["--help".into()]).is_ok());
+ assert!(run_stdio_from_cli(&DispatchCtx::process_default(), &["--help".into()]).is_ok());
}
#[test]
fn cli_verbose_advances_to_next_arg() {
- assert!(run_stdio_from_cli(&["--verbose".into(), "--help".into()]).is_ok());
+ assert!(run_stdio_from_cli(&DispatchCtx::process_default(), &["--verbose".into(), "--help".into()]).is_ok());
}
diff --git a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
index 953f1dfeb3..159015511b 100644
--- a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
+++ b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs
@@ -17,8 +17,8 @@ use tinymcp_bus::ToolCallError;
/// The tools `tools/list` advertises and `tools/call` accepts: every tool the
/// loaded config can serve, or only the config-independent base set when the
/// config will not load. `method` names the MCP method for the log line.
-async fn available_tool_specs(method: &str) -> Vec<McpToolSpec> {
- match config_rpc::load_config_with_timeout().await {
+async fn available_tool_specs(ctx: &DispatchCtx, method: &str) -> Vec<McpToolSpec> {
+ match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => tool_specs_for_loaded_config(&config),
Err(err) => {
log::warn!(
@@ -29,23 +29,23 @@ async fn available_tool_specs(method: &str) -> Vec<McpToolSpec> {
}
}
-pub async fn list_tool_specs() -> Vec<McpToolSpec> {
- available_tool_specs("tools/list").await
+pub async fn list_tool_specs(ctx: &DispatchCtx, ) -> Vec<McpToolSpec> {
+ available_tool_specs(&ctx, "tools/list").await
}
-pub async fn call_tool(
+pub async fn call_tool(ctx: &DispatchCtx,
name: &str,
arguments: Value,
client_info: &str,
) -> Result<Value, ToolCallError> {
- let specs = available_tool_specs("tools/call").await;
+ let specs = available_tool_specs(&ctx, "tools/call").await;
let spec = specs
.into_iter()
.find(|tool| tool.name == name)
.ok_or_else(|| ToolCallError::InvalidParams(format!("unknown MCP tool `{name}`")))?;
let audit_arguments = arguments.clone();
- let params = match build_rpc_params(spec.name, arguments).await {
+ let params = match build_rpc_params(&ctx, spec.name, arguments).await {
Ok(params) => params,
Err(err) => {
if write_dispatch::is_write_tool(spec.name) {
@@ -61,23 +61,23 @@ pub async fn call_tool(
};
match spec.name {
"core.list_tools" => {
- enforce_read_policy(spec.name).await?;
- return list_core_tools().await;
+ enforce_read_policy(&ctx, spec.name).await?;
+ return list_core_tools(&ctx).await;
}
"core.tool_instructions" => {
- enforce_read_policy(spec.name).await?;
- return core_tool_instructions().await;
+ enforce_read_policy(&ctx, spec.name).await?;
+ return core_tool_instructions(&ctx).await;
}
"agent.list_subagents" => {
- enforce_read_policy(spec.name).await?;
- return list_subagents().await;
+ enforce_read_policy(&ctx, spec.name).await?;
+ return list_subagents(&ctx).await;
}
"agent.run_subagent" => {
- enforce_act_policy(spec.name).await?;
- return run_subagent_tool(&params).await;
+ enforce_act_policy(&ctx, spec.name).await?;
+ return run_subagent_tool(&ctx, &params).await;
}
"memory.learn" | "memory.forget" => {
- let config = write_dispatch::load_write_config(spec.name).await?;
+ let config = write_dispatch::load_write_config(&ctx, spec.name).await?;
if let Err(err) = write_dispatch::enforce_write_policy_for_config(spec.name, &config) {
write_dispatch::audit_write_rejection(
&config,
@@ -120,7 +120,7 @@ pub async fn call_tool(
}
validate_controller_params(&spec, &params)?;
- enforce_read_policy(spec.name).await?;
+ enforce_read_policy(&ctx, spec.name).await?;
let rpc_method = spec.rpc_method.ok_or_else(|| {
ToolCallError::Internal(format!(
@@ -163,11 +163,11 @@ pub async fn call_tool(
}
}
-async fn enforce_read_policy(tool_name: &str) -> Result<(), ToolCallError> {
+async fn enforce_read_policy(ctx: &DispatchCtx, tool_name: &str) -> Result<(), ToolCallError> {
// Config-load failure is an internal/server issue (disk error, corrupt
// config), not bad client input — report it as `-32603 Internal error`
// rather than `-32602 Invalid params`.
- let config = match config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(err) => {
log::warn!(
@@ -188,8 +188,8 @@ async fn enforce_read_policy(tool_name: &str) -> Result<(), ToolCallError> {
.map_err(ToolCallError::InvalidParams)
}
-async fn enforce_act_policy(tool_name: &str) -> Result<(), ToolCallError> {
- let config = match config_rpc::load_config_with_timeout().await {
+async fn enforce_act_policy(ctx: &DispatchCtx, tool_name: &str) -> Result<(), ToolCallError> {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(err) => {
log::warn!(
@@ -207,8 +207,8 @@ async fn enforce_act_policy(tool_name: &str) -> Result<(), ToolCallError> {
.map_err(ToolCallError::InvalidParams)
}
-async fn load_config_and_init_registry() -> Result<crate::config::Config, ToolCallError> {
- let config = config_rpc::load_config_with_timeout()
+async fn load_config_and_init_registry(ctx: &DispatchCtx, ) -> Result<crate::config::Config, ToolCallError> {
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.map_err(|err| ToolCallError::Internal(format!("failed to load config: {err}")))?;
AgentDefinitionRegistry::init_global(&config.workspace_dir).map_err(|err| {
@@ -219,8 +219,8 @@ async fn load_config_and_init_registry() -> Result<crate::config::Config, ToolCa
Ok(config)
}
-async fn build_orchestrator_agent() -> Result<OpenHumanSessionHost, ToolCallError> {
- let config = load_config_and_init_registry().await?;
+async fn build_orchestrator_agent(ctx: &DispatchCtx, ) -> Result<OpenHumanSessionHost, ToolCallError> {
+ let config = load_config_and_init_registry(&ctx).await?;
let mut agent =
OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator").map_err(|err| {
ToolCallError::Internal(format!("failed to build orchestrator agent: {err}"))
@@ -230,8 +230,8 @@ async fn build_orchestrator_agent() -> Result<OpenHumanSessionHost, ToolCallErro
Ok(agent)
}
-async fn list_core_tools() -> Result<Value, ToolCallError> {
- let agent = build_orchestrator_agent().await?;
+async fn list_core_tools(ctx: &DispatchCtx, ) -> Result<Value, ToolCallError> {
+ let agent = build_orchestrator_agent(&ctx).await?;
let tools = agent
.tool_specs()
.iter()
@@ -246,8 +246,8 @@ async fn list_core_tools() -> Result<Value, ToolCallError> {
Ok(tool_success(json!({ "tools": tools })))
}
-async fn core_tool_instructions() -> Result<Value, ToolCallError> {
- let agent = build_orchestrator_agent().await?;
+async fn core_tool_instructions(ctx: &DispatchCtx, ) -> Result<Value, ToolCallError> {
+ let agent = build_orchestrator_agent(&ctx).await?;
let schemas: Vec<_> = agent
.tool_specs()
.iter()
@@ -267,8 +267,8 @@ async fn core_tool_instructions() -> Result<Value, ToolCallError> {
))
}
-async fn list_subagents() -> Result<Value, ToolCallError> {
- let config = load_config_and_init_registry().await?;
+async fn list_subagents(ctx: &DispatchCtx, ) -> Result<Value, ToolCallError> {
+ let config = load_config_and_init_registry(&ctx).await?;
let registry = AgentDefinitionRegistry::current().ok_or_else(|| {
ToolCallError::Internal("AgentDefinitionRegistry missing after init".to_string())
})?;
@@ -316,7 +316,7 @@ async fn list_subagents() -> Result<Value, ToolCallError> {
}))
}
-async fn run_subagent_tool(params: &Map<String, Value>) -> Result<Value, ToolCallError> {
+async fn run_subagent_tool(ctx: &DispatchCtx, params: &Map<String, Value>) -> Result<Value, ToolCallError> {
use super::super::subagent_depth;
let agent_id = validated_param(params, "agent_id")?;
@@ -337,7 +337,7 @@ async fn run_subagent_tool(params: &Map<String, Value>) -> Result<Value, ToolCal
subagent_depth::MAX_SUBAGENT_DEPTH
)))?;
- let config = load_config_and_init_registry().await?;
+ let config = load_config_and_init_registry(&ctx).await?;
let mut agent =
OpenHumanSessionHost::from_config_for_agent(&config, agent_id).map_err(|err| {
ToolCallError::InvalidParams(format!("failed to build agent `{agent_id}`: {err}"))
diff --git a/crates/openhuman-core/src/mcp/server/tools/params.rs b/crates/openhuman-core/src/mcp/server/tools/params.rs
index 316a18c22d..705c710f42 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;
@@ -12,11 +13,11 @@ use super::types::{
WEB_SEARCH_ARGUMENTS,
};
-pub async fn build_rpc_params(
+pub async fn build_rpc_params(ctx: &DispatchCtx,
tool_name: &str,
arguments: Value,
) -> Result<Map<String, Value>, ToolCallError> {
- let args = validate_tool_arguments(tool_name, arguments).await?;
+ let args = validate_tool_arguments(&ctx, tool_name, arguments).await?;
build_rpc_params_from_validated(tool_name, &args)
}
@@ -139,7 +140,7 @@ pub(crate) fn build_rpc_params_for_test(
build_rpc_params_from_validated(tool_name, &args)
}
-async fn validate_tool_arguments(
+async fn validate_tool_arguments(ctx: &DispatchCtx,
tool_name: &str,
arguments: Value,
) -> Result<Map<String, Value>, 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(&ctx)
.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/mcp/server/tools_tests_dispatch_tests.rs b/crates/openhuman-core/src/mcp/server/tools_tests_dispatch_tests.rs
index 4cce6fe8d2..218cf22727 100644
--- a/crates/openhuman-core/src/mcp/server/tools_tests_dispatch_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/tools_tests_dispatch_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
#[tokio::test]
@@ -7,11 +8,11 @@ async fn call_tool_records_write_argument_rejection() {
unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());
}
- let config = config_rpc::load_config_with_timeout()
+ let config = config_rpc::load_config_with_timeout(&DispatchCtx::process_default())
.await
.expect("config");
- let err = call_tool("memory.learn", json!({ "kind": "fact" }), "mcp:test")
+ let err = call_tool(&DispatchCtx::process_default(), "memory.learn", json!({ "kind": "fact" }), "mcp:test")
.await
.expect_err("missing text should reject");
assert!(
@@ -53,7 +54,7 @@ async fn call_tool_records_write_argument_rejection() {
#[tokio::test]
async fn call_tool_rejects_v1_memory_tools_as_unknown() {
for name in ["memory.search", "memory.store", "memory.note", "tree.tag"] {
- let err = call_tool(name, json!({}), "mcp:test")
+ let err = call_tool(&DispatchCtx::process_default(), name, json!({}), "mcp:test")
.await
.expect_err("removed tool");
assert!(err.message().contains("unknown MCP tool"), "{name}");
@@ -71,11 +72,12 @@ async fn call_tool_validates_memory_arguments_before_dispatch() {
unsafe {
std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());
}
- let err = call_tool("memory.forget", json!({ "ids": [] }), "mcp:test")
+ let err = call_tool(&DispatchCtx::process_default(), "memory.forget", json!({ "ids": [] }), "mcp:test")
.await
.expect_err("empty ids rejected before any RPC");
assert!(err.message().contains("`ids`"), "got: {}", err.message());
let err = call_tool(
+ &DispatchCtx::process_default(),
"memory.recall",
json!({ "question": "q", "filter": { "x": 1 } }),
"mcp:test",
diff --git a/crates/openhuman-core/src/mcp/server/write_dispatch.rs b/crates/openhuman-core/src/mcp/server/write_dispatch.rs
index ce45f3f1f9..10c46488e6 100644
--- a/crates/openhuman-core/src/mcp/server/write_dispatch.rs
+++ b/crates/openhuman-core/src/mcp/server/write_dispatch.rs
@@ -15,8 +15,8 @@ use crate::security::{SecurityPolicy, ToolOperation};
use super::tools::{tool_error, tool_success, ToolCallError};
-pub(super) async fn load_write_config(tool_name: &str) -> Result<Config, ToolCallError> {
- match config_rpc::load_config_with_timeout().await {
+pub(super) async fn load_write_config(ctx: &DispatchCtx, tool_name: &str) -> Result<Config, ToolCallError> {
+ match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => Ok(config),
Err(err) => {
log::warn!(
@@ -190,7 +190,7 @@ pub(super) fn audit_write_rejection(
);
}
-pub(super) fn audit_write_rejection_without_config(
+pub(super) fn audit_write_rejection_without_config(ctx: &DispatchCtx,
tool_name: &str,
audit_arguments: &Value,
client_info: &str,
@@ -210,7 +210,7 @@ pub(super) fn audit_write_rejection_without_config(
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
std::mem::drop(handle.spawn(async move {
- match config_rpc::load_config_with_timeout().await {
+ match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => audit_write(
&config,
NewMcpWriteRecord {
diff --git a/crates/openhuman-core/src/mcp/ui/schemas.rs b/crates/openhuman-core/src/mcp/ui/schemas.rs
index e1c896a051..cc4af16e02 100644
--- a/crates/openhuman-core/src/mcp/ui/schemas.rs
+++ b/crates/openhuman-core/src/mcp/ui/schemas.rs
@@ -90,25 +90,25 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_resource_read(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_resource_read(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let server_id = read_optional::<String>(&params, "server_id")?;
let uri = read_optional::<String>(&params, "uri")?;
let inline_id = read_optional::<String>(&params, "inline_id")?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let port = HostUiPort::new(Arc::new(config));
let outcome = ops::resource_read(&port, server_id, uri, inline_id).await?;
Ok(outcome.value)
})
}
-fn handle_tool_call(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_tool_call(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let server_id = read_optional::<String>(&params, "server_id")?;
let tool_name = read_optional::<String>(&params, "tool_name")?;
let arguments = params.get("arguments").cloned();
let confirmed = read_optional::<bool>(&params, "confirmed")?.unwrap_or(false);
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let security = crate::security::live_policy::current().unwrap_or_else(|| {
Arc::new(SecurityPolicy::from_config(
&config.autonomy,
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index 8a800c1f6b..364e4e453f 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 crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).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 crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).await {
Ok(config) => config,
Err(error) => {
tracing::debug!(error = %error, job = %job, "[memory:bus] config unavailable");
@@ -115,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.rs
index 1b27be12e7..1e582e60f4 100644
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@ -34,8 +34,8 @@ fn finish<T: Serialize>(result: MemoryResult<T>) -> Result<Value, String> {
to_json(result.map_err(String::from)?)
}
-async fn load() -> Result<Config, String> {
- crate::config::rpc::load_config_with_timeout().await
+async fn load(ctx: &DispatchCtx, ) -> Result<Config, String> {
+ crate::config::rpc::load_config_with_timeout(&ctx).await
}
async fn save(config: &Config) -> MemoryResult<()> {
@@ -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, &params)?;
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, &params).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, &params).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, &params.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/schemas.rs b/crates/openhuman-core/src/modules/schemas.rs
index aa3b92d4c7..8beb99385e 100644
--- a/crates/openhuman-core/src/modules/schemas.rs
+++ b/crates/openhuman-core/src/modules/schemas.rs
@@ -201,11 +201,11 @@ fn readiness_error(detail: &str) -> String {
}
fn handle_browser_check_readiness(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
crate::core::runtime::components::require_config(&config, "computer")?;
// The probe never navigates. Give its disposable session a non-routable
// origin so an empty website allowlist does not prevent a Chrome check.
@@ -242,7 +242,7 @@ fn handle_browser_check_readiness(
})
}
-fn handle_browser_forget_sites(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_browser_forget_sites(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
// A blank or non-text site must not read as "every site".
let site = match params.get("site") {
@@ -255,7 +255,7 @@ fn handle_browser_forget_sites(_ctx: DispatchCtx, params: Map<String, Value>) ->
)
}
};
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
crate::core::runtime::components::require_config(&config, "computer")?;
let forgotten = super::site_memory_host::forget(&config, site.as_deref())
.await
@@ -269,10 +269,10 @@ fn handle_browser_forget_sites(_ctx: DispatchCtx, params: Map<String, Value>) ->
})
}
-fn handle_computer_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_computer_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let load = params.get("load").and_then(Value::as_bool).unwrap_or(false);
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
crate::core::runtime::components::require_config(&config, "computer")?;
controller_value(super::computer::status(&config, load).await)
})
@@ -282,17 +282,17 @@ fn controller_value(value: impl serde::Serialize) -> Result<Value, String> {
serde_json::to_value(value).map_err(|error| error.to_string())
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
Ok(serde_json::json!({ "modules": ops::list(&config) }))
})
}
-fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let id = string_param(&params, "id").ok_or("`id` is required")?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
match ops::list(&config).into_iter().find(|m| m.id == id) {
Some(module) => Ok(serde_json::json!({ "module": module })),
None => Err(format!("unknown module '{id}'")),
@@ -300,10 +300,10 @@ fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_load(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_load(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let id = string_param(&params, "id").ok_or("`id` is required")?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// A failed load is reported through the returned status rather than as
// an RPC error: the caller asked "what happened", and the answer is a
// state plus a reason, not a transport failure.
diff --git a/crates/openhuman-core/src/modules/site_memory_host.rs b/crates/openhuman-core/src/modules/site_memory_host.rs
index 8e8497ea5c..784f957b6e 100644
--- a/crates/openhuman-core/src/modules/site_memory_host.rs
+++ b/crates/openhuman-core/src/modules/site_memory_host.rs
@@ -13,6 +13,7 @@
//! forget epoch that stops a task running when its site was forgotten from
//! writing it back.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
@@ -176,8 +177,8 @@ async fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[derive(Clone)]
struct SiteMemoryHost;
-async fn config() -> tinybus::Result<crate::config::Config> {
- crate::config::rpc::load_config_with_timeout()
+async fn config(ctx: &DispatchCtx, ) -> tinybus::Result<crate::config::Config> {
+ crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| method_error(format!("config unavailable: {e}")))
}
@@ -329,23 +330,23 @@ async fn save_site(
#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.SiteMemoryHost")]
impl SiteMemoryHost {
/// One site's memory; empty for a site with nothing kept.
- async fn load(&self, request: LoadSiteRequest) -> tinybus::Result<LoadSiteResponse> {
- load_site(&config().await?, request)
+ async fn load(&self, ctx: &DispatchCtx, request: LoadSiteRequest) -> tinybus::Result<LoadSiteResponse> {
+ load_site(&config(&ctx).await?, request)
.await
.map_err(method_error)
}
/// Replaces one site's memory, unless learning is off or the site was
/// forgotten since it was loaded.
- async fn save(&self, request: SaveSiteRequest) -> tinybus::Result<SaveSiteResponse> {
- save_site(&config().await?, request)
+ async fn save(&self, ctx: &DispatchCtx, request: SaveSiteRequest) -> tinybus::Result<SaveSiteResponse> {
+ save_site(&config(&ctx).await?, request)
.await
.map_err(method_error)
}
/// Forgets one site, or every site.
- async fn forget(&self, request: ForgetSiteRequest) -> tinybus::Result<ForgetSiteResponse> {
- let forgotten = forget(&config().await?, request.site.as_deref())
+ async fn forget(&self, ctx: &DispatchCtx, request: ForgetSiteRequest) -> tinybus::Result<ForgetSiteResponse> {
+ let forgotten = forget(&config(&ctx).await?, request.site.as_deref())
.await
.map_err(method_error)?;
Ok(ForgetSiteResponse {
diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs
index 9a5312b474..160743fb2a 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};
@@ -160,9 +161,9 @@ pub(super) fn has_endpoint_reference_for_test(reference: &str) -> bool {
.is_ok_and(|references| references.contains_key(reference))
}
-pub(crate) async fn wallet_accounts_snapshot(
+pub(crate) async fn wallet_accounts_snapshot(ctx: &DispatchCtx,
) -> Result<tinywallet_bus::wire::WalletAccountsResponse, String> {
- let status = crate::web3::wallet::status()
+ let status = crate::web3::wallet::status(&ctx)
.await
.map_err(|error| error.to_string())?
.value;
@@ -513,9 +514,9 @@ struct WalletHost;
impl WalletHost {
/// Public wallet setup state and addresses; encrypted secrets never leave
/// the host's custody store through this callback.
- async fn wallet_accounts(&self) -> tinybus::Result<HostResponse> {
+ async fn wallet_accounts(&self, ctx: &DispatchCtx) -> tinybus::Result<HostResponse> {
Ok(HostResponse::WalletAccounts(
- wallet_accounts_snapshot().await.map_err(callback_error)?,
+ wallet_accounts_snapshot(&ctx).await.map_err(callback_error)?,
))
}
@@ -632,8 +633,8 @@ impl WalletHost {
}
/// Perform only the named authenticated wallet-backend request.
- async fn wallet_backend(&self, request: WalletBackendRequest) -> tinybus::Result<HostResponse> {
- let config = crate::config::rpc::load_config_with_timeout()
+ async fn wallet_backend(&self, ctx: &DispatchCtx, request: WalletBackendRequest) -> tinybus::Result<HostResponse> {
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(callback_error)?;
let client =
diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rs
index 9d3ddde56d..3447077a26 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;
@@ -37,7 +38,7 @@ fn native_wallet_service() -> &'static tokio::sync::Mutex<Option<NativeWalletSer
/// Run one operation under the current user's module service. The lock spans
/// the complete bus operation so a user or endpoint change cannot replace the
/// module's quote store while an earlier request is still using it.
-pub(crate) async fn with_native_wallet<R, F, Fut>(
+pub(crate) async fn with_native_wallet<R, F, Fut>(ctx: &DispatchCtx,
config: &Config,
operation: F,
) -> Result<R, WalletCallError>
@@ -48,7 +49,7 @@ where
{
let mut active = native_wallet_service().lock().await;
register_native_wallet_shutdown_hook();
- let accounts = super::wallet_host::wallet_accounts_snapshot()
+ let accounts = super::wallet_host::wallet_accounts_snapshot(&ctx)
.await
.map_err(WalletCallError::Failed)?;
let configuration = native_wallet_config_request();
@@ -119,14 +120,14 @@ async fn ensure_native_wallet(
/// Prepare a native transfer through the module and retain its exact quote so
/// the host can bind approval and signer selection to the same immutable facts.
-pub(crate) async fn prepare_native_transfer(
+pub(crate) async fn prepare_native_transfer(ctx: &DispatchCtx,
config: &Config,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
params: tinywallet_bus::wire::PrepareTransferParams,
) -> Result<tinywallet_bus::wire::PreparedTransaction, WalletCallError> {
let mut active = native_wallet_service().lock().await;
register_native_wallet_shutdown_hook();
- let accounts = super::wallet_host::wallet_accounts_snapshot()
+ let accounts = super::wallet_host::wallet_accounts_snapshot(&ctx)
.await
.map_err(WalletCallError::Failed)?;
ensure_native_wallet(
@@ -163,7 +164,7 @@ pub(crate) async fn prepare_native_transfer(
/// Execute one explicitly confirmed native quote. The host retrieves only the
/// matching account secret and delivers it over the attested confidential bus
/// call; the module owns quote validation, approval facts, signing and broadcast.
-pub(crate) async fn execute_native_transfer(
+pub(crate) async fn execute_native_transfer(ctx: &DispatchCtx,
config: &Config,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
params: tinywallet_bus::wire::ExecutePreparedParams,
@@ -176,7 +177,7 @@ pub(crate) async fn execute_native_transfer(
let mut active = native_wallet_service().lock().await;
register_native_wallet_shutdown_hook();
- let accounts = super::wallet_host::wallet_accounts_snapshot()
+ let accounts = super::wallet_host::wallet_accounts_snapshot(&ctx)
.await
.map_err(WalletCallError::Failed)?;
ensure_native_wallet(
@@ -198,7 +199,7 @@ pub(crate) async fn execute_native_transfer(
.ok_or_else(|| {
WalletCallError::InvalidInput("prepared wallet quote is unavailable".into())
})?;
- let secret = signing_secret(config, quote.chain).await?;
+ let secret = signing_secret(&ctx, config, quote.chain).await?;
let mut request = tinywallet_bus::wire::NativeWalletExecuteRequest {
service: service.response.service.clone(),
owner,
@@ -221,7 +222,7 @@ pub(crate) async fn execute_native_transfer(
result
}
-async fn signing_secret(
+async fn signing_secret(ctx: &DispatchCtx,
config: &Config,
chain: tinywallet_bus::wire::WalletChain,
) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {
@@ -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(&ctx, local_chain)
.await
.map_err(WalletCallError::Failed)?;
let mnemonic =
diff --git a/crates/openhuman-core/src/modules/wallet_service_tests.rs b/crates/openhuman-core/src/modules/wallet_service_tests.rs
index 02941dd15c..a2a1d32f23 100644
--- a/crates/openhuman-core/src/modules/wallet_service_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_service_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use std::sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
@@ -195,6 +196,7 @@ fn native_service_reuses_its_handle_for_identical_user_state() {
#[tokio::test]
async fn unconfirmed_execution_is_rejected_before_wallet_service_or_secret_access() {
let error = execute_native_transfer(
+ &DispatchCtx::process_default(),
&crate::config::Config::default(),
None,
tinywallet_bus::wire::ExecutePreparedParams {
diff --git a/crates/openhuman-core/src/modules/web3_service.rs b/crates/openhuman-core/src/modules/web3_service.rs
index 452496055f..b27a841ba2 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};
@@ -31,12 +32,12 @@ fn service() -> &'static tokio::sync::Mutex<Option<Web3Service>> {
WEB3_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))
}
-async fn ensure_service(
+async fn ensure_service(ctx: &DispatchCtx,
config: &Config,
active: &mut Option<Web3Service>,
) -> Result<(), wallet::WalletCallError> {
- register_shutdown_hook();
- let accounts = wallet_host::wallet_accounts_snapshot()
+ register_shutdown_hook(&ctx);
+ let accounts = wallet_host::wallet_accounts_snapshot(&ctx)
.await
.map_err(wallet::WalletCallError::Failed)?;
let workspace = config.workspace_dir.clone();
@@ -109,8 +110,8 @@ pub(crate) fn owner_of(
/// Close the active module service on sign-out. The mutex joins any in-flight
/// quote, route, or execution call before its owner-scoped handles are cleared.
-pub(crate) async fn close_service(config: &Config) -> Result<(), wallet::WalletCallError> {
- register_shutdown_hook();
+pub(crate) async fn close_service(ctx: &DispatchCtx, config: &Config) -> Result<(), wallet::WalletCallError> {
+ register_shutdown_hook(&ctx);
let mut active = service().lock().await;
let Some(current) = active.as_ref() else {
return Ok(());
@@ -128,7 +129,7 @@ pub(crate) async fn close_service(config: &Config) -> Result<(), wallet::WalletC
Ok(())
}
-fn register_shutdown_hook() {
+fn register_shutdown_hook(ctx: &DispatchCtx, ) {
if WEB3_SHUTDOWN_HOOK_REGISTERED.swap(true, Ordering::AcqRel) {
return;
}
@@ -138,7 +139,7 @@ fn register_shutdown_hook() {
let Some(current) = active.as_ref() else {
return;
};
- let config = crate::config::rpc::load_config_with_timeout().await;
+ let config = crate::config::rpc::load_config_with_timeout(&ctx).await;
let Ok(config) = config else {
tracing::warn!(
"[modules:web3] could not load configuration to close service at shutdown"
@@ -173,14 +174,14 @@ pub(crate) struct ExecuteParams {
}
/// Prepare one implementation-owned Web3 quote.
-pub(crate) async fn quote(
+pub(crate) async fn quote(ctx: &DispatchCtx,
config: &Config,
owner: Option<QuoteOwner>,
member: &'static str,
params: serde_json::Value,
) -> Result<Web3QuoteResponse, wallet::WalletCallError> {
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
let service_handle = active
.as_ref()
.expect("ensure_service installs a handle")
@@ -206,14 +207,14 @@ pub(crate) async fn quote(
}
/// Call the module-owned authenticated-backend route operation.
-pub(crate) async fn routes(config: &Config) -> Result<serde_json::Value, wallet::WalletCallError> {
+pub(crate) async fn routes(ctx: &DispatchCtx, config: &Config) -> Result<serde_json::Value, wallet::WalletCallError> {
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
wallet::call(config, methods::WEB3_ROUTES, ()).await
}
/// Execute one explicitly confirmed quote using its module-declared signer chain.
-pub(crate) async fn execute(
+pub(crate) async fn execute(ctx: &DispatchCtx,
config: &Config,
owner: Option<QuoteOwner>,
quote_id: String,
@@ -225,7 +226,7 @@ pub(crate) async fn execute(
));
}
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
let service_handle = active
.as_ref()
.expect("ensure_service installs a handle")
@@ -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(&ctx, 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.rs
index e216b3bf60..b25a9eadfb 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;
@@ -20,22 +21,22 @@ use super::wallet::{self, WalletCallError};
/// Prepare and sign a 402 challenge inside TinyWallet. Both supported rails'
/// secret material is sent only through the attested confidential call; the
/// module parses the challenge and selects the matching chain.
-pub(crate) async fn prepare_payment(
+pub(crate) async fn prepare_payment(ctx: &DispatchCtx,
config: &Config,
url: String,
payment_required: String,
owner: Option<tinywallet_bus::wire::QuoteOwner>,
) -> Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError> {
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
let service_handle = active
.as_ref()
.ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?
.handle
.clone();
- let evm = signing_secret(config, crate::web3::wallet::WalletChain::Evm).await?;
- let solana = signing_secret(config, crate::web3::wallet::WalletChain::Solana).await?;
+ let evm = signing_secret(&ctx, config, crate::web3::wallet::WalletChain::Evm).await?;
+ let solana = signing_secret(&ctx, config, crate::web3::wallet::WalletChain::Solana).await?;
let mut request = X402PreparePaymentRequest {
service: service_handle.clone(),
url,
@@ -73,11 +74,11 @@ pub(crate) async fn record_payment(
.await
}
-async fn signing_secret(
+async fn signing_secret(ctx: &DispatchCtx,
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(&ctx, chain)
.await
.map_err(WalletCallError::Failed)?;
let phrase =
@@ -106,13 +107,13 @@ fn service() -> &'static tokio::sync::Mutex<Option<X402Service>> {
X402_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))
}
-async fn ensure_service(
+async fn ensure_service(ctx: &DispatchCtx,
config: &Config,
active: &mut Option<X402Service>,
) -> Result<(), WalletCallError> {
- register_shutdown_hook();
+ register_shutdown_hook(&ctx);
let workspace = config.workspace_dir.clone();
- let accounts = super::wallet_host::wallet_accounts_snapshot()
+ let accounts = super::wallet_host::wallet_accounts_snapshot(&ctx)
.await
.map_err(WalletCallError::Failed)?;
let budget = budget_from(|name| std::env::var(name).ok());
@@ -175,8 +176,8 @@ async fn ensure_service(
/// Close the active module ledger on sign-out after joining any current
/// operation. If close fails, the handle stays cached so a later lifecycle
/// attempt can retry instead of silently abandoning pending reservations.
-pub(crate) async fn close_service(config: &Config) -> Result<(), WalletCallError> {
- register_shutdown_hook();
+pub(crate) async fn close_service(ctx: &DispatchCtx, config: &Config) -> Result<(), WalletCallError> {
+ register_shutdown_hook(&ctx);
let mut active = service().lock().await;
let Some(current) = active.as_ref() else {
return Ok(());
@@ -193,7 +194,7 @@ pub(crate) async fn close_service(config: &Config) -> Result<(), WalletCallError
Ok(())
}
-fn register_shutdown_hook() {
+fn register_shutdown_hook(ctx: &DispatchCtx, ) {
if X402_SHUTDOWN_HOOK_REGISTERED.swap(true, Ordering::AcqRel) {
return;
}
@@ -203,7 +204,7 @@ fn register_shutdown_hook() {
let Some(current) = active.as_ref() else {
return;
};
- let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {
+ let Ok(config) = crate::config::rpc::load_config_with_timeout(&ctx).await else {
tracing::warn!(
"[modules:x402] could not load configuration to close service at shutdown"
);
@@ -226,13 +227,13 @@ fn register_shutdown_hook() {
});
}
-async fn with_service<R, F, Fut>(config: &Config, operation: F) -> Result<R, WalletCallError>
+async fn with_service<R, F, Fut>(ctx: &DispatchCtx, config: &Config, operation: F) -> Result<R, WalletCallError>
where
F: FnOnce(X402ServiceHandle) -> Fut,
Fut: std::future::Future<Output = Result<R, WalletCallError>>,
{
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
let handle = active
.as_ref()
.ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?
@@ -277,14 +278,14 @@ pub(crate) async fn list_payments(
}
/// Update live module-owned spending limits without replacing the ledger.
-pub(crate) async fn update_budget(
+pub(crate) async fn update_budget(ctx: &DispatchCtx,
config: &Config,
per_request_max_atomic: Option<u64>,
daily_max_atomic: Option<u64>,
monthly_max_atomic: Option<u64>,
) -> Result<tinywallet_bus::wire::X402SpendingSummary, WalletCallError> {
let mut active = service().lock().await;
- ensure_service(config, &mut active).await?;
+ ensure_service(&ctx, config, &mut active).await?;
let current = active
.as_mut()
.ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?;
diff --git a/crates/openhuman-core/src/platform/cost/schemas.rs b/crates/openhuman-core/src/platform/cost/schemas.rs
index 44e2ae5e88..d2c6aa4993 100644
--- a/crates/openhuman-core/src/platform/cost/schemas.rs
+++ b/crates/openhuman-core/src/platform/cost/schemas.rs
@@ -224,11 +224,11 @@ fn new_correlation_id() -> String {
uuid::Uuid::new_v4().simple().to_string()[..8].to_string()
}
-fn handle_cost_get_dashboard(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_cost_get_dashboard(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_dashboard.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_dashboard.config_load_failed err={err}");
})?;
let outcome = cost_rpc::dashboard(&config).map_err(|e| {
@@ -243,13 +243,13 @@ fn handle_cost_get_dashboard(_ctx: DispatchCtx, _params: Map<String, Value>) ->
}
fn handle_cost_get_daily_history(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_daily_history.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_daily_history.config_load_failed err={err}");
})?;
let payload = if params.is_empty() {
@@ -277,11 +277,11 @@ fn handle_cost_get_daily_history(
})
}
-fn handle_cost_get_summary(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_cost_get_summary(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_summary.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_summary.config_load_failed err={err}");
})?;
let outcome = cost_rpc::summary(&config).map_err(|e| {
@@ -295,11 +295,11 @@ fn handle_cost_get_summary(_ctx: DispatchCtx, _params: Map<String, Value>) -> Co
})
}
-fn handle_cost_get_usage_log(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_cost_get_usage_log(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_usage_log.entry");
- let config = config_rpc::load_config_with_timeout().await.inspect_err(|err| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.inspect_err(|err| {
log::warn!(target: "cost_rpc", "[cost_rpc][{cid}] cost_get_usage_log.config_load_failed err={err}");
})?;
let payload = if params.is_empty() {
@@ -340,11 +340,11 @@ fn parse_report_params<T: serde::de::DeserializeOwned + Default>(
serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))
}
-fn handle_cost_report(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_cost_report(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_report.entry");
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p: ReportParams = parse_report_params(params)?;
let days = p.days.unwrap_or_else(default_usage_days);
let outcome = cost_rpc::usage_report(&config, days, &p.group_by, &p.filter)
@@ -353,11 +353,11 @@ fn handle_cost_report(_ctx: DispatchCtx, params: Map<String, Value>) -> Controll
})
}
-fn handle_cost_cache_report(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_cost_cache_report(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let cid = new_correlation_id();
log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_cache_report.entry");
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p: CacheReportParams = parse_report_params(params)?;
let days = p.days.unwrap_or_else(default_usage_days);
let limit = p.limit.unwrap_or(200);
diff --git a/crates/openhuman-core/src/platform/doctor/schemas.rs b/crates/openhuman-core/src/platform/doctor/schemas.rs
index 4ae4731251..abf92d3be5 100644
--- a/crates/openhuman-core/src/platform/doctor/schemas.rs
+++ b/crates/openhuman-core/src/platform/doctor/schemas.rs
@@ -70,16 +70,16 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_report(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_report(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::doctor::rpc::doctor_report(&config).await?)
})
}
-fn handle_models(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_models(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let use_cache = read_optional::<bool>(&params, "use_cache")?.unwrap_or(true);
to_json(crate::platform::doctor::rpc::doctor_models(&config, use_cache).await?)
})
diff --git a/crates/openhuman-core/src/platform/service/schemas.rs b/crates/openhuman-core/src/platform/service/schemas.rs
index b3aa35bf01..71d76a5ed1 100644
--- a/crates/openhuman-core/src/platform/service/schemas.rs
+++ b/crates/openhuman-core/src/platform/service/schemas.rs
@@ -175,17 +175,17 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_install(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_install(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::service_install(&config).await?)
})
}
/// Service controller for `service.start`.
-fn handle_start(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_start(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::service_start(&config).await?)
})
}
@@ -227,25 +227,25 @@ fn handle_shutdown(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerF
}
/// Service controller for `service.stop`.
-fn handle_stop(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_stop(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::service_stop(&config).await?)
})
}
/// Service controller for `service.status`.
-fn handle_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::service_status(&config).await?)
})
}
/// Service controller for `service.uninstall`.
-fn handle_uninstall(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_uninstall(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::service_uninstall(&config).await?)
})
}
@@ -256,19 +256,19 @@ struct DaemonHostSetParams {
}
/// Service controller for `service.daemon_host_get`.
-fn handle_daemon_host_get(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_daemon_host_get(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::daemon_host_get(&config).await?)
})
}
/// Service controller for `service.daemon_host_set`.
-fn handle_daemon_host_set(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_daemon_host_set(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let payload: DaemonHostSetParams =
serde_json::from_value(Value::Object(params)).map_err(|e| e.to_string())?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::platform::service::rpc::daemon_host_set(&config, payload.show_tray).await?)
})
}
diff --git a/crates/openhuman-core/src/platform/socket/event_handlers.rs b/crates/openhuman-core/src/platform/socket/event_handlers.rs
index 31bf7756a4..8472c1988c 100644
--- a/crates/openhuman-core/src/platform/socket/event_handlers.rs
+++ b/crates/openhuman-core/src/platform/socket/event_handlers.rs
@@ -4,6 +4,7 @@
//! to the event bus for domain-specific handling. Webhook routing lives in
//! `webhooks::bus`, channel inbound processing lives in `channels::bus`.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use serde_json::json;
@@ -21,7 +22,7 @@ use super::manager::{emit_server_event, emit_state_change, SharedState};
// ---------------------------------------------------------------------------
/// Route a Socket.IO event to the appropriate handler based on its name.
-pub(super) fn handle_sio_event(
+pub(super) fn handle_sio_event(ctx: &DispatchCtx,
event_name: &str,
data: serde_json::Value,
_emit_tx: &mpsc::UnboundedSender<String>,
@@ -246,6 +247,7 @@ pub(super) fn handle_sio_event(
} else {
#[cfg(feature = "voice")]
tokio::spawn(crate::voice::realtime_harness::handle_voice_harness_turn(
+ &ctx,
correlation_id,
messages,
));
diff --git a/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs b/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs
index 9eb9003afb..63be405721 100644
--- a/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/event_handlers_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use parking_lot::RwLock;
use serde_json::json;
@@ -84,7 +85,7 @@ fn parse_sio_event_returns_none_when_json_invalid() {
fn handle_sio_event_ready_sets_connected() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_sio_event("ready", json!({}), &tx, &shared);
+ handle_sio_event(&DispatchCtx::process_default(), "ready", json!({}), &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Connected);
}
@@ -92,7 +93,7 @@ fn handle_sio_event_ready_sets_connected() {
fn handle_sio_event_error_sets_error_status() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_sio_event("error", json!({"msg":"oops"}), &tx, &shared);
+ handle_sio_event(&DispatchCtx::process_default(), "error", json!({"msg":"oops"}), &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Error);
}
@@ -115,6 +116,7 @@ fn handle_sio_event_debug_truncation_respects_utf8_boundary() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
handle_sio_event(
+ &DispatchCtx::process_default(),
"weird.unrelated.event",
serde_json::Value::String(inner),
&tx,
@@ -128,7 +130,7 @@ fn handle_sio_event_unknown_event_is_noop_on_status() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
// Start disconnected — an unhandled event must not flip status.
- handle_sio_event("weird.unrelated.event", json!({}), &tx, &shared);
+ handle_sio_event(&DispatchCtx::process_default(), "weird.unrelated.event", json!({}), &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
}
@@ -137,7 +139,7 @@ fn handle_sio_event_channel_message_missing_channel_is_dropped() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
// No "channel" field → the dispatcher must return without touching status.
- handle_sio_event("telegram:message", json!({"message": "hi"}), &tx, &shared);
+ handle_sio_event(&DispatchCtx::process_default(), "telegram:message", json!({"message": "hi"}), &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
}
@@ -146,6 +148,7 @@ fn handle_sio_event_channel_message_empty_text_is_dropped() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
handle_sio_event(
+ &DispatchCtx::process_default(),
"telegram:message",
json!({"channel": "tg:123", "message": " "}),
&tx,
@@ -203,6 +206,6 @@ fn handle_sio_event_payload_redacted_no_panic_on_multibyte_boundary() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
// Any event name exercises the pre-match log path. Must not panic.
- handle_sio_event("anything.unhandled", payload, &tx, &shared);
+ handle_sio_event(&DispatchCtx::process_default(), "anything.unhandled", payload, &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
}
diff --git a/crates/openhuman-core/src/platform/socket/manager_tests.rs b/crates/openhuman-core/src/platform/socket/manager_tests.rs
index c60a133d5a..0327c97379 100644
--- a/crates/openhuman-core/src/platform/socket/manager_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/manager_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use serde_json::json;
@@ -191,6 +192,7 @@ async fn emit_still_succeeds_after_server_error_on_live_connection() {
// to the readiness flag, which is owned by the connection loop.
let (sink_tx, _sink_rx) = mpsc::unbounded_channel::<String>();
super::super::event_handlers::handle_sio_event(
+ &DispatchCtx::process_default(),
"error",
json!({ "message": "boom" }),
&sink_tx,
diff --git a/crates/openhuman-core/src/platform/socket/ops.rs b/crates/openhuman-core/src/platform/socket/ops.rs
index 737ff73ff6..7224198b05 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,9 +50,9 @@ 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(crate::config::rpc::load_config_with_timeout().await?);
+ let config = std::sync::Arc::new(crate::config::rpc::load_config_with_timeout(&ctx).await?);
let api_url = crate::backend::require_base_url(&config.api_url)?;
let token = crate::security::credentials::session_support::get_session_token(&config)
.map_err(|e| format!("failed to read session token: {e}"))?
diff --git a/crates/openhuman-core/src/platform/socket/schemas.rs b/crates/openhuman-core/src/platform/socket/schemas.rs
index 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/socket/ws_loop/connect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
index 9ac49a9ce9..b1c144c4a7 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
@@ -2,6 +2,7 @@
//! Engine.IO/Socket.IO handshake reads, and a single connection's full
//! event loop ([`run_connection`]).
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use parking_lot::Mutex;
@@ -80,7 +81,7 @@ pub(super) struct ReconnectContext {
/// during the upgrade (see `connect_with_redirects`) is pinned for the next
/// reconnect attempt — we don't want to re-hit the redirect every time the
/// loop backs off and retries.
-pub(super) async fn run_connection(
+pub(super) async fn run_connection(ctx: &DispatchCtx,
ws_url: &mut String,
token: &str,
shared: &Arc<SharedState>,
@@ -234,7 +235,7 @@ pub(super) async fn run_connection(
if frame.starts_with('2') {
pings_received = pings_received.saturating_add(1);
}
- handle_eio_message(frame, internal_tx, shared);
+ handle_eio_message(&ctx, frame, internal_tx, shared);
}
Some(Ok(WsMessage::Ping(data))) => {
sent_since_last_frame = 0;
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs
index b853ed596d..d4f7b625b3 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/dispatch.rs
@@ -1,6 +1,7 @@
//! Incoming-message dispatch: Engine.IO framing and Socket.IO packet/ack
//! parsing.
+use crate::core::runtime::DispatchCtx;
use crate::platform::socket::manager::emit_state_change;
use crate::platform::socket::types::ConnectionStatus;
use std::sync::Arc;
@@ -13,7 +14,7 @@ use crate::platform::socket::event_handlers::{handle_sio_event, parse_sio_event}
use crate::platform::socket::manager::SharedState;
/// Handle an incoming Engine.IO text message by its type prefix.
-pub(super) fn handle_eio_message(
+pub(super) fn handle_eio_message(ctx: &DispatchCtx,
text: &str,
emit_tx: &mpsc::UnboundedSender<String>,
shared: &Arc<SharedState>,
@@ -33,7 +34,7 @@ pub(super) fn handle_eio_message(
b'4' => {
// Engine.IO MESSAGE → contains Socket.IO packet
if text.len() > 1 {
- handle_sio_packet(&text[1..], emit_tx, shared);
+ handle_sio_packet(&ctx, &text[1..], emit_tx, shared);
}
}
b'1' => {
@@ -52,7 +53,7 @@ pub(super) fn handle_eio_message(
}
/// Handle a Socket.IO packet (after stripping the Engine.IO '4' prefix).
-pub(super) fn handle_sio_packet(
+pub(super) fn handle_sio_packet(ctx: &DispatchCtx,
text: &str,
emit_tx: &mpsc::UnboundedSender<String>,
shared: &Arc<SharedState>,
@@ -65,7 +66,7 @@ pub(super) fn handle_sio_packet(
b'2' => {
// Socket.IO EVENT: 2["eventName", data]
if let Some((event_name, data)) = parse_sio_event(&text[1..]) {
- handle_sio_event(&event_name, data, emit_tx, shared);
+ handle_sio_event(&ctx, &event_name, data, emit_tx, shared);
} else {
log::warn!(
"[socket] Failed to parse SIO EVENT: {}",
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
index b57738b087..fe0f644a9d 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
@@ -1,6 +1,7 @@
//! The reconnect loop: [`ws_loop`], its failure-escalation logging, the
//! invalid-token retry decision, and the emit-queue drain used on shutdown.
+use crate::core::runtime::DispatchCtx;
use std::sync::atomic::Ordering;
use std::sync::Arc;
@@ -57,7 +58,7 @@ impl Drop for LoopActiveGuard<'_> {
/// fails with "Invalid token") the loop escalates immediately — it does
/// **not** waste the remaining back-off attempts on a provably dead token.
/// This is the fix for TAURI-RUST-9C (#2892).
-pub(crate) async fn ws_loop(
+pub(crate) async fn ws_loop(ctx: &DispatchCtx,
url: String,
token_provider: TokenProvider,
shared: Arc<SharedState>,
@@ -171,6 +172,7 @@ pub(crate) async fn ws_loop(
// from the `Connected after …` line (Codex review on #6270).
let attempt_started = Instant::now();
let outcome = run_connection(
+ &ctx,
&mut ws_url,
&token,
&shared,
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
index 3b9d74ccad..d388b9c7d6 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use super::*;
use crate::platform::socket::types::ConnectionStatus;
@@ -119,7 +120,7 @@ fn redirect_warning_is_recorded_once_and_pinned_to_first_hop() {
fn handle_eio_message_ping_sends_pong() {
let shared = make_shared();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- handle_eio_message("2", &tx, &shared);
+ handle_eio_message(&DispatchCtx::process_default(), "2", &tx, &shared);
let msg = rx.try_recv().expect("pong should be sent");
assert_eq!(msg, "3");
}
@@ -128,7 +129,7 @@ fn handle_eio_message_ping_sends_pong() {
fn handle_eio_message_pong_is_ignored() {
let shared = make_shared();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- handle_eio_message("3", &tx, &shared);
+ handle_eio_message(&DispatchCtx::process_default(), "3", &tx, &shared);
assert!(rx.try_recv().is_err(), "pong must not trigger a reply");
}
@@ -136,7 +137,7 @@ fn handle_eio_message_pong_is_ignored() {
fn handle_eio_message_empty_is_noop() {
let shared = make_shared();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
- handle_eio_message("", &tx, &shared);
+ handle_eio_message(&DispatchCtx::process_default(), "", &tx, &shared);
assert!(rx.try_recv().is_err());
}
@@ -147,7 +148,7 @@ fn handle_eio_message_message_routes_to_sio_packet() {
// `4` + `1` = Engine.IO MESSAGE + SIO DISCONNECT — should flip state.
*shared.status.write() = ConnectionStatus::Connected;
*shared.socket_id.write() = Some("old-sid".into());
- handle_eio_message("41", &tx, &shared);
+ handle_eio_message(&DispatchCtx::process_default(), "41", &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
assert!(shared.socket_id.read().is_none());
}
@@ -156,9 +157,9 @@ fn handle_eio_message_message_routes_to_sio_packet() {
fn handle_eio_message_close_and_noop_do_not_panic() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_eio_message("1", &tx, &shared); // CLOSE from server
- handle_eio_message("6", &tx, &shared); // NOOP
- handle_eio_message("9", &tx, &shared); // unknown
+ handle_eio_message(&DispatchCtx::process_default(), "1", &tx, &shared); // CLOSE from server
+ handle_eio_message(&DispatchCtx::process_default(), "6", &tx, &shared); // NOOP
+ handle_eio_message(&DispatchCtx::process_default(), "9", &tx, &shared); // unknown
}
#[test]
@@ -170,7 +171,7 @@ fn handle_eio_message_unknown_packet_is_utf8_safe_at_preview_boundary() {
let packet = format!("9{}{}", "a".repeat(28), "魔");
assert!(!packet.is_char_boundary(30));
- handle_eio_message(&packet, &tx, &shared);
+ handle_eio_message(&DispatchCtx::process_default(), &packet, &tx, &shared);
log::set_max_level(previous_max_level);
}
@@ -182,7 +183,7 @@ fn handle_sio_packet_event_dispatches_to_event_handler() {
let (tx, _rx) = mpsc::unbounded_channel::<String>();
*shared.status.write() = ConnectionStatus::Disconnected;
// `2` = SIO EVENT, payload is a "ready" event → should flip to Connected.
- handle_sio_packet(r#"2["ready",{}]"#, &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), r#"2["ready",{}]"#, &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Connected);
}
@@ -211,7 +212,7 @@ fn handle_sio_packet_event_with_unparseable_payload_is_logged_only() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
*shared.status.write() = ConnectionStatus::Disconnected;
- handle_sio_packet("2not-json", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "2not-json", &tx, &shared);
// Unparseable SIO events must not change status.
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
}
@@ -225,7 +226,7 @@ fn handle_sio_packet_unparseable_event_is_utf8_safe_at_preview_boundary() {
let packet = format!("2{}{}", "a".repeat(78), "魔");
assert!(!packet.is_char_boundary(80));
- handle_sio_packet(&packet, &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), &packet, &tx, &shared);
log::set_max_level(previous_max_level);
}
@@ -238,7 +239,7 @@ fn handle_sio_packet_unknown_type_is_utf8_safe_at_preview_boundary() {
let packet = format!("9{}{}", "a".repeat(28), "魔");
assert!(!packet.is_char_boundary(30));
- handle_sio_packet(&packet, &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), &packet, &tx, &shared);
log::set_max_level(previous_max_level);
}
@@ -247,7 +248,7 @@ fn handle_sio_packet_connect_reack_updates_sid() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
assert!(shared.socket_id.read().is_none());
- handle_sio_packet(r#"0{"sid":"new-sid-123"}"#, &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), r#"0{"sid":"new-sid-123"}"#, &tx, &shared);
assert_eq!(shared.socket_id.read().as_deref(), Some("new-sid-123"));
}
@@ -255,7 +256,7 @@ fn handle_sio_packet_connect_reack_updates_sid() {
fn handle_sio_packet_connect_reack_missing_sid_is_noop() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_sio_packet("0", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "0", &tx, &shared);
assert!(shared.socket_id.read().is_none());
}
@@ -265,7 +266,7 @@ fn handle_sio_packet_disconnect_flips_status_and_clears_sid() {
let (tx, _rx) = mpsc::unbounded_channel::<String>();
*shared.status.write() = ConnectionStatus::Connected;
*shared.socket_id.write() = Some("sid-x".into());
- handle_sio_packet("1", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "1", &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Disconnected);
assert!(shared.socket_id.read().is_none());
}
@@ -274,15 +275,15 @@ fn handle_sio_packet_disconnect_flips_status_and_clears_sid() {
fn handle_sio_packet_connect_error_does_not_panic() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_sio_packet("4", &tx, &shared);
- handle_sio_packet(r#"4{"message":"nope"}"#, &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "4", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), r#"4{"message":"nope"}"#, &tx, &shared);
}
#[test]
fn handle_sio_packet_empty_is_noop() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
- handle_sio_packet("", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "", &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Connected);
}
@@ -291,7 +292,7 @@ fn handle_sio_packet_unknown_type_is_noop() {
let shared = make_shared();
let (tx, _rx) = mpsc::unbounded_channel::<String>();
*shared.status.write() = ConnectionStatus::Connected;
- handle_sio_packet("9abc", &tx, &shared);
+ handle_sio_packet(&DispatchCtx::process_default(), "9abc", &tx, &shared);
assert_eq!(*shared.status.read(), ConnectionStatus::Connected);
}
diff --git a/crates/openhuman-core/src/platform/update/ops.rs b/crates/openhuman-core/src/platform/update/ops.rs
index be02910376..2d31353a0c 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,15 +10,15 @@ 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> {
- config::rpc::load_config_with_timeout()
+async fn load_update_policy(ctx: &DispatchCtx, ) -> Result<UpdateConfig, String> {
+ config::rpc::load_config_with_timeout(&ctx)
.await
.map(|cfg| cfg.update)
.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"
);
@@ -177,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(
@@ -341,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>,
@@ -351,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.rs
index 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/schemas.rs b/crates/openhuman-core/src/platform/update/schemas.rs
index 103301a1bc..e33e10189d 100644
--- a/crates/openhuman-core/src/platform/update/schemas.rs
+++ b/crates/openhuman-core/src/platform/update/schemas.rs
@@ -130,8 +130,8 @@ fn handle_check(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFut
Box::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 { to_json(crate::platform::update::rpc::update_run(&ctx).await) })
}
fn handle_apply(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
diff --git a/crates/openhuman-core/src/profiles/host_tests.rs b/crates/openhuman-core/src/profiles/host_tests.rs
index 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.rs
index 52247b4858..53c6e601e7 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.
@@ -57,7 +58,7 @@ pub async fn command_requires_sandbox(sandbox_mode: Option<SandboxMode>) -> Resu
if matches!(sandbox_mode, Some(SandboxMode::Sandboxed)) {
return Ok(true);
}
- let config = crate::config::ops::load_config_with_timeout().await?;
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
if config_disables_sandbox(&config) {
return Ok(false);
}
@@ -73,14 +74,14 @@ 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> {
if crate::core::runtime::is_saas() {
return crate::profiles::tools::sandbox_policy(action_dir, state_dir);
}
- let config = crate::config::ops::load_config_with_timeout()
+ let config = crate::config::ops::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("Cannot read sandbox configuration: {error}"))?;
let mut policy = resolve_sandbox_policy(
@@ -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
@@ -232,7 +233,7 @@ pub async fn create_sandbox_backend(policy: &SandboxPolicy) -> SandboxBackendHan
backend_id: None,
});
}
- let config = match crate::config::ops::load_config_with_timeout().await {
+ let config = match crate::config::ops::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(_) if policy.backend == SandboxBackendKind::Docker => {
return docker_error_handle();
@@ -285,20 +286,20 @@ 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 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,
@@ -317,7 +318,7 @@ pub(crate) async fn execute_in_sandbox_metered(
let explicitly_requested = if crate::core::runtime::is_saas() || sandbox_disabled_by_host() {
false
} else {
- let config = crate::config::ops::load_config_with_timeout()
+ let config = crate::config::ops::load_config_with_timeout(&ctx)
.await
.map_err(|e| anyhow::anyhow!("Cannot read sandbox configuration: {e}"))?;
module_config = Some(config.clone());
@@ -349,7 +350,7 @@ pub(crate) async fn execute_in_sandbox_metered(
crate::config::ensure_usable_cwd(working_dir)?;
let config = match module_config {
Some(config) => config,
- None => crate::config::ops::load_config_with_timeout()
+ None => crate::config::ops::load_config_with_timeout(&ctx)
.await
.map_err(|error| {
anyhow::anyhow!("Cannot read module configuration: {error}")
@@ -370,7 +371,7 @@ pub(crate) async fn execute_in_sandbox_metered(
crate::config::ensure_usable_cwd(working_dir)?;
let config = match module_config {
Some(config) => config,
- None => crate::config::ops::load_config_with_timeout()
+ None => crate::config::ops::load_config_with_timeout(&ctx)
.await
.map_err(|error| {
anyhow::anyhow!("Cannot read module configuration: {error}")
@@ -399,7 +400,7 @@ pub(crate) async fn execute_in_sandbox_metered(
};
let config = match module_config {
Some(config) => config,
- None => crate::config::ops::load_config_with_timeout()
+ None => crate::config::ops::load_config_with_timeout(&ctx)
.await
.map_err(|error| {
anyhow::anyhow!("Cannot read module configuration: {error}")
diff --git a/crates/openhuman-core/src/sandbox/ops_tests.rs b/crates/openhuman-core/src/sandbox/ops_tests.rs
index e225b222ce..a9d57fbb60 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);
}
@@ -207,6 +208,7 @@ async fn execute_in_sandbox_none_backend() {
false,
);
let result = execute_in_sandbox(
+ &DispatchCtx::process_default(),
&policy,
"echo sandbox-test",
Path::new("/tmp"),
@@ -282,6 +284,7 @@ async fn execute_in_sandbox_none_backend_runs_on_every_os() {
false,
);
let result = execute_in_sandbox(
+ &DispatchCtx::process_default(),
&policy,
"echo sandbox-test",
tempdir.path(),
@@ -354,7 +357,7 @@ async fn sandbox_off_component_forces_the_unsandboxed_fallback_and_no_module_loa
crate::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/sandbox/schemas.rs b/crates/openhuman-core/src/sandbox/schemas.rs
index 9bc50c3f4b..f14a84085d 100644
--- a/crates/openhuman-core/src/sandbox/schemas.rs
+++ b/crates/openhuman-core/src/sandbox/schemas.rs
@@ -168,7 +168,7 @@ pub fn schemas(function: &str) -> ControllerSchema {
/// requested name — so `backend:"docker"` on a native-config host reports Local,
/// matching what a real session on that host would run. Reporting the requested
/// backend instead was the conflation fixed in #6081.
-fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
let backend_str = params
@@ -195,7 +195,7 @@ fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
// and the mounted workspace, not the compiled-in `RuntimeConfig::default()`
// (#6081). A failed config load surfaces to the caller rather than
// silently answering from defaults.
- let config = match config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(err) => {
log::warn!("[sandbox] handle_status config load failed error={err}");
@@ -225,7 +225,7 @@ fn handle_status(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})
}
-fn handle_resolve_policy(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_resolve_policy(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
let mode_str = params
@@ -248,7 +248,7 @@ fn handle_resolve_policy(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
// and the user's action dir, not the compiled-in `RuntimeConfig::default()`
// and `default_action_dir()` (#6081). A failed config load surfaces to
// the caller rather than silently answering from defaults.
- let config = match config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(err) => {
log::warn!("[sandbox] handle_resolve_policy config load failed error={err}");
@@ -284,10 +284,10 @@ fn handle_resolve_policy(_ctx: DispatchCtx, params: Map<String, Value>) -> Contr
})
}
-fn handle_cleanup_orphans(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_cleanup_orphans(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
gate()?;
- let config = match crate::config::ops::load_config_with_timeout().await {
+ let config = match crate::config::ops::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(error) => return Err(error),
};
@@ -301,7 +301,7 @@ fn handle_cleanup_orphans(_ctx: DispatchCtx, _params: Map<String, Value>) -> Con
})
}
-fn handle_validate_policy(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_validate_policy(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
gate()?;
let policy_val = params.get("policy").cloned().unwrap_or(Value::Null);
@@ -309,7 +309,7 @@ fn handle_validate_policy(_ctx: DispatchCtx, params: Map<String, Value>) -> Cont
Ok(p) => p,
Err(e) => return Err(format!("Invalid policy: {e}")),
};
- let config = crate::config::ops::load_config_with_timeout().await?;
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
// The module owns the verdict; a missing one is an error, never "valid".
let issues = super::docker::validate_docker_policy(&config, &policy)
.await
diff --git a/crates/openhuman-core/src/search/bus.rs b/crates/openhuman-core/src/search/bus.rs
index 987bbae5e2..2d5c19a5ef 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 crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient()).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 9ba37f5044..0dca08701d 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,10 +117,10 @@ 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 => crate::config::rpc::load_config_with_timeout()
+ None => crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| anyhow::anyhow!(error)),
}
@@ -244,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.rs
index 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.rs
index 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(&params, "request_id")?;
let decision_str = read_required_string(&params, "decision")?;
@@ -221,7 +221,7 @@ fn handle_decide(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFut
})?;
let agent_id = read_optional_string(&params, "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.rs
index f622181e03..b7e731acce 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;
@@ -55,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;
}
}
@@ -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;
};
@@ -86,7 +87,7 @@ impl SessionExpiredSubscriber {
// turns out to be a local offline session (never truly expired).
scheduler_gate::set_signed_out(true);
- match crate::config::rpc::load_config_with_timeout().await {
+ match crate::config::rpc::load_config_with_timeout(&ctx).await {
Ok(config) => {
// An API-key runtime has no session to clear: a backend 401 on
// the key is a per-call error for the caller, not a sign-out.
@@ -129,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.rs
index 71a5a9a897..a52135e98d 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]
@@ -38,6 +39,7 @@ async fn session_expired_in_saas_returns_before_any_teardown() {
tokio::time::timeout(
std::time::Duration::from_secs(1),
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.rs
index 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.rs
index 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.rs
index af6176828b..828e25e7ad 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};
@@ -180,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> {
@@ -269,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());
@@ -296,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())
}
@@ -376,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> {
@@ -411,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,
@@ -505,16 +506,16 @@ 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")]
- if let Err(error) = crate::modules::web3_service::close_service(config).await {
+ if let Err(error) = crate::modules::web3_service::close_service(&ctx, config).await {
tracing::warn!(%error, "{LOG_PREFIX} failed to close Web3 service during sign-out");
logs.push("Web3 service cleanup will retry on replacement or shutdown".into());
}
#[cfg(feature = "web3")]
- if let Err(error) = crate::modules::x402_service::close_service(config).await {
+ if let Err(error) = crate::modules::x402_service::close_service(&ctx, config).await {
tracing::warn!(%error, "{LOG_PREFIX} failed to close x402 service during sign-out");
logs.push("x402 service cleanup will retry on replacement or shutdown".into());
}
@@ -551,7 +552,7 @@ async fn clear_session_credential(config: &Config) -> Result<Outcome<bool>, Stri
// Every process-global store must follow the now-active pre-login
// workspace, or a signed-out caller keeps reading the previous account's
// context until the process restarts.
- match crate::config::load_config_with_timeout().await {
+ match crate::config::load_config_with_timeout(&ctx).await {
Ok(signed_out_config) => {
logs.extend(rebind_after_credential_change(
&signed_out_config,
@@ -572,13 +573,14 @@ async fn clear_session_credential(config: &Config) -> Result<Outcome<bool>, Stri
/// 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(
+ &ctx,
config,
SetCredentialRequest {
token: token.to_string(),
@@ -593,8 +595,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 one
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 37ae57e98e..4050ccc868 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,8 +110,8 @@ 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> {
- crate::config::load_config_with_timeout()
+pub(super) async fn reload_config_or(ctx: &DispatchCtx, _fallback: &Config) -> Result<Config, String> {
+ crate::config::load_config_with_timeout(&ctx)
.await
.map_err(|error| error.to_string())
}
diff --git a/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs b/crates/openhuman-core/src/security/credentials/ops_credential_tests.rs
index adac89a47a..69d3ea7ddb 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;
@@ -20,6 +21,7 @@ async fn same_token_refresh_preserves_issuing_backend_and_refuses_rebinding() {
)
.unwrap();
let state = set_credential(
+ &DispatchCtx::process_default(),
&config,
SetCredentialRequest {
token: "synthetic-session".into(),
@@ -35,6 +37,7 @@ async fn same_token_refresh_preserves_issuing_backend_and_refuses_rebinding() {
Some("https://issuer.example")
);
let error = set_credential(
+ &DispatchCtx::process_default(),
&config,
SetCredentialRequest {
token: "synthetic-session".into(),
@@ -96,9 +99,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"));
}
@@ -107,6 +110,7 @@ async fn set_credential_rejects_unknown_kind() {
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp);
let err = set_credential(
+ &DispatchCtx::process_default(),
&config,
SetCredentialRequest {
token: "x".into(),
@@ -127,7 +131,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,7 +150,7 @@ 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}");
@@ -222,7 +226,7 @@ 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;
@@ -258,7 +262,7 @@ async fn set_credential_with_the_same_token_and_user_is_a_cheap_refresh() {
assert!(first.logs.join(" ").contains("user directory activated"));
// The host's `/auth/me` answer arrives: same token, same user.
- let user_config = crate::config::load_config_with_timeout().await.unwrap();
+ let user_config = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
let second = store_session(
&user_config,
&token,
@@ -288,6 +292,7 @@ async fn set_credential_for_a_different_user_signs_the_previous_one_out_first()
let config = test_config(&tmp);
let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp();
store_session(
+ &DispatchCtx::process_default(),
&config,
&jwt_with_payload(json!({ "sub": "alice", "exp": exp })),
None,
@@ -295,8 +300,9 @@ 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 alice_config = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
let result = store_session(
+ &DispatchCtx::process_default(),
&alice_config,
&jwt_with_payload(json!({ "sub": "bob", "exp": exp })),
None,
@@ -328,6 +334,7 @@ async fn set_and_clear_api_key_credential() {
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp);
let state = set_credential(
+ &DispatchCtx::process_default(),
&config,
SetCredentialRequest {
token: "sk-live".into(),
@@ -342,7 +349,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;
@@ -377,8 +384,9 @@ async fn clearing_the_session_preserves_a_coexisting_api_key() {
// 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();
+ let user_scoped = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
set_credential(
+ &DispatchCtx::process_default(),
&user_scoped,
SetCredentialRequest {
token: "sk-live".into(),
@@ -394,7 +402,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;
@@ -404,7 +412,7 @@ async fn clearing_the_session_preserves_a_coexisting_api_key() {
// The process is now back on the pre-login/signed-out config. The key
// must be readable — and `auth.get_state` must report it — from there,
// not stranded under the deactivated user directory.
- let signed_out = crate::config::load_config_with_timeout().await.unwrap();
+ let signed_out = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
assert_ne!(
signed_out.config_path, user_scoped.config_path,
"sign-out must have rebound to a different (pre-login) config"
@@ -447,8 +455,9 @@ 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();
+ let pre_login = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
set_credential(
+ &DispatchCtx::process_default(),
&pre_login,
SetCredentialRequest {
token: "sk-stale-a".into(),
@@ -472,8 +481,9 @@ async fn clearing_the_session_preserves_the_active_key_over_a_stale_destination_
.unwrap();
// Key B is the one actually active while the session is up.
- let user_scoped = crate::config::load_config_with_timeout().await.unwrap();
+ let user_scoped = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
set_credential(
+ &DispatchCtx::process_default(),
&user_scoped,
SetCredentialRequest {
token: "sk-live-b".into(),
@@ -490,11 +500,11 @@ 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();
- let signed_out = crate::config::load_config_with_timeout().await.unwrap();
+ let signed_out = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
assert_eq!(
api_key::get_api_key(&signed_out).unwrap().as_deref(),
Some("sk-live-b"),
@@ -523,8 +533,9 @@ async fn clearing_without_a_kind_removes_a_user_scoped_api_key_at_its_source() {
.await
.unwrap();
- let user_scoped = crate::config::load_config_with_timeout().await.unwrap();
+ let user_scoped = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
set_credential(
+ &DispatchCtx::process_default(),
&user_scoped,
SetCredentialRequest {
token: "sk-live".into(),
@@ -536,7 +547,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!(
@@ -550,7 +561,7 @@ async fn clearing_without_a_kind_removes_a_user_scoped_api_key_at_its_source() {
"the api key must be gone from its real (user-scoped) location, not just the \
post-teardown config clear_credential ends up using"
);
- let signed_out = crate::config::load_config_with_timeout().await.unwrap();
+ let signed_out = crate::config::load_config_with_timeout(&DispatchCtx::process_default()).await.unwrap();
assert!(!api_key::has_api_key(&signed_out));
assert!(
!auth_get_state(&signed_out)
@@ -569,6 +580,7 @@ async fn clear_credential_without_a_kind_removes_everything() {
let _home = EnvVarGuard::set("HOME", tmp.path());
let config = test_config(&tmp);
set_credential(
+ &DispatchCtx::process_default(),
&config,
SetCredentialRequest {
token: "sk-live".into(),
@@ -578,7 +590,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 +615,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!(
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.rs
index 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)
.await
diff --git a/crates/openhuman-core/src/security/credentials/schemas.rs b/crates/openhuman-core/src/security/credentials/schemas.rs
index e65134d714..774b4b8ceb 100644
--- a/crates/openhuman-core/src/security/credentials/schemas.rs
+++ b/crates/openhuman-core/src/security/credentials/schemas.rs
@@ -193,18 +193,18 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_auth_set_credential(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_auth_set_credential(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).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?)
})
}
-fn handle_auth_clear_credential(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_auth_clear_credential(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload = deserialize_params::<AuthClearCredentialParams>(params)?;
let kind = match payload
.kind
@@ -218,33 +218,33 @@ 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?)
})
}
-fn handle_auth_get_state(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_auth_get_state(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::security::credentials::rpc::auth_get_state(&config).await?)
})
}
fn handle_auth_get_session_token(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::security::credentials::rpc::auth_get_session_token_json(&config).await?)
})
}
fn handle_auth_store_provider_credentials(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload = deserialize_params::<AuthStoreProviderCredentialsParams>(params)?;
to_json(
crate::security::credentials::rpc::store_provider_credentials(
@@ -261,11 +261,11 @@ fn handle_auth_store_provider_credentials(
}
fn handle_auth_remove_provider_credentials(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload = deserialize_params::<AuthRemoveProviderCredentialsParams>(params)?;
to_json(
crate::security::credentials::rpc::remove_provider_credentials(
@@ -279,11 +279,11 @@ fn handle_auth_remove_provider_credentials(
}
fn handle_auth_list_provider_credentials(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let payload = if params.is_empty() {
AuthListProviderCredentialsParams::default()
} else {
diff --git a/crates/openhuman-core/src/security/credentials/session_support.rs b/crates/openhuman-core/src/security/credentials/session_support.rs
index 3dda8f5463..e9ba933e81 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,8 +66,8 @@ 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 {
- let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {
+pub async fn current_session_is_local(ctx: &DispatchCtx, ) -> bool {
+ let Ok(config) = crate::config::rpc::load_config_with_timeout(&ctx).await else {
return false;
};
get_session_token(&config)
diff --git a/crates/openhuman-core/src/security/devices/bus.rs b/crates/openhuman-core/src/security/devices/bus.rs
index c2410c5ac4..bca154239e 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;
@@ -94,7 +95,7 @@ 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(),
@@ -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,
@@ -393,7 +394,7 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
// Load config from global env (best-effort; pairing persists even if config
// loading is slow — the UI will see the device on next list call).
- if let Ok(config) = crate::config::rpc::load_config_with_timeout().await {
+ if let Ok(config) = crate::config::rpc::load_config_with_timeout(&ctx).await {
match store::insert_device(
&config,
channel_id,
diff --git a/crates/openhuman-core/src/security/devices/owner.rs b/crates/openhuman-core/src/security/devices/owner.rs
index 738366f698..05cf4631d3 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,8 +63,8 @@ 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> {
- let config = crate::config::rpc::load_config_with_timeout()
+async fn has_live_device(ctx: &DispatchCtx, channel_id: &str) -> Result<bool, String> {
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("load config: {error}"))?;
super::store::get_device(&config, channel_id)
@@ -73,8 +74,8 @@ 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> {
- let config = crate::config::rpc::load_config_with_timeout()
+async fn is_revoked(ctx: &DispatchCtx, channel_id: &str) -> Result<bool, String> {
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("load config: {error}"))?;
super::store::get_device(&config, channel_id)
@@ -94,7 +95,7 @@ async fn is_revoked(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> {
@@ -109,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()),
@@ -128,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),
@@ -142,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.rs
index 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_CIPHERS
diff --git a/crates/openhuman-core/src/security/devices/schemas.rs b/crates/openhuman-core/src/security/devices/schemas.rs
index 02b922b2c7..32971b16a5 100644
--- a/crates/openhuman-core/src/security/devices/schemas.rs
+++ b/crates/openhuman-core/src/security/devices/schemas.rs
@@ -150,24 +150,24 @@ pub fn schemas(function: &str) -> ControllerSchema {
// Handler bridges
// ---------------------------------------------------------------------------
-fn handle_create_pairing(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_create_pairing(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let label = read_optional_string(&params, "label")?;
to_json(crate::security::devices::rpc::devices_create_pairing(&config, label).await?)
})
}
-fn handle_list(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::security::devices::rpc::devices_list(&config).await?)
})
}
-fn handle_revoke(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_revoke(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let channel_id = read_required::<String>(&params, "channel_id")?;
to_json(crate::security::devices::rpc::devices_revoke(&config, channel_id).await?)
})
diff --git a/crates/openhuman-core/src/security/encryption/schemas.rs b/crates/openhuman-core/src/security/encryption/schemas.rs
index 29f528a5af..5dc294c571 100644
--- a/crates/openhuman-core/src/security/encryption/schemas.rs
+++ b/crates/openhuman-core/src/security/encryption/schemas.rs
@@ -75,17 +75,17 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_encrypt_secret(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_encrypt_secret(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let plaintext = read_required::<String>(&params, "plaintext")?;
to_json(crate::security::encryption::rpc::encrypt_secret(&config, &plaintext).await?)
})
}
-fn handle_decrypt_secret(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_decrypt_secret(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let ciphertext = read_required::<String>(&params, "ciphertext")?;
to_json(crate::security::encryption::rpc::decrypt_secret(&config, &ciphertext).await?)
})
diff --git a/crates/openhuman-core/src/security/keyring_consent/ops.rs b/crates/openhuman-core/src/security/keyring_consent/ops.rs
index 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.rs
index 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.rs
index 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.rs b/crates/openhuman-core/src/security/ops.rs
index b46fdb7849..4e72883380 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,8 +25,8 @@ 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> {
- let config = crate::config::ops::load_config_with_timeout().await?;
+pub async fn load_and_get_security_policy_info(ctx: &DispatchCtx, ) -> Result<Outcome<serde_json::Value>, String> {
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
Ok(security_policy_info_for_config(&config))
}
diff --git a/crates/openhuman-core/src/security/ops_tests.rs b/crates/openhuman-core/src/security/ops_tests.rs
index 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.rs
index c889f34fd7..807ad9c75d 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 {
+fn handle_policy_info(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async {
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/skills/webhooks/bus.rs b/crates/openhuman-core/src/skills/webhooks/bus.rs
index bb90c16222..ba2509c229 100644
--- a/crates/openhuman-core/src/skills/webhooks/bus.rs
+++ b/crates/openhuman-core/src/skills/webhooks/bus.rs
@@ -5,6 +5,7 @@
//! echo target), waits for the response, and emits it back through the socket.
//! This decouples the socket module from webhook routing logic.
+use crate::core::runtime::DispatchCtx;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::platform::socket::global_socket_manager;
@@ -130,7 +131,7 @@ impl EventHandler<DomainEvent> for WebhookRequestSubscriber {
tokio::spawn(async move {
let result =
tokio::time::timeout(std::time::Duration::from_secs(60), async {
- run_agent_trigger(&envelope).await
+ run_agent_trigger(&DispatchCtx::ambient(), &envelope).await
})
.await;
let (resp, err) = match result {
@@ -301,10 +302,10 @@ fn decode_webhook_body(base64_body: &str) -> Result<serde_json::Value, String> {
/// Run the triage pipeline for a trigger envelope and return the
/// human-readable decision summary on success.
-async fn run_agent_trigger(
+async fn run_agent_trigger(ctx: &DispatchCtx,
envelope: &crate::agent::triage::TriggerEnvelope,
) -> Result<String, String> {
- let outcome = crate::agent::triage::run_triage(envelope)
+ let outcome = crate::agent::triage::run_triage(&ctx, envelope)
.await
.map_err(|e| format!("triage evaluation failed: {e}"))?;
diff --git a/crates/openhuman-core/src/skills/webhooks/ops.rs b/crates/openhuman-core/src/skills/webhooks/ops.rs
index 4456ef24c3..15794a59b5 100644
--- a/crates/openhuman-core/src/skills/webhooks/ops.rs
+++ b/crates/openhuman-core/src/skills/webhooks/ops.rs
@@ -1,3 +1,4 @@
+use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::skills::webhooks::{
WebhookDebugLogListResult, WebhookDebugLogsClearedResult, WebhookDebugRegistrationsResult,
@@ -128,7 +129,7 @@ pub async fn register_agent(
/// Trigger the triage/agent pipeline directly via RPC without requiring
/// an incoming webhook request. Useful for testing and manual escalation.
-pub async fn trigger_agent(
+pub async fn trigger_agent(ctx: &DispatchCtx,
source: &str,
caller_id: &str,
reason: &str,
@@ -155,7 +156,7 @@ pub async fn trigger_agent(
let outcome = tokio::time::timeout(
std::time::Duration::from_secs(60),
- crate::agent::triage::run_triage(&envelope),
+ crate::agent::triage::run_triage(&ctx, &envelope),
)
.await
.map_err(|_| "triage timed out after 60s".to_string())?
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index bd0e912330..f9183fe372 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,11 +152,11 @@ 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();
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| ThreadsError::Message(format!("load config: {error}")))?;
let persistence_dir = workspace_dir().await.map_err(ThreadsError::Message)?;
@@ -404,10 +405,10 @@ 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 = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|e| format!("load config: {e}"))?;
run_to_completion("thread_delete", thread_delete_inner(config, request)).await
diff --git a/crates/openhuman-core/src/threads/ops_conversion_tests.rs b/crates/openhuman-core/src/threads/ops_conversion_tests.rs
index 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.rs
index 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.rs
index 1f87506756..fc8762cc4e 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};
@@ -241,6 +242,7 @@ impl EventHandler<DomainEvent> for ConversationPersistenceSubscriber {
return;
}
if let Err(error) = persist_channel_turn(
+ &DispatchCtx::ambient(),
&my_workspace,
ChannelTurnDescriptor {
channel,
@@ -299,6 +301,7 @@ impl EventHandler<DomainEvent> for ConversationPersistenceSubscriber {
return;
}
if let Err(error) = persist_channel_turn(
+ &DispatchCtx::ambient(),
&my_workspace,
ChannelTurnDescriptor {
channel,
@@ -347,7 +350,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> {
@@ -356,7 +359,7 @@ async fn persist_channel_turn(
let client = crate::channels::module_fixture::client().await;
#[cfg(not(all(test, feature = "channels", feature = "modules")))]
let client = {
- let config = crate::config::rpc::load_config_with_timeout().await?;
+ let config = crate::config::rpc::load_config_with_timeout(&ctx).await?;
if config.workspace_dir != workspace_dir {
return Err("channel workspace changed".into());
}
diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rs
index fc752f12d2..3adaeb57d0 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")]
@@ -47,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)
}
@@ -290,7 +291,7 @@ mod x402 {
.ok_or_else(|| {
"402 response is missing a valid PAYMENT-REQUIRED header".to_string()
})?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&DispatchCtx::ambient())
.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 64b2767337..c5e57e99b0 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 = crate::config::ops::load_config_with_timeout()
+ loaded = crate::config::ops::load_config_with_timeout(&DispatchCtx::ambient())
.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 97e30a2f23..87f5decdee 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;
@@ -263,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(
@@ -272,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> {
@@ -297,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);
@@ -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>,
@@ -596,7 +597,7 @@ impl ShellTool {
);
let config = match self.analysis_config.as_deref() {
Some(config) => config.clone(),
- None => match crate::config::ops::load_config_with_timeout().await {
+ None => match crate::config::ops::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(e) => {
return (
diff --git a/crates/openhuman-core/src/tools/impl/system/update_apply.rs b/crates/openhuman-core/src/tools/impl/system/update_apply.rs
index 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/composio.rs b/crates/openhuman-core/src/tools/schemas/composio.rs
index 847625ddae..27b6a6c2ac 100644
--- a/crates/openhuman-core/src/tools/schemas/composio.rs
+++ b/crates/openhuman-core/src/tools/schemas/composio.rs
@@ -8,7 +8,7 @@ use crate::core::all::ControllerFuture;
use crate::core::Outcome;
pub(super) fn handle_composio_execute(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
@@ -19,7 +19,7 @@ pub(super) fn handle_composio_execute(
.ok_or_else(|| "missing required `action`".to_string())?;
let action_args = params.get("params").cloned();
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
// The connector module owns the mode split (backend proxy vs. the
// user's personal direct tenant, #1710); this only supplies the config.
let resp = crate::integrations::composio::execute_dispatch::execute_composio_action(
diff --git a/crates/openhuman-core/src/tools/schemas/web_search.rs b/crates/openhuman-core/src/tools/schemas/web_search.rs
index 14d5404b11..7a8d799403 100644
--- a/crates/openhuman-core/src/tools/schemas/web_search.rs
+++ b/crates/openhuman-core/src/tools/schemas/web_search.rs
@@ -29,12 +29,12 @@ 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,
) -> Result<Value, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
run_role_tool_with(&config, tool, arguments, method).await
}
@@ -151,20 +151,21 @@ fn search_arguments(params: &Map<String, Value>, provider: Option<&str>) -> Resu
Ok(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(&params, 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(&params, Some("searxng"))?;
run_role_tool(
+ &ctx,
tinysearch_bus::tools::WEB_SEARCH,
arguments,
"searxng_search",
@@ -173,7 +174,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(&params, "query")?;
let mut arguments = json!({ "query": query });
@@ -190,12 +191,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 {
@@ -212,6 +213,7 @@ pub(super) fn handle_web_contents(
}
tracing::debug!(urls = urls.len(), "[rpc][tools.web_contents] request");
run_role_tool(
+ &ctx,
tinysearch_bus::tools::WEB_CONTENTS,
arguments,
"web_contents",
diff --git a/crates/openhuman-core/src/voice/live/schemas.rs b/crates/openhuman-core/src/voice/live/schemas.rs
index 5492e66a83..35e7521433 100644
--- a/crates/openhuman-core/src/voice/live/schemas.rs
+++ b/crates/openhuman-core/src/voice/live/schemas.rs
@@ -118,34 +118,34 @@ struct TestParams {
provider: String,
}
-fn handle_live_providers(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_live_providers(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_value(ops::live_providers(&config).value)
})
}
-fn handle_live_settings_get(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_live_settings_get(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_value(ops::live_settings_get(&config).value)
})
}
-fn handle_live_settings_set(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_live_settings_set(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let patch: LiveSettingsPatch = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
to_value(ops::live_settings_set(&mut config, patch).await?.value)
})
}
-fn handle_live_test_provider(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_live_test_provider(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let params: TestParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_value(
ops::live_test_provider(&config, &params.provider)
.await
diff --git a/crates/openhuman-core/src/voice/realtime_harness/agent.rs b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
index 37bc2c519d..b0725f5cca 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/agent.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
@@ -3,6 +3,7 @@
//! history, run under the hard per-turn ceiling with the same chat-scoped
//! approval surface web chat installs.
+use crate::core::runtime::DispatchCtx;
use std::time::Duration;
use log::{info, warn};
@@ -69,13 +70,13 @@ const VOICE_MODEL: &str = "hint:chat";
/// under the hard per-turn ceiling, then detach the sink so the forwarder's
/// channel closes. Runs entirely on the background task, so the ack deadline in
/// the caller covers both the build and the model round-trips.
-pub(super) async fn run_voice_turn(
+pub(super) async fn run_voice_turn(ctx: &DispatchCtx,
correlation_id: &str,
messages: &[Value],
prompt: &str,
progress_tx: tokio::sync::mpsc::Sender<AgentProgress>,
) -> Result<String, String> {
- let mut agent = build_voice_agent(correlation_id, messages, prompt).await?;
+ let mut agent = build_voice_agent(&ctx, correlation_id, messages, prompt).await?;
// Attach the streaming sink before the turn: its presence switches the harness
// onto the true per-token streaming path, and each `AgentProgress::TextDelta`
@@ -92,12 +93,12 @@ pub(super) async fn run_voice_turn(
/// Construct the per-turn voice orchestrator: load config, pin the fast voice
/// model, isolate the transcript namespace, and seed the relayed history.
-async fn build_voice_agent(
+async fn build_voice_agent(ctx: &DispatchCtx,
correlation_id: &str,
messages: &[Value],
prompt: &str,
) -> Result<OpenHumanSessionHost, String> {
- let config = crate::config::ops::load_config_with_timeout().await?;
+ let config = crate::config::ops::load_config_with_timeout(&ctx).await?;
let mut agent = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
.map_err(|e| format!("orchestrator build failed: {e}"))?;
agent.set_event_context(format!("voice_{correlation_id}"), "voice_agent");
@@ -112,7 +113,7 @@ async fn build_voice_agent(
// so follow-ups like "what about tomorrow?" keep their context. No-ops when
// there is nothing prior to the current user message.
let history = messages_to_history_pairs(messages);
- if let Err(e) = agent.seed_resume_from_messages(history, prompt) {
+ if let Err(e) = agent.seed_resume_from_messages(&ctx, history, prompt) {
warn!("[voice-harness] seed prior messages failed correlation={correlation_id}: {e}");
}
@@ -126,7 +127,7 @@ async fn build_voice_agent(
/// Run the orchestrator turn under the hard per-turn ceiling. The streaming sink
/// must already be attached; deltas flow out while this runs.
-async fn run_single_with_timeout(
+async fn run_single_with_timeout(ctx: &DispatchCtx,
agent: &mut OpenHumanSessionHost,
correlation_id: &str,
prompt: &str,
@@ -145,6 +146,7 @@ async fn run_single_with_timeout(
};
agent.set_thread_id(Some(VOICE_CHAT_THREAD_ID));
let scoped_run = agent.run_single_with_approval(
+ &ctx,
prompt,
None,
crate::security::approval::ApprovalTurnContext::chat(approval_ctx),
diff --git a/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
index 96f1d80f4d..66e090ec09 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
@@ -2,6 +2,7 @@
//! the relay socket, race the turn against the spoken-ack deadline, and hand
//! a slow turn off to chat delivery in the background.
+use crate::core::runtime::DispatchCtx;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
@@ -132,7 +133,7 @@ impl Drop for InFlightGuard {
/// background and delivers its answer into the user's in-app chat. Never panics —
/// every failure path emits `voice:harness:error` (or a clean `done`) so the
/// backend relay ends the turn cleanly.
-pub async fn handle_voice_harness_turn(correlation_id: String, messages: Vec<Value>) {
+pub async fn handle_voice_harness_turn(ctx: &DispatchCtx, correlation_id: String, messages: Vec<Value>) {
let prompt = extract_prompt(&messages);
if prompt.trim().is_empty() {
emit_error(&correlation_id, "no user message in the relayed turn").await;
@@ -232,7 +233,7 @@ pub async fn handle_voice_harness_turn(correlation_id: String, messages: Vec<Val
return;
}
};
- let outcome = run_voice_turn(&turn_cid, &turn_messages, &turn_prompt, progress_tx).await;
+ let outcome = run_voice_turn(&ctx, &turn_cid, &turn_messages, &turn_prompt, progress_tx).await;
// Hand the result to the foreground. If it already deferred (dropped the
// receiver at the ack deadline), the send fails and we deliver the reply
// into the user's chat instead.
diff --git a/crates/openhuman-core/src/voice/schemas/handlers/provider_server.rs b/crates/openhuman-core/src/voice/schemas/handlers/provider_server.rs
index a37d8dc7fe..517313042c 100644
--- a/crates/openhuman-core/src/voice/schemas/handlers/provider_server.rs
+++ b/crates/openhuman-core/src/voice/schemas/handlers/provider_server.rs
@@ -20,12 +20,12 @@ use crate::voice::schemas::params::{
// ---------------------------------------------------------------------------
pub(crate) fn handle_voice_set_providers(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<SetProvidersParams>(params)?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
if let Some(stt) = p
.stt_provider
@@ -83,7 +83,7 @@ pub(crate) fn handle_voice_set_providers(
}
pub(crate) fn handle_voice_update_provider_settings(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
@@ -94,7 +94,7 @@ pub(crate) fn handle_voice_update_provider_settings(
use tinyinference_voice::external_tts::TtsApiStyle;
let p = deserialize_params::<VoiceUpdateProviderSettingsParams>(params)?;
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
if let Some(providers) = p.voice_providers {
let mut new_entries = Vec::with_capacity(providers.len());
@@ -238,12 +238,12 @@ pub(crate) fn handle_voice_update_provider_settings(
}
pub(crate) fn handle_voice_list_models(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<VoiceListModelsParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let provider_id = p.provider_id.trim();
let capability = p.capability.as_deref().unwrap_or("both");
@@ -306,12 +306,12 @@ pub(crate) fn handle_voice_list_models(
}
pub(crate) fn handle_voice_test_provider(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = deserialize_params::<VoiceTestProviderParams>(params)?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let start = std::time::Instant::now();
log::debug!(
@@ -425,14 +425,14 @@ pub(crate) fn handle_voice_test_provider(
// ---------------------------------------------------------------------------
pub(crate) fn handle_voice_server_start(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
use crate::voice::server::{global_server, VoiceServerConfig};
use tinyvoice_bus::hotkey::ActivationMode;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let hotkey = params
.get("hotkey")
diff --git a/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs b/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs
index c5b0514ae2..aaed38760c 100644
--- a/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs
+++ b/crates/openhuman-core/src/voice/schemas/handlers/transcribe_tts.rs
@@ -15,11 +15,11 @@ use crate::voice::schemas::params::{
};
pub(crate) fn handle_voice_status(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::voice::voice_status(&config).await?)
})
}
@@ -27,21 +27,21 @@ pub(crate) fn handle_voice_status(
/// Mint a realtime voice-agent signed WebSocket URL (#5399). Takes no params —
/// the agent is server-configured; the desktop only asks for a fresh signed URL.
pub(crate) fn handle_voice_agent_signed_url(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
_params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
to_json(crate::voice::realtime::mint_voice_agent_signed_url(&config).await?)
})
}
pub(crate) fn handle_voice_transcribe(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<TranscribeParams>(params)?;
to_json(
crate::voice::voice_transcribe(
@@ -56,11 +56,11 @@ pub(crate) fn handle_voice_transcribe(
}
pub(crate) fn handle_voice_transcribe_bytes(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<TranscribeBytesParams>(params)?;
to_json(
crate::voice::voice_transcribe_bytes(
@@ -75,20 +75,20 @@ pub(crate) fn handle_voice_transcribe_bytes(
})
}
-pub(crate) fn handle_voice_tts(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+pub(crate) fn handle_voice_tts(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<TtsParams>(params)?;
to_json(crate::voice::voice_tts(&config, &p.text, p.output_path.as_deref()).await?)
})
}
pub(crate) fn handle_voice_reply_synthesize(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<ReplySynthesizeParams>(params)?;
// Dispatch through the TTS factory so the user's `tts_provider`
// setting (cloud / piper / …) is honored on the spoken-reply path,
@@ -132,11 +132,11 @@ pub(crate) fn handle_voice_reply_synthesize(
}
pub(crate) fn handle_voice_cloud_transcribe(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<CloudTranscribeParams>(params)?;
let opts = tinyinference_voice::cloud::CloudTranscribeOptions {
model: p.model,
@@ -152,11 +152,11 @@ pub(crate) fn handle_voice_cloud_transcribe(
}
pub(crate) fn handle_voice_stt_dispatch(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<SttDispatchParams>(params)?;
let provider_name = p
.provider
@@ -196,11 +196,11 @@ pub(crate) fn handle_voice_stt_dispatch(
}
pub(crate) fn handle_voice_tts_dispatch(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let p = deserialize_params::<TtsDispatchParams>(params)?;
let provider_name = p
.provider
diff --git a/crates/openhuman-core/src/web3/bridge/schemas.rs b/crates/openhuman-core/src/web3/bridge/schemas.rs
index c76de358d9..58244b9d49 100644
--- a/crates/openhuman-core/src/web3/bridge/schemas.rs
+++ b/crates/openhuman-core/src/web3/bridge/schemas.rs
@@ -92,10 +92,11 @@ pub fn schema(function: &str) -> ControllerSchema {
}
}
-fn handle_quote(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_quote(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let quote = web3_service::quote(
+ &ctx,
&config,
None,
methods::WEB3_BRIDGE_QUOTE,
@@ -107,12 +108,12 @@ fn handle_quote(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
})
}
-fn handle_execute(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_execute(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let config = config_rpc::load_config_with_timeout().await?;
- let result = web3_service::execute(&config, None, parsed.quote_id, parsed.confirmed)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let result = web3_service::execute(&ctx, &config, None, parsed.quote_id, parsed.confirmed)
.await
.map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
diff --git a/crates/openhuman-core/src/web3/dapp/schemas.rs b/crates/openhuman-core/src/web3/dapp/schemas.rs
index d8d9defa80..dc40360b06 100644
--- a/crates/openhuman-core/src/web3/dapp/schemas.rs
+++ b/crates/openhuman-core/src/web3/dapp/schemas.rs
@@ -75,10 +75,11 @@ pub fn schema(function: &str) -> ControllerSchema {
}
}
-fn handle_call(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_call(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let quote = web3_service::quote(
+ &ctx,
&config,
None,
methods::WEB3_DAPP_QUOTE,
@@ -90,12 +91,12 @@ fn handle_call(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutur
})
}
-fn handle_execute(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_execute(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let config = config_rpc::load_config_with_timeout().await?;
- let result = web3_service::execute(&config, None, parsed.quote_id, parsed.confirmed)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let result = web3_service::execute(&ctx, &config, None, parsed.quote_id, parsed.confirmed)
.await
.map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
diff --git a/crates/openhuman-core/src/web3/module_tools.rs b/crates/openhuman-core/src/web3/module_tools.rs
index d810d63b74..3b17c4b8cb 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};
@@ -35,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(
@@ -45,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(
@@ -60,17 +61,18 @@ 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> {
let owner = crate::modules::web3_service::owner_of(chat);
- let config = match crate::config::rpc::load_config_with_timeout().await {
+ let config = match crate::config::rpc::load_config_with_timeout(&ctx).await {
Ok(config) => config,
Err(error) => return Ok(ToolResult::error(error)),
};
let result: anyhow::Result<Value> = match self.name() {
"web3_swap_quote" => crate::modules::web3_service::quote(
+ &ctx,
&config,
owner.clone(),
tinywallet_bus::names::methods::WEB3_SWAP_QUOTE,
@@ -80,6 +82,7 @@ impl Web3ModuleTool {
.map_err(|error| anyhow::anyhow!(error.to_string()))
.and_then(|value| serde_json::to_value(value).map_err(Into::into)),
"web3_bridge_quote" => crate::modules::web3_service::quote(
+ &ctx,
&config,
owner.clone(),
tinywallet_bus::names::methods::WEB3_BRIDGE_QUOTE,
@@ -89,6 +92,7 @@ impl Web3ModuleTool {
.map_err(|error| anyhow::anyhow!(error.to_string()))
.and_then(|value| serde_json::to_value(value).map_err(Into::into)),
"web3_dapp_call" => crate::modules::web3_service::quote(
+ &ctx,
&config,
owner.clone(),
tinywallet_bus::names::methods::WEB3_DAPP_QUOTE,
@@ -97,12 +101,13 @@ impl Web3ModuleTool {
.await
.map_err(|error| anyhow::anyhow!(error.to_string()))
.and_then(|value| serde_json::to_value(value).map_err(Into::into)),
- "web3_swap_routes" => crate::modules::web3_service::routes(&config)
+ "web3_swap_routes" => crate::modules::web3_service::routes(&ctx, &config)
.await
.map_err(|error| anyhow::anyhow!(error.to_string())),
"web3_swap_execute" | "web3_bridge_execute" | "web3_dapp_execute" => {
match serde_json::from_value::<crate::modules::web3_service::ExecuteParams>(args) {
Ok(params) => crate::modules::web3_service::execute(
+ &ctx,
&config,
owner,
params.quote_id,
diff --git a/crates/openhuman-core/src/web3/swap/schemas.rs b/crates/openhuman-core/src/web3/swap/schemas.rs
index 300d921d1d..46415425b9 100644
--- a/crates/openhuman-core/src/web3/swap/schemas.rs
+++ b/crates/openhuman-core/src/web3/swap/schemas.rs
@@ -103,10 +103,11 @@ fn unknown_schema() -> ControllerSchema {
}
}
-fn handle_quote(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_quote(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let quote = web3_service::quote(
+ &ctx,
&config,
None,
methods::WEB3_SWAP_QUOTE,
@@ -118,12 +119,12 @@ fn handle_quote(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFutu
})
}
-fn handle_execute(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_execute(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let config = config_rpc::load_config_with_timeout().await?;
- let result = web3_service::execute(&config, None, parsed.quote_id, parsed.confirmed)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let result = web3_service::execute(&ctx, &config, None, parsed.quote_id, parsed.confirmed)
.await
.map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
@@ -131,10 +132,10 @@ fn handle_execute(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFu
})
}
-fn handle_routes(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_routes(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = config_rpc::load_config_with_timeout().await?;
- let routes = web3_service::routes(&config)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let routes = web3_service::routes(&ctx, &config)
.await
.map_err(|error| error.to_string())?;
Outcome::new(routes, vec!["web3 supported routes listed".to_string()])
diff --git a/crates/openhuman-core/src/web3/wallet/execution.rs b/crates/openhuman-core/src/web3/wallet/execution.rs
index c4d52d0099..68b2c2a1a6 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,8 +20,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn network_defaults(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -38,8 +39,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn supported_assets(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<SupportedAsset>>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -57,8 +58,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn chain_status(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<ChainStatus>>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -76,8 +77,8 @@ pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {
}
/// Live native balances.
-pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn balances(ctx: &DispatchCtx, ) -> Result<Outcome<Vec<BalanceInfo>>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -95,12 +96,12 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
- let quote = wallet_service::prepare_native_transfer(&config, owner, params)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let quote = wallet_service::prepare_native_transfer(&ctx, &config, owner, params)
.await
.map_err(|error| error.to_string())?;
Ok(Outcome::new(
@@ -110,12 +111,12 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
- let result = wallet_service::execute_native_transfer(&config, owner, params)
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
+ let result = wallet_service::execute_native_transfer(&ctx, &config, owner, params)
.await
.map_err(|error| error.to_string())?;
Ok(Outcome::new(
@@ -125,12 +126,12 @@ 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,
) -> Result<Outcome<TxStatusInfo>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -153,12 +154,12 @@ 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,
) -> Result<Outcome<TxReceiptInfo>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -181,12 +182,12 @@ 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,
) -> Result<Outcome<TxLookupInfo>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let result = wallet_service::with_native_wallet(&config, |service| async {
wallet_module::call(
&config,
@@ -209,8 +210,8 @@ 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> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn encode_erc20_transfer(ctx: &DispatchCtx, to_address: &str, amount_raw: &str) -> Result<String, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
wallet_module::encode_erc20_transfer(&config, to_address, amount_raw)
.await
.map_err(|error| error.to_string())
diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs
index 60e3bcdbaf..5f488917eb 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,11 +38,11 @@ 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())?;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let generated = crate::modules::wallet::generate_mnemonic(&config, word_count)
.await
.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();
@@ -70,7 +71,7 @@ pub async fn derive_recovery_material(
));
}
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let mnemonic = Zeroizing::new(mnemonic);
let mnemonic = Zeroizing::new(mnemonic.split_whitespace().collect::<Vec<_>>().join(" "));
let seed = crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic.to_string())
@@ -114,12 +115,12 @@ 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;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let valid = match crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic).await {
Ok(mut response) => {
if response.seed.len() != 64 {
@@ -200,8 +201,8 @@ fn validate_setup(params: &WalletSetupParams) -> Result<Vec<WalletAccount>, Stri
Ok(normalized)
}
-pub async fn status() -> Result<Outcome<WalletStatus>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn status(ctx: &DispatchCtx, ) -> Result<Outcome<WalletStatus>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let _guard = WALLET_STATE_FILE_LOCK.lock();
let status = to_status(&config, load_stored_wallet_state_unlocked(&config)?);
@@ -218,8 +219,8 @@ pub async fn status() -> Result<Outcome<WalletStatus>, String> {
))
}
-pub async fn setup(params: WalletSetupParams) -> Result<Outcome<WalletStatus>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
+pub async fn setup(ctx: &DispatchCtx, params: WalletSetupParams) -> Result<Outcome<WalletStatus>, String> {
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let accounts = validate_setup(&params)?;
let encrypted_mnemonic = params
.encrypted_mnemonic
@@ -270,10 +271,10 @@ 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 = config_rpc::load_config_with_timeout().await.map_err(|e| {
+ let config = config_rpc::load_config_with_timeout(&ctx).await.map_err(|e| {
log::warn!("{LOG_PREFIX} reveal_recovery_phrase config load failed: {e}");
e
})?;
@@ -348,12 +349,12 @@ 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()
);
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
debug!(
"{LOG_PREFIX} secret_material acquiring state lock chain={}",
chain.as_str()
diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs
index 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.rs
index 03f53261a7..c9e27bdf19 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,16 +453,16 @@ 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 {
@@ -477,99 +477,99 @@ fn handle_encode_erc20_transfer(_ctx: DispatchCtx, params: Map<String, Value>) -
})
}
-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.rs
index e1411665a1..7c1a7dbcf7 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,16 +116,16 @@ 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.
let workspace_guard = set_workspace_env_for_test(temp).await;
- let config = config_rpc::load_config_with_timeout().await?;
+ let config = config_rpc::load_config_with_timeout(&ctx).await?;
let 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.rs
index be4bf5369e..f521c8eb6d 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,12 @@ 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(
+ &ctx,
query.chain,
query.evm_network,
&query.hash,
@@ -116,7 +118,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,
),
};
diff --git a/crates/openhuman-core/src/web3/x402/schemas.rs b/crates/openhuman-core/src/web3/x402/schemas.rs
index 724a031546..e9c31f794c 100644
--- a/crates/openhuman-core/src/web3/x402/schemas.rs
+++ b/crates/openhuman-core/src/web3/x402/schemas.rs
@@ -109,9 +109,9 @@ pub fn schemas(function: &str) -> ControllerSchema {
}
}
-fn handle_get_summary(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
+fn handle_get_summary(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("x402 get_summary: {error}"))?;
let summary = crate::modules::x402_service::summary(&config)
@@ -128,12 +128,12 @@ struct ListPaymentsParams {
limit: Option<u64>,
}
-fn handle_list_payments(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_list_payments(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p: ListPaymentsParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("x402 list_payments params: {e}"))?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("x402 list_payments: {error}"))?;
let limit = p.limit.unwrap_or(50).min(500);
@@ -159,12 +159,12 @@ struct UpdateBudgetParams {
monthly_max: Option<u64>,
}
-fn handle_update_budget(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
+fn handle_update_budget(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let p: UpdateBudgetParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("x402 update_budget params: {e}"))?;
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("x402 update_budget: {error}"))?;
let summary = crate::modules::x402_service::update_budget(
diff --git a/crates/openhuman-core/src/web_chat/journal_shadow.rs b/crates/openhuman-core/src/web_chat/journal_shadow.rs
index 3844b2d780..0f07cc0130 100644
--- a/crates/openhuman-core/src/web_chat/journal_shadow.rs
+++ b/crates/openhuman-core/src/web_chat/journal_shadow.rs
@@ -15,6 +15,7 @@
//! crate journals no sub-agent events at all, so every delegating turn loses
//! that subtree on replay.
+use crate::core::runtime::DispatchCtx;
fn span_projection_signature(
spans: &[tinyagents_harness::observability::trace_export::TraceSpan],
) -> Vec<String> {
@@ -99,7 +100,7 @@ fn describe_signature_divergence(live: &[String], projected: &[String]) -> Strin
)
}
-pub(super) async fn shadow_compare_journal_projection(
+pub(super) async fn shadow_compare_journal_projection(ctx: &DispatchCtx,
request_id: &str,
trace_ctx: tinyagents_harness::observability::trace_export::TraceContext,
max_iterations: u32,
@@ -115,7 +116,7 @@ pub(super) async fn shadow_compare_journal_projection(
return None;
};
- let observations = match crate::agent::tinyagents::journal::read_run_events(&journal_run_id, 0)
+ let observations = match crate::agent::tinyagents::journal::read_run_events(&ctx, &journal_run_id, 0)
.await
{
Ok(observations) => observations,
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 98fba4977e..e73f555d0c 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -3,6 +3,7 @@
//! run-queue dispatch, and the spawned turn body that delivers a response or
//! classifies and reports a failure.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use std::sync::Arc;
use tinyagents_harness::run_queue::{QueueLane, RunQueue};
@@ -160,7 +161,7 @@ pub fn start_chat<'a>(
}
#[allow(clippy::too_many_arguments)]
-async fn start_chat_inner(
+async fn start_chat_inner(ctx: &DispatchCtx,
client_id: &str,
thread_id: &str,
message: &str,
@@ -190,7 +191,7 @@ async fn start_chat_inner(
// Save originals before scanning, history, memory, or queue persistence.
// A missing config/root cannot safely accept an upload.
let mut message = if message.contains("[FILE:") || message.contains("[IMAGE:") {
- let config = crate::config::rpc::load_config_with_timeout()
+ let config = crate::config::rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| {
StartChatError::Other(format!("upload configuration unavailable: {error}"))
diff --git a/crates/openhuman-core/src/web_chat/ops/system_turn.rs b/crates/openhuman-core/src/web_chat/ops/system_turn.rs
index 1c05221f47..01257f6339 100644
--- a/crates/openhuman-core/src/web_chat/ops/system_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/system_turn.rs
@@ -14,6 +14,7 @@
//! that one — three rows — over the real history, so after a restart the
//! agent had forgotten everything but the delivery notice.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use tinyagents_harness::run_queue::RunQueue;
@@ -42,13 +43,13 @@ pub const SESSION_CHECKOUT_FAILURE: &str = "session checkout failed: ";
/// The turn is not registered in `IN_FLIGHT`: it is not interruptible by a
/// newer user message and does not interrupt one. Callers gate on idleness
/// themselves (background delivery defers while a user turn is in flight).
-pub async fn run_system_turn_on_thread(
+pub async fn run_system_turn_on_thread(ctx: &DispatchCtx,
thread_id: &str,
run_id: &str,
prompt: &str,
origin: AgentTurnOrigin,
) -> Result<String, String> {
- let config = config_rpc::load_config_with_timeout()
+ let config = config_rpc::load_config_with_timeout(&ctx)
.await
.map_err(|error| format!("{SESSION_CHECKOUT_FAILURE}{error}"))?;
let CheckedOutSession {
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index 5fa2448a1a..5239713bcd 100644
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@ -2,6 +2,7 @@
//! backstop and cooperative cancellation — plus the Sentry-suppression /
//! timeout-tagging policy applied to whatever error a guarded turn produces.
+use crate::core::runtime::DispatchCtx;
use std::time::Duration;
use tokio_util::sync::CancellationToken;
@@ -43,11 +44,11 @@ fn web_turn_deadline() -> Option<Duration> {
/// explicit `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` override still wins; otherwise the
/// default is the local turn ceiling plus a grace period, never the hosted
/// backstop, which sits below the local harness ceilings and would pre-empt them.
-async fn resolve_web_turn_deadline() -> Option<Duration> {
+async fn resolve_web_turn_deadline(ctx: &DispatchCtx, ) -> Option<Duration> {
if std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS").is_ok() {
return web_turn_deadline();
}
- let local = match crate::config::rpc::load_config_with_timeout().await {
+ let local = match crate::config::rpc::load_config_with_timeout(&ctx).await {
Ok(config) => crate::agent::tinyagents::chat_provider_is_local(&config),
Err(error) => {
log::debug!("[web-channel] backstop locality probe skipped: {error}");
@@ -223,7 +224,7 @@ fn turn_host_env(
/// scope.
///
/// [`TurnDeadline`]: tinyagents_harness::turn_deadline::TurnDeadline
-pub(crate) async fn run_turn_under_cancel_and_deadline<B, F>(
+pub(crate) async fn run_turn_under_cancel_and_deadline<B, F>(ctx: &DispatchCtx,
cancel_token: CancellationToken,
origin: crate::agent::turn_origin::AgentTurnOrigin,
approval_ctx: crate::security::approval::ApprovalChatContext,
@@ -237,7 +238,7 @@ where
thread_id: approval_ctx.thread_id.clone(),
request_id,
});
- let deadline = resolve_web_turn_deadline().await;
+ let deadline = resolve_web_turn_deadline(&ctx).await;
let (env, turn_cancellation) = turn_host_env(deadline);
run_until_stopped(
cancel_token,
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index 878271256f..9d50c8c5e4 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -3,6 +3,7 @@
//! `inference_heartbeat` liveness beat (see [`INFERENCE_HEARTBEAT_SECS`])
//! so a long silent prefill can't trip the frontend's ~120s silence timeout.
+use crate::core::runtime::DispatchCtx;
use serde_json::json;
use crate::threads::turn_state::mirror::ObserveProgress;
@@ -271,7 +272,7 @@ fn session_profile_user_attribution(config: &crate::config::Config) -> Option<St
/// agent turn loop and translates them into [`WebChannelEvent`]s tagged
/// with the correct client/thread/request IDs. The task runs until the
/// sender is dropped (i.e. when the agent turn finishes).
-pub(crate) fn spawn_progress_bridge(
+pub(crate) fn spawn_progress_bridge(ctx: &DispatchCtx,
mut rx: tokio::sync::mpsc::Receiver<crate::agent::progress::AgentProgress>,
client_id: String,
thread_id: String,
@@ -1164,6 +1165,7 @@ pub(crate) fn spawn_progress_bridge(
let live_spans = collector.spans().to_vec();
let journal_export = if let Some(trace_ctx) = journal_trace_ctx.take() {
super::journal_shadow::shadow_compare_journal_projection(
+ &ctx,
&request_id,
trace_ctx.clone(),
parent_max_iterations,
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 8e37ddb187..29151541f5 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -4,6 +4,7 @@
//! to a failed turn. Called from `start_chat` and `spawn_parallel_turn`
//! (`ops/start_chat.rs`/`ops/parallel_turn.rs`) once the message has been validated.
+use crate::core::runtime::DispatchCtx;
use std::sync::Arc;
use tinyagents_harness::run_queue::RunQueue;
@@ -25,7 +26,7 @@ use tinyinference_llm::failure::is_empty_provider_response_text;
#[cfg(any(test, debug_assertions))]
use super::ops::TEST_FORCED_RUN_CHAT_TASK_ERROR;
-pub(crate) async fn run_chat_task(
+pub(crate) async fn run_chat_task(ctx: &DispatchCtx,
client_id: &str,
thread_id: &str,
request_id: &str,
@@ -116,7 +117,7 @@ pub(crate) async fn run_chat_task(
}
}
- let mut config = config_rpc::load_config_with_timeout().await?;
+ let mut config = config_rpc::load_config_with_timeout(&ctx).await?;
// A thread started in a chosen folder acts there, not in the global
// `action_dir`. Applied before checkout so the session agent, its security
// policy (which grants `action_dir` as a trusted root) and its tools are
@@ -205,7 +206,7 @@ pub(crate) async fn run_chat_task(
// default test-thread stack — see the channels web-turn coverage tests).
#[cfg(feature = "tinymemes")]
let turn_started = std::time::Instant::now();
- let turn = Box::pin(agent.run_single_with_approval(message, Some(origin), approval));
+ let turn = Box::pin(agent.run_single_with_approval(&ctx, message, Some(origin), approval));
let mut result = match turn.await {
Ok(response) => {
// A successful turn proves the thread's balance is usable, so drop
diff --git a/crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rs b/crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rs
index 60f6e6c1cb..85cbeb3265 100644
--- a/crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rs
+++ b/crates/openhuman-core/src/web_chat/session_checkout_agents_tests.rs
@@ -41,7 +41,7 @@ async fn two_agents_with_the_same_thread_id_get_their_own_cache_slots() {
super::build_session_fingerprint(&config, None, None, "orchestrator".into(), "chat");
for (ctx, key) in [(&asha, &key_a), (&ravi, &key_b)] {
let entry = crate::web_chat::types::SessionEntry {
- agent: host_seeded_with(&config, "x"),
+ agent: host_seeded_with(&ctx, &config, "x"),
fingerprint: fingerprint.clone(),
};
CoreContext::scope(Arc::clone(ctx), async {
diff --git a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
index d8b21522d5..b7fd182463 100644
--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
@@ -6,6 +6,7 @@
//! cold-boot resume preferred over the real conversation. Routing it through
//! this checkout is what keeps one live history per thread.
+use crate::core::runtime::DispatchCtx;
use std::path::Path;
use tinyagents_session::transcript::{write_transcript, TranscriptMeta};
@@ -86,9 +87,10 @@ fn prose(history: &[TranscriptEntry]) -> Vec<String> {
.collect()
}
-pub(super) fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {
+pub(super) fn host_seeded_with(ctx: &DispatchCtx, config: &Config, marker: &str) -> OpenHumanSessionHost {
let mut host = OpenHumanSessionHost::from_config_for_agent(config, "orchestrator").unwrap();
host.seed_resume_from_messages(
+ &ctx,
vec![
("user".to_string(), marker.to_string()),
("agent".to_string(), "ok".to_string()),
@@ -140,7 +142,7 @@ async fn checkout_cold_boots_from_the_thread_transcript_and_checkin_keeps_it_war
// when the session resumes, which every turn does for itself. The
// conversation the transcript holds must come back either way.
assert!(
- agent.resume_bound_session().await.unwrap(),
+ agent.resume_bound_session(&DispatchCtx::process_default()).await.unwrap(),
"a thread with a transcript must resume"
);
let history = prose(&agent.history());
@@ -193,11 +195,11 @@ async fn checkin_if_vacant_yields_to_a_turn_that_re_cached_meanwhile() {
// A user turn finished while the system turn was running and cached its
// agent unconditionally.
- let user_turn_agent = host_seeded_with(&config, "user-turn-history");
+ let user_turn_agent = host_seeded_with(&DispatchCtx::process_default(), &config, "user-turn-history");
checkin_session_agent(&thread_id, user_turn_agent, fingerprint(&config)).await;
// The system turn must not clobber it.
- let system_turn_agent = host_seeded_with(&config, "system-turn-history");
+ let system_turn_agent = host_seeded_with(&DispatchCtx::process_default(), &config, "system-turn-history");
assert!(
!checkin_session_agent_if_vacant(&thread_id, system_turn_agent, fingerprint(&config)).await
);
@@ -215,7 +217,7 @@ async fn checkin_if_vacant_yields_to_a_turn_that_re_cached_meanwhile() {
assert_eq!(prose(&agent.history()), vec!["user-turn-history", "ok"]);
// Into a vacant slot it goes in.
- let system_turn_agent = host_seeded_with(&config, "system-turn-history");
+ let system_turn_agent = host_seeded_with(&DispatchCtx::process_default(), &config, "system-turn-history");
assert!(
checkin_session_agent_if_vacant(&thread_id, system_turn_agent, fingerprint(&config)).await
);
@@ -243,7 +245,7 @@ async fn a_fork_never_takes_or_returns_the_cached_agent() {
super::build_session_fingerprint(&config, None, None, "orchestrator".into(), "chat");
checkin_session_agent(
&thread_id,
- host_seeded_with(&config, "primary-history"),
+ host_seeded_with(&DispatchCtx::process_default(), &config, "primary-history"),
fingerprint,
)
.await;
@@ -280,7 +282,7 @@ async fn a_system_turn_adopts_the_cached_agent_and_its_fingerprint() {
super::build_session_fingerprint(&config, None, Some(0.2), "orchestrator".into(), "chat");
checkin_session_agent(
&thread_id,
- host_seeded_with(&config, "pinned-history"),
+ host_seeded_with(&DispatchCtx::process_default(), &config, "pinned-history"),
pinned.clone(),
)
.await;
@@ -566,7 +568,7 @@ async fn a_system_turn_never_adopts_an_agent_from_another_workspace() {
super::build_session_fingerprint(&config_a, None, None, "orchestrator".into(), "chat");
checkin_session_agent(
&thread_id,
- host_seeded_with(&config_a, "user-a-history"),
+ host_seeded_with(&DispatchCtx::process_default(), &config_a, "user-a-history"),
built_for_a,
)
.await;
diff --git a/crates/openhuman-core/src/web_chat/suggestions.rs b/crates/openhuman-core/src/web_chat/suggestions.rs
index d24b0b7a2c..6a434d44f4 100644
--- a/crates/openhuman-core/src/web_chat/suggestions.rs
+++ b/crates/openhuman-core/src/web_chat/suggestions.rs
@@ -28,6 +28,7 @@
//! (`agent::orchestration::background_delivery`), none of which have a
//! human waiting on suggestions for their next message.
+use crate::core::runtime::DispatchCtx;
use std::time::Duration;
use serde::Deserialize;
@@ -98,7 +99,7 @@ pub(crate) fn spawn_follow_up_suggestions(
));
}
-async fn generate_and_emit(
+async fn generate_and_emit(ctx: &DispatchCtx,
client_id: &str,
thread_id: &str,
request_id: &str,
@@ -115,7 +116,7 @@ async fn generate_and_emit(
return;
}
- let config = match config_rpc::load_config_with_timeout().await {
+ let config = match config_rpc::load_config_with_timeout(&ctx).await {
Ok(c) => c,
Err(err) => {
log::debug!(