Skip to content

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

refactor(threads): pass dispatch context by reference

Steven Enamakelc4c3e4a6186d
diff --git a/crates/openhuman-core/src/agent/attachments/mod.rs b/crates/openhuman-core/src/agent/attachments/mod.rs
index 4e5ae52db1..0124414adb 100644
--- a/crates/openhuman-core/src/agent/attachments/mod.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod.rs
@@ -168,9 +168,13 @@ pub(crate) async fn thread_action_dir(
let Some(thread_id) = thread_id.filter(|id| !id.is_empty()) else {
return Ok(config.action_dir.clone());
};
- let bound = crate::threads::ops::thread_working_dir(DispatchCtx::ambient(), threads_dir.to_path_buf(), thread_id)
- .await
- .map_err(anyhow::Error::msg)?;
+ let bound = crate::threads::ops::thread_working_dir(
+ &DispatchCtx::ambient(),
+ threads_dir.to_path_buf(),
+ thread_id,
+ )
+ .await
+ .map_err(anyhow::Error::msg)?;
Ok(bound.unwrap_or_else(|| config.action_dir.clone()))
}
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 45b9ff0e7d..953ee10e4e 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -717,7 +717,7 @@ fn persist_delivery_reply(
success: bool,
) -> Result<(), String> {
crate::threads::store::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir,
thread_id,
crate::threads::store::ConversationMessage {
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
index f12be2fb98..bd9b1d38bc 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
@@ -4,7 +4,6 @@
//! accepted. Completion/failure is reported through normal sub-agent lifecycle
//! events and, when possible, persisted in the child worker thread.
-use crate::core::runtime::DispatchCtx;
use super::subagent_abort_report::AbortReport;
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
use crate::agent::orchestration::fleet_tools::FleetToolSet;
@@ -18,6 +17,7 @@ use crate::agent::progress::AgentProgress;
use crate::agent::subagent_host::{
run_subagent_with_parent, SubagentRunOptions, SubagentRunStatus,
};
+use crate::core::runtime::DispatchCtx;
use crate::threads::store::{self as conversations, ConversationMessage};
use async_trait::async_trait;
use serde_json::json;
@@ -583,7 +583,7 @@ fn attach_workflow_proposal(
);
if let Some(thread_id) = parent_thread_id {
let persisted = conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
thread_id,
ConversationMessage {
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
index 2604aa322e..7688233e0b 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
@@ -12,13 +12,13 @@
//! Sub-agents always run in "typed" mode: a narrow archetype-specific
//! prompt with a filtered tool list, on a cheaper model where applicable.
//!
-use crate::core::runtime::DispatchCtx;
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
use crate::agent::orchestration::tools::dispatch::{incomplete_stop, stopped_subagent_result};
use crate::agent::progress::AgentProgress;
use crate::agent::subagent_host::{
run_subagent_with_parent, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,
};
+use crate::core::runtime::DispatchCtx;
use crate::threads::store::{self as conversations, ConversationMessage, CreateConversationThread};
use async_trait::async_trait;
use serde_json::json;
@@ -141,7 +141,7 @@ fn persist_worker_thread(
let now = chrono::Utc::now().to_rfc3339();
conversations::ensure_thread(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
CreateConversationThread {
id: thread_id.clone(),
@@ -156,7 +156,7 @@ fn persist_worker_thread(
.map_err(|err| format!("ensure_thread: {err}"))?;
conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
&thread_id,
ConversationMessage {
@@ -175,7 +175,7 @@ fn persist_worker_thread(
.map_err(|err| format!("append user message: {err}"))?;
conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
&thread_id,
ConversationMessage {
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs
index 03ca7434fd..bdeed5975f 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs
@@ -9,9 +9,9 @@
//! Worker threads carry a hard cap on depth: a worker thread cannot spawn
//! another worker thread.
-use crate::core::runtime::DispatchCtx;
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
use crate::agent::subagent_host::{run_subagent_with_parent, SubagentRunOptions};
+use crate::core::runtime::DispatchCtx;
use crate::threads::store as conversations;
use async_trait::async_trait;
use serde_json::json;
@@ -240,8 +240,9 @@ impl SpawnWorkerThreadTool {
"[spawn_worker_thread] invoked"
);
- let threads = conversations::list_threads(DispatchCtx::ambient(), parent.workspace_dir.clone())
- .map_err(|e| anyhow::anyhow!(e))?;
+ let threads =
+ conversations::list_threads(&DispatchCtx::ambient(), parent.workspace_dir.clone())
+ .map_err(|e| anyhow::anyhow!(e))?;
if let Some(current_thread) = threads.iter().find(|t| t.id == current_thread_id) {
let is_delegated_label = current_thread
.labels
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/worker_thread.rs b/crates/openhuman-core/src/agent/orchestration/tools/worker_thread.rs
index 6611778346..95ef1f3f8b 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/worker_thread.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/worker_thread.rs
@@ -35,7 +35,7 @@ pub(crate) fn create_worker_thread(
let now = chrono::Utc::now().to_rfc3339();
conversations::ensure_thread(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.clone(),
CreateConversationThread {
id: worker_thread_id.clone(),
@@ -56,7 +56,7 @@ pub(crate) fn create_worker_thread(
);
if let Err(err) = conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir,
&worker_thread_id,
ConversationMessage {
@@ -86,7 +86,7 @@ pub(crate) fn append_worker_user_message(
prompt: &str,
) -> Result<(), String> {
conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir,
worker_thread_id,
ConversationMessage {
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs
index 2e91114a6b..8aa32bd3c8 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/worker_mirror.rs
@@ -51,7 +51,12 @@ fn append_worker_message(
sender: sender.to_string(),
created_at: chrono::Utc::now().to_rfc3339(),
};
- if let Err(err) = append_message(DispatchCtx::ambient(), workspace_dir.to_path_buf(), thread_id, message) {
+ if let Err(err) = append_message(
+ &DispatchCtx::ambient(),
+ workspace_dir.to_path_buf(),
+ thread_id,
+ message,
+ ) {
tracing::debug!(
agent_id,
thread_id,
diff --git a/crates/openhuman-core/src/channels/host/remote_control.rs b/crates/openhuman-core/src/channels/host/remote_control.rs
index b0a620c181..3cb652f7ac 100644
--- a/crates/openhuman-core/src/channels/host/remote_control.rs
+++ b/crates/openhuman-core/src/channels/host/remote_control.rs
@@ -1,7 +1,7 @@
//! Captured host conversation and session state supplied to the channel module.
-use crate::core::runtime::DispatchCtx;
use crate::channels::context::{clear_sender_history, ChannelRuntimeContext};
+use crate::core::runtime::DispatchCtx;
use crate::threads::store::{self as conversations, CreateConversationThread};
/// Serves product-owned conversation state to the captured module runtime.
@@ -19,8 +19,11 @@ pub(crate) async fn dispatch_callback(
}
match request {
Request::ListThreads => {
- let threads = conversations::list_threads(DispatchCtx::ambient(), ctx.workspace_dir.to_path_buf())
- .map_err(|_| tinybus::Error::failed("conversation state unavailable"))?;
+ let threads = conversations::list_threads(
+ &DispatchCtx::ambient(),
+ ctx.workspace_dir.to_path_buf(),
+ )
+ .map_err(|_| tinybus::Error::failed("conversation state unavailable"))?;
Ok(Response::Threads(
threads
.into_iter()
@@ -40,7 +43,7 @@ pub(crate) async fn dispatch_callback(
return Err(tinybus::Error::failed("channel session ended"));
}
conversations::ensure_thread(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
ctx.workspace_dir.to_path_buf(),
CreateConversationThread {
id: thread.id,
diff --git a/crates/openhuman-core/src/channels/providers/relay/store.rs b/crates/openhuman-core/src/channels/providers/relay/store.rs
index 5f4ec41fe8..01b46828f9 100644
--- a/crates/openhuman-core/src/channels/providers/relay/store.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/store.rs
@@ -79,8 +79,12 @@ pub async fn record_inbound(
let id = inbound_message_id(&params.message_id);
let lock = thread_lock(workspace_dir, thread_id);
let _guard = lock.lock().await;
- let existing =
- conversations::get_messages(DispatchCtx::ambient(), workspace_dir.to_path_buf(), thread_id.to_string()).await?;
+ let existing = conversations::get_messages(
+ DispatchCtx::ambient(),
+ workspace_dir.to_path_buf(),
+ thread_id.to_string(),
+ )
+ .await?;
if existing.iter().any(|message| message.id == id) {
return Ok(Recorded::Duplicate);
}
@@ -151,8 +155,12 @@ pub async fn prior_turns(
limit: usize,
) -> Result<Vec<ChatMessage>, String> {
let current = inbound_message_id(message_id);
- let messages =
- conversations::get_messages(DispatchCtx::ambient(), workspace_dir.to_path_buf(), thread_id.to_string()).await?;
+ let messages = conversations::get_messages(
+ DispatchCtx::ambient(),
+ workspace_dir.to_path_buf(),
+ thread_id.to_string(),
+ )
+ .await?;
let rows = to_history(&messages, &current);
let skip = rows.len().saturating_sub(limit);
Ok(rows.into_iter().skip(skip).collect())
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_context.rs b/crates/openhuman-core/src/cron/scheduler/origin_context.rs
index dbb29914d8..fc3b78166f 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_context.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_context.rs
@@ -2,8 +2,8 @@
//! a bounded tail of the conversation that created the job, plus a fixed
//! preamble saying the run is unattended.
-use crate::core::runtime::DispatchCtx;
use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
use {
crate::cron::channel_bridge, tinyflows_schedule::types::CronJob,
tinyflows_schedule::types::JobOrigin,
@@ -58,7 +58,7 @@ async fn origin_messages(config: &Config, origin: &JobOrigin) -> Vec<(String, St
match origin {
JobOrigin::Web { thread_id, .. } => {
match crate::threads::store::blocking::get_messages(
- DispatchCtx::ambient(),
+ DispatchCtx::ambient(),
config.workspace_dir.clone(),
thread_id.clone(),
)
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index c903a969ca..8335d46165 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -141,8 +141,12 @@ async fn plan(
.map_err(|error| MemoryError::Engine(format!("reading chat threads failed: {error}")))?;
let mut plans = Vec::new();
for thread in listed {
- let messages = match threads::get_messages(DispatchCtx::ambient(), workspace_dir.to_path_buf(), thread.id.clone())
- .await
+ let messages = match threads::get_messages(
+ DispatchCtx::ambient(),
+ workspace_dir.to_path_buf(),
+ thread.id.clone(),
+ )
+ .await
{
Ok(messages) => messages,
Err(error) => {
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 1628fcfc7f..7c3bc9f3ca 100644
--- a/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/user_scope.rs
@@ -74,7 +74,7 @@ pub(super) fn activate_user_scope(user_id: &str) -> Result<Vec<String>, String>
// concurrent thread RPC in this process cannot interleave.
let pre_ws = pre_login_user_dir(&root_dir).join("workspace");
let pre_ws_log = pre_ws.display().to_string();
- match conversations::purge_threads(DispatchCtx::ambient(), pre_ws) {
+ match conversations::purge_threads(&DispatchCtx::ambient(), pre_ws) {
Ok(stats) => {
tracing::info!(
pre_login_workspace = %pre_ws_log,
diff --git a/crates/openhuman-core/src/threads/store/bus.rs b/crates/openhuman-core/src/threads/store/bus.rs
index 385299faf4..9316f865c8 100644
--- a/crates/openhuman-core/src/threads/store/bus.rs
+++ b/crates/openhuman-core/src/threads/store/bus.rs
@@ -403,7 +403,7 @@ async fn persist_channel_turn(
let created_at = Utc::now().to_rfc3339();
ensure_thread(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
CreateConversationThread {
id: thread_id.clone(),
@@ -417,9 +417,13 @@ async fn persist_channel_turn(
)?;
let persisted_message_id = format!("{}:{}", descriptor.role, descriptor.message_id);
- if get_messages(DispatchCtx::ambient(), workspace_dir.to_path_buf(), &thread_id)?
- .iter()
- .any(|message| message.id == persisted_message_id)
+ if get_messages(
+ &DispatchCtx::ambient(),
+ workspace_dir.to_path_buf(),
+ &thread_id,
+ )?
+ .iter()
+ .any(|message| message.id == persisted_message_id)
{
log::debug!(
"{LOG_PREFIX} skipping duplicate persisted turn thread_id={} message_id={}",
@@ -430,7 +434,7 @@ async fn persist_channel_turn(
}
append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
&thread_id,
ConversationMessage {
diff --git a/crates/openhuman-core/src/threads/welcome_migration.rs b/crates/openhuman-core/src/threads/welcome_migration.rs
index 3bc9d6a370..b9dffceb66 100644
--- a/crates/openhuman-core/src/threads/welcome_migration.rs
+++ b/crates/openhuman-core/src/threads/welcome_migration.rs
@@ -93,7 +93,7 @@ fn migrate_welcome_thread_labels(
WELCOME_THREAD_LABEL
);
- let threads = conversations::list_threads(DispatchCtx::ambient(), workspace_dir.to_path_buf())
+ let threads = conversations::list_threads(&DispatchCtx::ambient(), workspace_dir.to_path_buf())
.map_err(|e| format!("[migration::welcome-to-orchestrator] list_threads failed: {e}"))?;
let mut threads_updated = 0usize;
@@ -116,7 +116,7 @@ fn migrate_welcome_thread_labels(
let updated_at = chrono::Utc::now().to_rfc3339();
match conversations::update_thread_labels(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
&thread.id,
new_labels,
diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rs
index 00faad5d3f..41845d6a43 100644
--- a/crates/openhuman-core/src/tinymemes/mod.rs
+++ b/crates/openhuman-core/src/tinymemes/mod.rs
@@ -39,8 +39,8 @@ mod jev;
mod search;
pub(crate) mod service;
-use crate::core::runtime::DispatchCtx;
use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
use async_trait::async_trait;
use std::time::{Duration, Instant};
use tinymemes_bus::{RemixOptions, RemixRequest, RemixResponse, SkipReason};
@@ -191,9 +191,13 @@ async fn load(
let config = config.clone();
let thread_id = thread_id.to_owned();
crate::core::runtime::spawn_blocking_scoped(move || {
- crate::threads::store::get_messages(DispatchCtx::ambient(), config.workspace_dir.clone(), &thread_id)
- .map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}"))
- .ok()
+ crate::threads::store::get_messages(
+ &DispatchCtx::ambient(),
+ config.workspace_dir.clone(),
+ &thread_id,
+ )
+ .map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}"))
+ .ok()
})
.await
.ok()
diff --git a/crates/openhuman-core/src/web_chat/reply_persistence.rs b/crates/openhuman-core/src/web_chat/reply_persistence.rs
index 2e8174e05a..db690d0ce3 100644
--- a/crates/openhuman-core/src/web_chat/reply_persistence.rs
+++ b/crates/openhuman-core/src/web_chat/reply_persistence.rs
@@ -71,7 +71,7 @@ pub(crate) fn persist_delivered_reply(
extra_metadata["citations"] = json!(citations);
}
conversations::append_message(
- DispatchCtx::ambient(),
+ &DispatchCtx::ambient(),
workspace_dir.to_path_buf(),
thread_id,
ConversationMessage {
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index ba02ab424d..8d01439e5d 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -123,7 +123,8 @@ pub(crate) async fn run_chat_task(
// policy (which grants `action_dir` as a trusted root) and its tools are
// all built on the thread's folder.
let thread_dir =
- crate::threads::ops::thread_working_dir(&ctx, config.workspace_dir.clone(), thread_id).await?;
+ crate::threads::ops::thread_working_dir(&ctx, config.workspace_dir.clone(), thread_id)
+ .await?;
if let Some(dir) = &thread_dir {
log::debug!("[web-channel] thread working folder applied thread_id={thread_id}");
config.action_dir = dir.clone();