Skip to content

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

Merge remote-tracking branch 'upstream/main' into tinywallet-release-0192

Steven Enamakel0bf4b5ea6165
diff --cc crates/openhuman-core/src/agent/attachments/provider.rs
index 717995c83c,717995c83c..5d6ac8900a
--- a/crates/openhuman-core/src/agent/attachments/provider.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider.rs
@@@ -454,6 -454,6 +454,10 @@@ mod source
#[path = "provider_tests.rs"]
mod tests;
++#[cfg(test)]
++#[path = "provider_context_tests.rs"]
++mod context_tests;
++
#[cfg(test)]
#[path = "provider_history_tests.rs"]
mod history_tests;
diff --cc crates/openhuman-core/src/agent/attachments/provider_context_tests.rs
index 0000000000,0000000000..964021c196
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/agent/attachments/provider_context_tests.rs
@@@ -1,0 -1,0 +1,20 @@@
++use super::tests::Probe;
++use super::*;
++use std::sync::Mutex;
++
++#[tokio::test]
++async fn the_wrapped_model_keeps_its_turns_context_while_another_is_active() {
++ use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};
++ let turn = CoreContext::for_test(DomainSet::full(), None);
++ let other = CoreContext::for_test(DomainSet::full(), None);
++ let concrete = AttachmentModel {
++ inner: Arc::new(Probe::default()),
++ config: Arc::new(Config::default()),
++ core: DispatchCtx::new(Arc::clone(&turn)).downgrade(),
++ profile: ModelProfile::default(),
++ fallback_cache: Mutex::new(Default::default()),
++ };
++ let seen = CoreContext::scope(Arc::clone(&other), async { concrete.dispatch_ctx() }).await;
++ assert!(Arc::ptr_eq(seen.core().expect("bound"), &turn));
++ assert!(!Arc::ptr_eq(seen.core().expect("bound"), &other));
++}
diff --cc crates/openhuman-core/src/agent/attachments/provider_tests.rs
index 994b631fba,8d8c6740cc..52006c9024
--- a/crates/openhuman-core/src/agent/attachments/provider_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_tests.rs
@@@ -741,20 -682,20 +741,3 @@@ async fn pdf_attachment_degrades_to_a_n
assert!(text.contains("brief.pdf"));
assert!(!cacheable);
}
--
--#[tokio::test]
--async fn the_wrapped_model_keeps_its_turns_context_while_another_is_active() {
-- use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};
-- let turn = CoreContext::for_test(DomainSet::full(), None);
-- let other = CoreContext::for_test(DomainSet::full(), None);
-- let concrete = AttachmentModel {
-- inner: Arc::new(Probe::default()),
-- config: Arc::new(Config::default()),
-- core: DispatchCtx::new(Arc::clone(&turn)).downgrade(),
-- profile: ModelProfile::default(),
-- fallback_cache: Mutex::new(Default::default()),
-- };
-- let seen = CoreContext::scope(Arc::clone(&other), async { concrete.dispatch_ctx() }).await;
-- assert!(Arc::ptr_eq(seen.core().expect("bound"), &turn));
-- assert!(!Arc::ptr_eq(seen.core().expect("bound"), &other));
--}
diff --cc crates/openhuman-core/src/agent/hooks_tests.rs
index 8be3aa9e6e,0edc78df1b..1251bd7630
--- a/crates/openhuman-core/src/agent/hooks_tests.rs
+++ b/crates/openhuman-core/src/agent/hooks_tests.rs
@@@ -183,3 -183,38 +183,41 @@@ async fn fired_hooks_observe_the_firing
not the process default"
);
}
+
+ /// The process-wide snapshot is independent of any task scope: a hook the host
+ /// registered is listed by name whatever context is active, and the per-context
+ /// snapshot starts from the same list.
+ #[tokio::test]
+ async fn embedder_snapshots_read_the_process_registry_not_the_task_scope() {
+ use crate::core::runtime::context::CoreContext;
+
+ struct Named;
+ #[async_trait::async_trait]
+ impl PostTurnHook for Named {
+ fn name(&self) -> &str {
+ "snapshot-scope-probe"
+ }
+ async fn on_turn_complete(&self, _ctx: &TurnContext) -> anyhow::Result<()> {
+ Ok(())
+ }
+ }
+
+ replace_embedder_post_turn_hook("snapshot-scope-probe", Some(std::sync::Arc::new(Named)));
+ let tenant_ctx = CoreContext::for_test(crate::core::runtime::DomainSet::full(), None);
+ let in_scope = CoreContext::scope(tenant_ctx, async {
+ embedder_post_turn_hooks()
+ .iter()
+ .any(|hook| hook.name() == "snapshot-scope-probe")
+ })
+ .await;
+ let via_ctx = embedder_post_turn_hooks_in(&crate::core::runtime::DispatchCtx::unbound())
+ .iter()
+ .any(|hook| hook.name() == "snapshot-scope-probe");
+ replace_embedder_post_turn_hook("snapshot-scope-probe", None);
+
+ assert!(in_scope, "the process registry is visible under a scope");
- assert!(via_ctx, "the per-context snapshot extends the same registry");
++ assert!(
++ via_ctx,
++ "the per-context snapshot extends the same registry"
++ );
+ }
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
index 4262865c99,cfee4dfcae..ecca2e5280
--- 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
@@@ -234,8 -234,7 +234,8 @@@ impl OpenHumanTurnPrelude
)
.await;
};
- crate::core::runtime::DispatchCtx::ambient()
- self.dispatch_ctx().spawn(deferred_memory_work(profile_context, work));
++ self.dispatch_ctx()
+ .spawn(deferred_memory_work(profile_context, work));
}
}
diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/post_commit_tests.rs
index 67b84b1027,2b02a2b221..d768bb4a33
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/post_commit_tests.rs
@@@ -62,7 -62,7 +62,11 @@@ async fn completion_is_published_before
let (delivered, pending) = tokio::time::timeout(
std::time::Duration::from_secs(5),
- complete_then_defer(publish, slow_tail),
- complete_then_defer(&crate::core::runtime::DispatchCtx::unbound(), publish, slow_tail),
++ complete_then_defer(
++ &crate::core::runtime::DispatchCtx::unbound(),
++ publish,
++ slow_tail,
++ ),
)
.await
.expect("completion does not wait for the slow tail");
@@@ -89,3 -89,25 +93,28 @@@
async fn await_pending_is_a_no_op_without_deferred_work() {
await_pending(None).await;
}
+
+ /// The deferred tail acts for the context it was handed, not for whichever
+ /// context is active on the task that published the completion.
+ #[tokio::test]
+ async fn deferred_tail_runs_under_the_handed_context_not_the_active_one() {
+ use crate::core::runtime::{CoreContext, DispatchCtx, DomainSet};
+
+ let handed = CoreContext::for_test(DomainSet::full(), None);
+ let active = CoreContext::for_test(DomainSet::full(), None);
+ let (seen_tx, seen_rx) = tokio::sync::oneshot::channel();
+ let tail = async move {
+ let _ = seen_tx.send(CoreContext::scoped());
+ };
+ let dispatch = DispatchCtx::new(std::sync::Arc::clone(&handed));
+ let (_, pending) = CoreContext::scope(active, async {
+ complete_then_defer(&dispatch, async { true }, tail).await
+ })
+ .await;
+ pending.await.expect("tail finishes");
- let seen = seen_rx.await.expect("tail ran").expect("tail has a context");
++ let seen = seen_rx
++ .await
++ .expect("tail ran")
++ .expect("tail has a context");
+ assert!(std::sync::Arc::ptr_eq(&seen, &handed));
+ }
diff --cc crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
index e62cc81605,fe40cddf9f..c8061aa6a6
--- a/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/module_providers.rs
@@@ -58,7 -56,7 +58,8 @@@ impl ModuleChannelRuntime
tracing::warn!("[channels] legacy delivery import failed, will retry: {error:#}");
}
}
- let callback = ChannelHostCallbacks::new(Arc::clone(&config), context, dispatch);
- let callback = ChannelHostCallbacks::new(dispatch_ctx, Arc::clone(&config), context, dispatch);
++ let callback =
++ ChannelHostCallbacks::new(dispatch_ctx, Arc::clone(&config), context, dispatch);
let lease = ChannelRuntimeLease::open(client.clone(), callback)
.await
.map_err(anyhow::Error::new)
diff --cc crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
index 01941a9146,13b7f986a9..714a36b771
--- a/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
@@@ -488,7 -488,7 +488,11 @@@ async fn scheduler_tick_once_publishes_
tick_once(
&config,
&mut last_emitted_health,
- &mut JobDispatcher::new(&config, &security),
- &mut JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security),
++ &mut JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security,
++ ),
)
.await;
@@@ -551,7 -551,7 +555,11 @@@ async fn scheduler_tick_once_does_not_r
tick_once(
&config,
&mut last_emitted_health,
- &mut JobDispatcher::new(&config, &security),
- &mut JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security),
++ &mut JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security,
++ ),
)
.await;
assert_eq!(
@@@ -569,7 -569,7 +577,11 @@@
tick_once(
&config,
&mut last_emitted_health,
- &mut JobDispatcher::new(&config, &security),
- &mut JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security),
++ &mut JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security,
++ ),
)
.await;
assert_eq!(
diff --cc crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
index a8fd94947a,0a6ef1824b..3d8305ac12
--- a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
@@@ -115,7 -115,7 +115,11 @@@ async fn a_long_job_does_not_hold_up_th
let _fast = register("dispatch-fast", counting(Arc::clone(&fast_calls), Ok(())));
let slow = due_system_job(&config, "dispatch-slow");
- let mut dispatcher = JobDispatcher::new(&config, &security);
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security);
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security,
++ );
let mut health = None;
// First poll picks up only the slow job.
tick_once(&config, &mut health, &mut dispatcher).await;
@@@ -170,7 -170,7 +174,11 @@@ async fn dispatch_claims_the_slot_so_a_
}),
);
let job = due_system_job(&config, "dispatch-claim");
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
let stored = cron::get_job(&config, &job.id).unwrap();
assert!(stored.next_run > Utc::now(), "the running slot is claimed");
@@@ -190,7 -190,7 +198,11 @@@ async fn a_job_already_in_flight_is_not
let _handler = register("dispatch-dedupe", counting(Arc::clone(&calls), Ok(())));
let job = due_system_job(&config, "dispatch-dedupe");
let running = crate::cron::ops::try_acquire_run(&job.id).expect("the job is free");
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
dispatcher.drain().await;
drop(running);
@@@ -219,7 -219,7 +231,11 @@@ async fn a_single_flight_job_records_th
.unwrap();
let job = cron::get_job(&config, &job.id).unwrap();
let running = crate::cron::ops::try_acquire_run(&job.id).expect("the job is free");
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
dispatcher.drain().await;
drop(running);
@@@ -260,7 -260,7 +276,13 @@@ async fn zero_retries_means_exactly_one
)
.unwrap();
let job = cron::get_job(&config, &job.id).unwrap();
- let (success, output) = execute_job_now(&config, &job, "dispatch-run").await;
- let (success, output) = execute_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "dispatch-run").await;
++ let (success, output) = execute_job_now(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &job,
++ "dispatch-run",
++ )
++ .await;
assert!(!success);
assert!(output.contains("boom"), "{output}");
assert_eq!(calls.load(Ordering::SeqCst), 1);
@@@ -278,7 -278,7 +300,13 @@@ async fn without_a_policy_the_configure
counting(Arc::clone(&calls), Err("again".to_string())),
);
let job = due_system_job(&config, "dispatch-default-retries");
- let (success, _) = execute_job_now(&config, &job, "dispatch-run").await;
- let (success, _) = execute_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "dispatch-run").await;
++ let (success, _) = execute_job_now(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &job,
++ "dispatch-run",
++ )
++ .await;
assert!(!success);
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
@@@ -305,7 -305,7 +333,11 @@@ async fn a_system_job_handler_error_is_
)
.unwrap();
let job = cron::get_job(&config, &job.id).unwrap();
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
dispatcher.drain().await;
let stored = cron::get_job(&config, &job.id).unwrap();
@@@ -321,7 -321,7 +353,13 @@@ async fn a_system_job_without_a_handler
let tmp = TempDir::new().unwrap();
let config = test_config(&tmp).await;
let job = due_system_job(&config, "dispatch-unclaimed");
- let (success, output) = execute_job_now(&config, &job, "dispatch-run").await;
- let (success, output) = execute_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "dispatch-run").await;
++ let (success, output) = execute_job_now(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &job,
++ "dispatch-run",
++ )
++ .await;
assert!(success);
assert!(output.contains("dispatched"), "{output}");
}
@@@ -380,7 -380,7 +418,11 @@@ async fn an_upgraded_job_with_a_side_ta
assert_eq!(job.policy.retries, Some(0));
assert!(job.policy.single_flight);
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job]).await.unwrap();
dispatcher.drain().await;
@@@ -411,7 -411,7 +453,11 @@@ async fn a_flow_schedule_job_fires_thro
force_due(&config, &job.id);
let job = cron::get_job(&config, &job.id).unwrap();
- let mut dispatcher = JobDispatcher::new(&config, &security(&config));
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security(&config));
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security(&config),
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
dispatcher.drain().await;
@@@ -462,3 -463,26 +509,28 @@@ async fn a_flow_schedule_job_is_skipped
assert!(!output.contains("tick emitted"));
assert!(stored.next_run > Utc::now(), "the recurrence moved on");
}
+
+ #[tokio::test]
+ async fn a_dispatcher_binds_the_context_it_is_handed_not_the_ambient_one() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let security = security(&config);
- let handed = crate::core::runtime::CoreContext::for_test(crate::core::runtime::DomainSet::full(), None);
- let ambient = crate::core::runtime::CoreContext::for_test(crate::core::runtime::DomainSet::full(), None);
++ let handed =
++ crate::core::runtime::CoreContext::for_test(crate::core::runtime::DomainSet::full(), None);
++ let ambient =
++ crate::core::runtime::CoreContext::for_test(crate::core::runtime::DomainSet::full(), None);
+
+ let dispatcher = crate::core::runtime::CoreContext::scope(Arc::clone(&ambient), async {
+ // Across an await the handed context is still the one bound.
+ tokio::task::yield_now().await;
+ JobDispatcher::new(
+ &crate::core::runtime::DispatchCtx::new(Arc::clone(&handed)),
+ &config,
+ &security,
+ )
+ })
+ .await;
+ let bound = dispatcher.dispatch_ctx();
+ assert!(Arc::ptr_eq(bound.core().expect("bound"), &handed));
+ assert!(!Arc::ptr_eq(bound.core().unwrap(), &ambient));
+ }
diff --cc crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
index 7eb8ff0ea8,608213dd44..1e50025499
--- a/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
@@@ -367,7 -367,7 +367,11 @@@ async fn run_through_scheduler(config:
&config.workspace_dir,
&config.action_dir,
));
- let mut dispatcher = JobDispatcher::new(config, &security);
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), config, &security);
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ config,
++ &security,
++ );
dispatcher.dispatch(vec![job]).await.unwrap();
dispatcher.drain().await;
}
@@@ -427,7 -427,7 +431,11 @@@ async fn scheduler_flow_runs_active_hou
&config.workspace_dir,
&config.workspace_dir,
));
- let mut dispatcher = JobDispatcher::new(&config, &security);
- let mut dispatcher = JobDispatcher::new(&crate::core::runtime::DispatchCtx::ambient(), &config, &security);
++ let mut dispatcher = JobDispatcher::new(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &security,
++ );
dispatcher.dispatch(vec![job.clone()]).await.unwrap();
dispatcher.drain().await;
diff --cc crates/openhuman-core/src/cron/scheduler_tests.rs
index efdec7fcaa,bf0ce4a92f..8a496784be
--- a/crates/openhuman-core/src/cron/scheduler_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_tests.rs
@@@ -173,7 -172,7 +173,13 @@@ async fn retryable_shell_failure_consum
let counter = tmp.path().join("retryable-attempts.log");
let job = test_job(&counting_failure_command(&counter));
- let (success, output) = execute_job_now(&config, &job, "test-run").await;
- let (success, output) = execute_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "test-run").await;
++ let (success, output) = execute_job_now(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &job,
++ "test-run",
++ )
++ .await;
assert!(
!success,
@@@ -231,7 -230,7 +237,13 @@@ async fn security_policy_block_halts_wi
);
let started = std::time::Instant::now();
- let (success, output) = execute_job_now(&config, &job, "test-run").await;
- let (success, output) = execute_job_now(&crate::core::runtime::DispatchCtx::ambient(), &config, &job, "test-run").await;
++ let (success, output) = execute_job_now(
++ &crate::core::runtime::DispatchCtx::ambient(),
++ &config,
++ &job,
++ "test-run",
++ )
++ .await;
let elapsed = started.elapsed();
assert!(!success, "a blocked job cannot succeed; got {output}");
diff --cc crates/openhuman-core/src/cron/tools/run.rs
index c144206e8a,e709b5519f..cce0909c16
--- a/crates/openhuman-core/src/cron/tools/run.rs
+++ b/crates/openhuman-core/src/cron/tools/run.rs
@@@ -102,7 -104,7 +104,8 @@@ impl Tool for CronRunTool
let started_at = Utc::now();
let run_id = uuid::Uuid::new_v4().to_string();
- let (success, output) = cron::scheduler::execute_job_now(&self.config, &job, &run_id).await;
- let (success, output) = cron::scheduler::execute_job_now(&dispatch, &self.config, &job, &run_id).await;
++ let (success, output) =
++ cron::scheduler::execute_job_now(&dispatch, &self.config, &job, &run_id).await;
let finished_at = Utc::now();
let duration_ms = (finished_at - started_at).num_milliseconds();
let status = if success { "ok" } else { "error" };
diff --cc crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs
index daf3b0ba54,fccb782b20..34a4359104
--- a/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs
+++ b/crates/openhuman-core/src/inference/tokenjuice/repl_tools.rs
@@@ -287,11 -287,11 +287,10 @@@ impl ModuleReplTool
);
return Ok(ToolResult::error(not_a_handle_message()));
};
- let read = tokio::task::spawn_blocking(move || {
- let read = crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || {
-- read_tool_result_artifact(&dir, &path, MAX_ARTIFACT_BYTES)
-- })
-- .await
-- .map_err(|e| anyhow::anyhow!("juice: artifact read task failed: {e}"))?;
++ let read = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || read_tool_result_artifact(&dir, &path, MAX_ARTIFACT_BYTES))
++ .await
++ .map_err(|e| anyhow::anyhow!("juice: artifact read task failed: {e}"))?;
match read {
Ok(content) => {
log::debug!(
diff --cc crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs
index 62b20d462b,c77ff6d85f..bf969fcbaa
--- a/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs
+++ b/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber.rs
@@@ -5,6 -5,6 +5,7 @@@
use crate::core::runtime::DispatchCtx;
use std::time::Duration;
++use std::{future::Future, sync::Arc};
use async_trait::async_trait;
use tinybus::EventHandler;
@@@ -95,10 -95,12 +96,25 @@@ impl EventHandler<DomainEvent> for Comp
// The cache refresh runs for every toolkit; only the profile fetch is gated on a native provider.
let toolkit = toolkit.clone();
let connection_id = connection_id.clone();
- tokio::spawn(async move { on_connection_created(&ctx, toolkit, connection_id).await });
- tokio::spawn(async move {
- on_connection_created(&ctx, toolkit, connection_id).await
++ spawn_connection_created_task(ctx, move |task_ctx| async move {
++ on_connection_created(&task_ctx, toolkit, connection_id).await;
+ });
}
}
++fn spawn_connection_created_task<F, Fut>(
++ ctx: DispatchCtx,
++ task: F,
++) -> tokio::task::JoinHandle<Fut::Output>
++where
++ F: FnOnce(DispatchCtx) -> Fut + Send + 'static,
++ Fut: Future + Send + 'static,
++ Fut::Output: Send + 'static,
++{
++ let task_ctx = ctx.clone();
++ ctx.spawn(task(task_ctx))
++}
++
async fn on_connection_created(ctx: &DispatchCtx, toolkit: String, connection_id: String) {
let config = match ctx.load_config().await {
Ok(c) => c,
@@@ -197,6 -199,6 +213,10 @@@
}
}
++#[cfg(test)]
++#[path = "connection_created_subscriber_tests.rs"]
++mod tests;
++
// ── Connection-readiness polling ────────────────────────────────────
#[derive(Debug)]
diff --cc crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber_tests.rs
index 0000000000,0000000000..303eebdce0
new file mode 100644
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/bus/connection_created_subscriber_tests.rs
@@@ -1,0 -1,0 +1,16 @@@
++use super::*;
++use crate::core::runtime::{CoreContext, DomainSet};
++
++#[tokio::test]
++async fn spawned_connection_created_task_keeps_its_dispatch_context() {
++ let context = CoreContext::for_test(DomainSet::full(), None);
++ let expected = Arc::clone(&context);
++ let dispatch = DispatchCtx::new(context);
++
++ spawn_connection_created_task(dispatch, move |_task_ctx| async move {
++ let current = CoreContext::current().expect("spawn should enter dispatch context");
++ assert!(Arc::ptr_eq(&current, &expected));
++ })
++ .await
++ .expect("connection task should complete");
++}
diff --cc crates/openhuman-core/src/integrations/composio/file_store.rs
index 239c543ee2,d44a688daa..a7449b6bae
--- a/crates/openhuman-core/src/integrations/composio/file_store.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store.rs
@@@ -30,10 -30,13 +30,11 @@@ async fn import_legacy
name: &'static str,
) -> Result<(), String> {
let marker_docs = docs.clone();
- let done = tokio::task::spawn_blocking(move || marker_docs.legacy_imported(name))
- let done =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || marker_docs.legacy_imported(name))
- .await
- .map_err(|error| format!("[composio:store] checking legacy {name} failed: {error}"))?
- .map_err(|error| {
- format!("[composio:store] checking legacy {name} failed: {error:#}")
- })?;
++ let done = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || marker_docs.legacy_imported(name))
+ .await
+ .map_err(|error| format!("[composio:store] checking legacy {name} failed: {error}"))?
+ .map_err(|error| format!("[composio:store] checking legacy {name} failed: {error:#}"))?;
if done {
return Ok(());
}
@@@ -50,10 -53,13 +51,11 @@@
let value: serde_json::Value = serde_json::from_slice(&bytes)
.map_err(|error| format!("[composio:store] parsing legacy {name} failed: {error}"))?;
let docs = docs.clone();
- let wrote = tokio::task::spawn_blocking(move || docs.import_if_absent(name, value))
- let wrote =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || docs.import_if_absent(name, value))
- .await
- .map_err(|error| format!("[composio:store] importing legacy {name} failed: {error}"))?
- .map_err(|error| {
- format!("[composio:store] importing legacy {name} failed: {error:#}")
- })?;
++ let wrote = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs.import_if_absent(name, value))
+ .await
+ .map_err(|error| format!("[composio:store] importing legacy {name} failed: {error}"))?
+ .map_err(|error| format!("[composio:store] importing legacy {name} failed: {error:#}"))?;
log::debug!("[composio:store] legacy import name={name} wrote={wrote}");
Ok(())
}
@@@ -72,7 -78,7 +74,8 @@@ wher
import_legacy(config, &docs, name).await?;
// The document port is reached through a blocking bridge; keep it off the
// async worker, under the caller's context.
- tokio::task::spawn_blocking(move || docs.load(name))
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || docs.load(name))
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs.load(name))
.await
.map_err(|error| format!("[composio:store] reading {name} failed: {error}"))?
.map_err(|error| format!("[composio:store] reading {name} failed: {error:#}"))
@@@ -97,7 -103,7 +100,8 @@@ wher
let docs = super::file_store_documents::current(&config.workspace_dir)
.map_err(|e| format!("[composio:store] {e:#}"))?;
import_legacy(config, &docs, name).await?;
- tokio::task::spawn_blocking(move || docs.update(name, change))
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || docs.update(name, change))
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs.update(name, change))
.await
.map_err(|error| format!("[composio:store] updating {name} failed: {error}"))?
.map_err(|error| format!("[composio:store] updating {name} failed: {error:#}"))
@@@ -117,7 -123,7 +121,8 @@@ wher
.map_err(|e| format!("[composio:store] {e:#}"))?;
let value = serde_json::to_value(value)
.map_err(|error| format!("[composio:store] serializing failed: {error}"))?;
- tokio::task::spawn_blocking(move || docs.save(name, &value))
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || docs.save(name, &value))
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs.save(name, &value))
.await
.map_err(|error| format!("[composio:store] writing {name} failed: {error}"))?
.map_err(|error| format!("[composio:store] writing {name} failed: {error:#}"))
diff --cc crates/openhuman-core/src/integrations/composio/trigger_history.rs
index acf9f0a007,32bcef8cde..7aa545238e
--- a/crates/openhuman-core/src/integrations/composio/trigger_history.rs
+++ b/crates/openhuman-core/src/integrations/composio/trigger_history.rs
@@@ -87,13 -87,13 +87,14 @@@ impl TriggerHistory
let client = self.client(&config);
// Keep ownership installation running if the caller is cancelled while
// OpenArchive completes. A later close can still release the handle.
- tokio::spawn(async move {
- crate::core::runtime::DispatchCtx::ambient().spawn(async move {
-- let mut guard = lease.lock_owned().await;
-- Self::ensure_lease(&config, &mut guard, client).await?;
-- Ok(guard)
-- })
-- .await
-- .map_err(|_| "trigger archive ownership task failed".to_owned())?
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn(async move {
++ let mut guard = lease.lock_owned().await;
++ Self::ensure_lease(&config, &mut guard, client).await?;
++ Ok(guard)
++ })
++ .await
++ .map_err(|_| "trigger archive ownership task failed".to_owned())?
}
async fn release(lease: &mut Option<Lease>) -> Result<(), String> {
@@@ -157,9 -157,11 +158,10 @@@
/// Release the module resource while retaining all persisted documents.
pub async fn close(&self) -> Result<(), String> {
let lease = Arc::clone(&self.lease);
- tokio::spawn(async move { Self::release(&mut *lease.lock_owned().await).await })
- crate::core::runtime::DispatchCtx::ambient().spawn(async move {
- Self::release(&mut *lease.lock_owned().await).await
- })
- .await
- .map_err(|_| "trigger archive release task failed".to_owned())?
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn(async move { Self::release(&mut *lease.lock_owned().await).await })
+ .await
+ .map_err(|_| "trigger archive release task failed".to_owned())?
}
}
diff --cc crates/openhuman-core/src/mcp/ui/tools.rs
index e1f8d9a148,c11c9b2bb0..83652470e5
--- a/crates/openhuman-core/src/mcp/ui/tools.rs
+++ b/crates/openhuman-core/src/mcp/ui/tools.rs
@@@ -110,33 -110,33 +110,34 @@@ pub fn confine_path_in(roots: &[PathBuf
///
/// When the open is refused, the file is not regular, or it is too large.
pub async fn read_confined(root: PathBuf, resolved: PathBuf) -> Result<String, String> {
- tokio::task::spawn_blocking(move || {
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || {
-- use std::io::Read;
-- let file = crate::agent::attachments::provider::open::secure_open(&resolved, &root)
-- .map_err(|error| {
-- tracing::debug!(?error, "[mcp_ui] show_ui refused the file open");
-- "the file is not inside the workspace or a skill bundle".to_string()
-- })?;
-- let metadata = file
-- .metadata()
-- .map_err(|_| "could not read the file".to_string())?;
-- if !metadata.is_file() {
-- return Err("only regular files can be shown".to_string());
-- }
-- if metadata.len() > MAX_RESOURCE_BYTES as u64 {
-- return Err("the file is too large to show".to_string());
-- }
-- let mut html = String::new();
-- file.take(MAX_RESOURCE_BYTES as u64 + 1)
-- .read_to_string(&mut html)
-- .map_err(|_| "could not read the file".to_string())?;
-- if html.len() > MAX_RESOURCE_BYTES {
-- return Err("the file is too large to show".to_string());
-- }
-- Ok(html)
-- })
-- .await
-- .map_err(|_| "could not read the file".to_string())?
++ crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || {
++ use std::io::Read;
++ let file = crate::agent::attachments::provider::open::secure_open(&resolved, &root)
++ .map_err(|error| {
++ tracing::debug!(?error, "[mcp_ui] show_ui refused the file open");
++ "the file is not inside the workspace or a skill bundle".to_string()
++ })?;
++ let metadata = file
++ .metadata()
++ .map_err(|_| "could not read the file".to_string())?;
++ if !metadata.is_file() {
++ return Err("only regular files can be shown".to_string());
++ }
++ if metadata.len() > MAX_RESOURCE_BYTES as u64 {
++ return Err("the file is too large to show".to_string());
++ }
++ let mut html = String::new();
++ file.take(MAX_RESOURCE_BYTES as u64 + 1)
++ .read_to_string(&mut html)
++ .map_err(|_| "could not read the file".to_string())?;
++ if html.len() > MAX_RESOURCE_BYTES {
++ return Err("the file is too large to show".to_string());
++ }
++ Ok(html)
++ })
++ .await
++ .map_err(|_| "could not read the file".to_string())?
}
fn clean_title(raw: Option<&str>) -> Option<String> {
diff --cc crates/openhuman-core/src/memory/lifecycle/prefetch.rs
index 3cfb144d93,568fb64f95..d64ff13ecf
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
@@@ -171,10 -171,10 +171,11 @@@ pub(crate) fn pre_turn
if let Some(channel) = channel {
let workspace = config.workspace_dir.clone();
let thread = input.thread_id.clone();
- let _ = tokio::task::spawn_blocking(move || {
- let _ = crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || {
-- crate::memory::channels::record(&workspace, &channel, &thread)
-- })
-- .await;
++ let _ = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || {
++ crate::memory::channels::record(&workspace, &channel, &thread)
++ })
++ .await;
}
}
hooks::pre_turn_work(&dispatch, &config, &identity, input).await
diff --cc crates/openhuman-core/src/modules/storage_host_endpoint.rs
index a1eee19340,549cc0c7c0..e49bcae7d2
--- a/crates/openhuman-core/src/modules/storage_host_endpoint.rs
+++ b/crates/openhuman-core/src/modules/storage_host_endpoint.rs
@@@ -102,26 -102,26 +102,28 @@@ impl StorageHost
let mut signals = binding.server.signals();
let tx = relay.tx.clone();
relay.fed_by = Some(Arc::downgrade(binding));
- relay.bridge = Some(tokio::spawn(async move {
- relay.bridge = Some(crate::core::runtime::DispatchCtx::ambient().spawn(async move {
-- loop {
-- match signals.recv().await {
-- Ok(signal) => {
-- // No receiver just means the bus forwarder is gone.
-- let _ = tx.send(signal);
++ relay.bridge = Some(
++ crate::core::runtime::DispatchCtx::ambient().spawn(async move {
++ loop {
++ match signals.recv().await {
++ Ok(signal) => {
++ // No receiver just means the bus forwarder is gone.
++ let _ = tx.send(signal);
++ }
++ Err(broadcast::error::RecvError::Lagged(missed)) => {
++ // The watch ids in the skipped batch are gone; the
++ // signal carries no reset form, so record the loss.
++ tracing::warn!(
++ target: "storage_host",
++ missed,
++ "[storage-host] watch relay lagged; dropped watch signals"
++ );
++ }
++ Err(broadcast::error::RecvError::Closed) => return,
}
-- Err(broadcast::error::RecvError::Lagged(missed)) => {
-- // The watch ids in the skipped batch are gone; the
-- // signal carries no reset form, so record the loss.
-- tracing::warn!(
-- target: "storage_host",
-- missed,
-- "[storage-host] watch relay lagged; dropped watch signals"
-- );
-- }
-- Err(broadcast::error::RecvError::Closed) => return,
}
-- }
-- }));
++ }),
++ );
}
}
diff --cc crates/openhuman-core/src/modules/storage_import_tinyconnectors.rs
index 0d955ea436,8bd1c7b0fa..a5e65e4ba9
--- a/crates/openhuman-core/src/modules/storage_import_tinyconnectors.rs
+++ b/crates/openhuman-core/src/modules/storage_import_tinyconnectors.rs
@@@ -91,9 -91,10 +91,10 @@@ async fn import_into(scoped: &ScopedSto
return Ok(Outcome::NoSource);
}
- let legacy = tokio::task::spawn_blocking(move || read_legacy(&prefs_dir, &triggers_dir))
- let legacy =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || read_legacy(&prefs_dir, &triggers_dir))
- .await
- .context("the legacy reader panicked")??;
++ let legacy = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || read_legacy(&prefs_dir, &triggers_dir))
+ .await
+ .context("the legacy reader panicked")??;
docs.ensure_collection(&CollectionSpec::new(PREFS_COLLECTION))
.await
diff --cc crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
index 088fbfba61,19b31a1c3b..1275f17baf
--- a/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
+++ b/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
@@@ -92,9 -92,10 +92,10 @@@ async fn import_into
}
let dir = root.to_owned();
- let (originals, mut skipped) = tokio::task::spawn_blocking(move || read_originals(&dir, now))
- let (originals, mut skipped) =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || read_originals(&dir, now))
- .await
- .context("the legacy reader panicked")??;
++ let (originals, mut skipped) = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || read_originals(&dir, now))
+ .await
+ .context("the legacy reader panicked")??;
let (mut imported, mut expired) = (0usize, 0usize);
for original in originals {
diff --cc crates/openhuman-core/src/modules/storage_import_tinymcp.rs
index c5be8a9b03,6b78c07f73..4b8f362c52
--- a/crates/openhuman-core/src/modules/storage_import_tinymcp.rs
+++ b/crates/openhuman-core/src/modules/storage_import_tinymcp.rs
@@@ -112,21 -109,22 +112,22 @@@ async fn import_into
}
// The files are read on a blocking thread, from copies.
- let (legacy_servers, legacy_audit) = tokio::task::spawn_blocking(move || -> Result<_> {
- let servers = if clients.exists() {
- read_servers(&clients)?
- } else {
- Vec::new()
- };
- let audit = if audit.exists() {
- read_audit(&audit)?
- } else {
- Vec::new()
- };
- Ok((servers, audit))
- })
- .await
- .context("the legacy reader panicked")??;
- let (legacy_servers, legacy_audit) =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || -> Result<_> {
++ let (legacy_servers, legacy_audit) = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || -> Result<_> {
+ let servers = if clients.exists() {
+ read_servers(&clients)?
+ } else {
+ Vec::new()
+ };
+ let audit = if audit.exists() {
+ read_audit(&audit)?
+ } else {
+ Vec::new()
+ };
+ Ok((servers, audit))
+ })
+ .await
+ .context("the legacy reader panicked")??;
for name in [SERVERS, SERVER_NAMES] {
docs.ensure_collection(&CollectionSpec::new(name))
diff --cc crates/openhuman-core/src/modules/storage_import_tinywallet.rs
index a615833920,da7b0967a7..eacae41293
--- a/crates/openhuman-core/src/modules/storage_import_tinywallet.rs
+++ b/crates/openhuman-core/src/modules/storage_import_tinywallet.rs
@@@ -66,13 -66,13 +66,14 @@@ async fn import_into(scoped: &ScopedSto
if !ledger.is_file() {
return Ok(Outcome::NoSource);
}
- let (records, skipped) = tokio::task::spawn_blocking(move || -> Result<_> {
- let (records, skipped) = crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || -> Result<_> {
-- let text = std::fs::read_to_string(&ledger)
-- .with_context(|| format!("read {}", ledger.display()))?;
-- Ok(support::parse_jsonl(&text))
-- })
-- .await
-- .context("the legacy reader panicked")??;
++ let (records, skipped) = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || -> Result<_> {
++ let text = std::fs::read_to_string(&ledger)
++ .with_context(|| format!("read {}", ledger.display()))?;
++ Ok(support::parse_jsonl(&text))
++ })
++ .await
++ .context("the legacy reader panicked")??;
let payments = support::append_if_empty(scoped, PAYMENTS_STREAM, records)
.await
diff --cc crates/openhuman-core/src/storage/import/mod.rs
index 25708689d8,68597bb126..dc0b6dc150
--- a/crates/openhuman-core/src/storage/import/mod.rs
+++ b/crates/openhuman-core/src/storage/import/mod.rs
@@@ -190,7 -190,8 +190,9 @@@ pub async fn run(config: &Config) -> Ve
return Vec::new();
}
let config = config.clone();
- let joined = tokio::task::spawn_blocking(move || run_all(&backend, &config)).await;
- let joined =
- crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || run_all(&backend, &config)).await;
++ let joined = crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || run_all(&backend, &config))
++ .await;
match joined {
Ok(reports) => reports,
Err(error) => {
diff --cc crates/openhuman-core/src/tinymemes/callbacks.rs
index 395cfd25cf,e9e0d97c90..83bb8da9eb
--- a/crates/openhuman-core/src/tinymemes/callbacks.rs
+++ b/crates/openhuman-core/src/tinymemes/callbacks.rs
@@@ -264,7 -257,7 +264,10 @@@ async fn search
async fn load_index(session: &Session, request: LoadIndexRequest) -> HostResult<Option<String>> {
let config = session.config.clone();
let kind: IndexKind = request.kind;
- match tokio::task::spawn_blocking(move || docs::load(&config, kind)).await {
- match crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || docs::load(&config, kind)).await {
++ match crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs::load(&config, kind))
++ .await
++ {
Ok(Ok(document)) => Ok(document),
Ok(Err(error)) => {
log::warn!("[tinymemes] cannot read index: {error}");
@@@ -279,7 -272,10 +282,9 @@@
async fn save_index(session: &Session, request: SaveIndexRequest) -> HostResult<()> {
let config = session.config.clone();
- match tokio::task::spawn_blocking(move || docs::save(&config, request.kind, request.json)).await
- match crate::core::runtime::DispatchCtx::ambient().spawn_blocking(move || {
- docs::save(&config, request.kind, request.json)
- })
- .await
++ match crate::core::runtime::DispatchCtx::ambient()
++ .spawn_blocking(move || docs::save(&config, request.kind, request.json))
++ .await
{
Ok(Ok(())) => Ok(()),
Ok(Err(error)) => {
diff --cc crates/openhuman-embed/src/turn.rs
index 38d29c98a0,058645adaf..26f99bd4ce
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@@ -589,6 -589,7 +589,8 @@@ async fn dispatch
}
let ctx = std::sync::Arc::clone(rt.context());
let chat_env = options.chat_env;
- let dispatch = openhuman_core::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&ctx));
++ let dispatch =
++ openhuman_core::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&ctx));
let turn: futures_box::BoxFuture<'_, Result<AgentReply, CoreError>> =
Box::pin(async move {
use openhuman_core::inference::host_runtime::ops::{
diff --cc scripts/ci/saas-ambient-baseline.json
index fa7b923aad,8fdb846aca..7ef15378e5
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@@ -114,7 -114,7 +114,7 @@@
{
"rule": "home-dir",
"path": "crates/openhuman-core/src/channels/host/adapters.rs",
- "line": 291,
- "line": 289,
++ "line": 288,
"text": ".map(|u| u.home_dir().to_path_buf())",
"occurrence": 1
},
@@@ -800,14 -688,7 +681,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/memory/backfill.rs",
-- "line": 253,
++ "line": 254,
"text": "tokio::spawn(async move {",
"occurrence": 1
},
@@@ -1129,7 -940,7 +933,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/threads/ops/edit.rs",
-- "line": 398,
++ "line": 404,
"text": "let result = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},