Skip to content

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

feat(agent): add turn workspace for per-turn state

Steven Enamakel577631690b44
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 2086308a81..bd517dc574 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -93,12 +93,6 @@ pub mod turn_origin;
/// How a turn that reached the completion path was stopped early (breaker,
/// deadline wind-down, iteration cap), carried to traces and parent tools.
pub mod turn_projection;
-/// Turn-workspace task-local — the per-turn filesystem root an embedder binds
-/// a single agent turn to. Read by the session builder (as the turn's default
-/// cwd) and by the path policy (as a read/write trusted root), so a host that
-/// runs one turn against a checkout it names does not have to mutate
-/// process-global state to do it.
-pub mod turn_workspace;
pub use schemas::{
all_controller_schemas as all_agent_controller_schemas,
all_registered_controllers as all_agent_registered_controllers,
diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rs
index 4535d8e6bf..6bafc86d8b 100644
--- a/crates/openhuman-core/src/agent/orchestration/ops.rs
+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs
@@ -413,7 +413,7 @@ impl AgentOrchestrationSession {
// already is. Without the origin the spawned agent's external-effect
// tools reach the approval gate unlabelled and are refused.
let handle = tokio::spawn(crate::agent::turn_origin::propagate(
- crate::agent::turn_workspace::propagate(async move {
+ async move {
mark_running(&task_status_tx);
let result = with_parent_context(parent, async move {
run_subagent(&definition, &prompt, options).await
@@ -428,7 +428,7 @@ impl AgentOrchestrationSession {
result,
)
.await;
- }),
+ }
));
self.registry
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
index 0b3b66aa22..378b8858a3 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
@@ -395,7 +395,7 @@ impl SpawnAsyncSubagentTool {
let detached_run_context = detached_parent.data.child();
let mut abort_report = AbortReport::arm(progress_sink.clone(), &definition.id, &task_id);
let join = crate::core::runtime::spawn_scoped(crate::agent::turn_origin::propagate(
- crate::agent::turn_workspace::propagate(async move {
+ async move {
let options = SubagentRunOptions {
skill_filter_override: None,
context,
@@ -710,7 +710,7 @@ impl SpawnAsyncSubagentTool {
}
}
abort_report.disarm();
- }),
+ }
));
// Register *after* spawn so the AbortHandle is available. The task owns
diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rs
index 72934fcf51..1964cd4739 100644
--- a/crates/openhuman-core/src/agent/session_store/mod.rs
+++ b/crates/openhuman-core/src/agent/session_store/mod.rs
@@ -34,21 +34,6 @@ pub use workspace::{
static PROVIDER: LazyLock<RwLock<Option<Arc<dyn SessionStoreProvider>>>> =
LazyLock::new(|| RwLock::new(None));
-tokio::task_local! {
- /// A provider for one task tree only, ahead of the process-wide one; how
- /// tests in a shared binary use a store without touching each other.
- static SCOPED: Arc<dyn SessionStoreProvider>;
-}
-
-/// Runs `future` with `provider` as the session store, for that task only.
-/// Tasks it spawns do not inherit it.
-pub async fn scope<F: std::future::Future>(
- provider: Arc<dyn SessionStoreProvider>,
- future: F,
-) -> F::Output {
- SCOPED.scope(provider, future).await
-}
-
/// Routes every agent's session state through `provider`, replacing any
/// earlier one.
pub fn install(provider: Arc<dyn SessionStoreProvider>) -> Option<Arc<dyn SessionStoreProvider>> {
@@ -97,17 +82,12 @@ pub fn restore(provider: Option<Arc<dyn SessionStoreProvider>>) {
*PROVIDER.write().unwrap_or_else(PoisonError::into_inner) = provider;
}
-/// The provider in effect: the task's [`scope`]d one, else the installed
-/// one, if any.
+/// The provider in effect: the context's host-override one, else the
+/// installed one, if any.
#[must_use]
pub fn installed() -> Option<Arc<dyn SessionStoreProvider>> {
- SCOPED
- .try_with(Arc::clone)
- .ok()
- .or_else(|| {
- crate::core::runtime::CoreContext::current_host_overrides()
- .and_then(|local| local.session_store.clone())
- })
+ crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.session_store.clone())
.or_else(|| {
PROVIDER
.read()
diff --git a/crates/openhuman-core/src/agent/turn_workspace.rs b/crates/openhuman-core/src/agent/turn_workspace.rs
deleted file mode 100644
index b6f1d7b749..0000000000
--- a/crates/openhuman-core/src/agent/turn_workspace.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! Agent turn workspace — the per-turn filesystem root an embedder binds a
-//! single agent turn to.
-//!
-//! A host that drives the core in-process (an embedded core, a
-//! workflow node dispatched to the `openhuman` harness) runs one turn *against
-//! a checkout it names*, not against the operator's ambient
-//! [`Config::action_dir`](crate::config::Config). Everything the
-//! core already had for this was **process-global**: `action_dir` comes from
-//! config, and [`SecurityPolicy`](crate::security::SecurityPolicy)
-//! is installed once per process, so two concurrent turns could not disagree
-//! about where they are allowed to write.
-//!
-//! This module is the per-turn answer, deliberately shaped like
-//! [`super::turn_origin`]: a [`tokio::task_local`] the entry point scopes
-//! around its `run_turn` invocation, read by the two places that decide where
-//! a turn may work:
-//!
-//! * the session builder
-//! ([`OpenHumanSessionHost::from_config`](crate::agent::OpenHumanSessionHost::from_config)),
-//! which turns it into the turn's
-//! [`WorkspaceDescriptor`](tinyagents_harness::workspace::WorkspaceDescriptor)
-//! so acting tools (shell, file, git) resolve their default cwd there; and
-//! * [`SecurityPolicy::is_within_trusted_root`](crate::security::SecurityPolicy::is_within_trusted_root),
-//! which treats the scoped root as a read/write trusted root for the
-//! duration of the turn, so a write into that checkout is not refused as an
-//! escape from `workspace_dir`.
-//!
-//! # Trust
-//!
-//! Scoping a root here is a **grant**, exactly as strong as a user-configured
-//! [`TrustedRoot`](crate::security::TrustedRoot) with
-//! `access = ReadWrite`, and it is scoped to one turn rather than persisted.
-//! It therefore never weakens the two invariants a trusted root has never been
-//! able to weaken: credential stores
-//! ([`SecurityPolicy::is_always_forbidden`](crate::security::SecurityPolicy::is_always_forbidden))
-//! and workspace-internal application state stay unreachable. An embedder
-//! scopes it only for a root it already decided the turn owns — a workflow
-//! run's checkout — which is why the API takes an owned [`PathBuf`] the caller
-//! resolved rather than a string the model could have supplied.
-//!
-//! Nothing is scoped by default: `current()` returning `None` is every
-//! existing caller, and leaves path policy byte-identical.
-
-use std::path::PathBuf;
-
-tokio::task_local! {
- /// Per-turn filesystem root. Scoped by an embedder around the agent turn it
- /// drives; read by the session builder and the path policy. Unset for every
- /// caller that has not opted in.
- pub static AGENT_TURN_WORKSPACE: PathBuf;
-}
-
-/// Scope `root` as the workspace for the duration of `fut`.
-///
-/// `root` should be an existing, absolute directory the caller has already
-/// resolved — a relative or missing path still scopes, but the tools rooted at
-/// it will fail on their own terms rather than being caught here, and the
-/// policy grant only ever covers paths that actually resolve under it.
-///
-/// The inner future is `Box::pin`-ed before entering the task-local scope for
-/// the same reason [`super::turn_origin::with_origin`] does it: the agent loop
-/// downstream is deep, and stacking task-local scopes plus the loop on a 2 MiB
-/// worker stack blows the test runtime.
-pub async fn with_workspace<F: std::future::Future>(root: PathBuf, fut: F) -> F::Output {
- AGENT_TURN_WORKSPACE.scope(root, Box::pin(fut)).await
-}
-
-/// The workspace root scoped for the current turn, when an embedder set one.
-///
-/// `None` — the default everywhere — means "no per-turn root": the session
-/// binds no [`WorkspaceDescriptor`](tinyagents_harness::workspace::WorkspaceDescriptor)
-/// of its own and the path policy grants nothing beyond its configured roots.
-pub fn current() -> Option<PathBuf> {
- AGENT_TURN_WORKSPACE.try_with(|root| root.clone()).ok()
-}
-
-/// Carry the workspace scoped **right now** into a future that will run on
-/// another task.
-///
-/// Same contract, and same reason, as
-/// [`turn_origin::propagate`](super::turn_origin::propagate): a detached
-/// sub-agent starts on a fresh task where [`current`] is `None`, so it would
-/// lose the root its parent turn was bound to and have its writes into that
-/// checkout refused. Build the future on the parent task, before `tokio::spawn`
-/// — the root is read when this is called, not when the future is polled.
-///
-/// With no scoped root this is a no-op, which is every caller that never opted
-/// in.
-pub fn propagate<F: std::future::Future>(fut: F) -> impl std::future::Future<Output = F::Output> {
- let captured = current();
- async move {
- match captured {
- Some(root) => with_workspace(root, fut).await,
- None => fut.await,
- }
- }
-}
-
-#[cfg(test)]
-#[path = "turn_workspace_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/turn_workspace_tests.rs b/crates/openhuman-core/src/agent/turn_workspace_tests.rs
deleted file mode 100644
index 86171463b0..0000000000
--- a/crates/openhuman-core/src/agent/turn_workspace_tests.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn scope_sets_and_clears_the_root() {
- assert!(current().is_none(), "baseline outside any scope");
- let observed = with_workspace(PathBuf::from("/work/checkout"), async { current() }).await;
- assert_eq!(observed, Some(PathBuf::from("/work/checkout")));
- assert!(current().is_none(), "root must not leak past the scope");
-}
-
-/// A detached sub-agent must keep working in the tree its parent turn was
-/// bound to; a bare `tokio::spawn` drops the root, which is what put its
-/// writes back outside the sandbox.
-#[tokio::test]
-async fn propagate_carries_the_root_across_a_spawn() {
- let observed = with_workspace(PathBuf::from("/work/checkout"), async {
- tokio::spawn(propagate(async { current() }))
- .await
- .expect("spawned task panicked")
- })
- .await;
- assert_eq!(observed, Some(PathBuf::from("/work/checkout")));
-}
-
-/// Without the wrapper the same spawn loses the root — pinned so the fix
-/// cannot be silently undone.
-#[tokio::test]
-async fn a_bare_spawn_loses_the_root() {
- let observed = with_workspace(PathBuf::from("/work/checkout"), async {
- tokio::spawn(async { current() })
- .await
- .expect("spawned task panicked")
- })
- .await;
- assert!(observed.is_none());
-}
-
-#[tokio::test]
-async fn nested_scope_overrides_the_outer_root() {
- with_workspace(PathBuf::from("/outer"), async {
- assert_eq!(current(), Some(PathBuf::from("/outer")));
- with_workspace(PathBuf::from("/inner"), async {
- assert_eq!(current(), Some(PathBuf::from("/inner")));
- })
- .await;
- assert_eq!(current(), Some(PathBuf::from("/outer")));
- })
- .await;
-}