Skip to content

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

fix(agent): preserve scoped turn context

Steven Enamakel5f54f84af387
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index 2a41fae6cd..95ef9f67ca 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -114,11 +114,13 @@ pub(crate) async fn run_channel_turn_via_graph(
context_window,
"[channel:graph] routing channel turn through tinyagents harness"
);
+ let mut run_context =
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();
+ // The channel dispatcher owns this explicit sink. It wins over an embedder
+ // scope exactly as it did before this carrier was introduced.
+ run_context.progress = on_progress.clone().or(run_context.progress);
let outcome = run_turn_via_tinyagents_shared(
- crate::agent::tinyagents::host::OpenHumanRunContext {
- progress: on_progress.clone(),
- ..Default::default()
- },
+ run_context,
turn_models,
provider_id,
model,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
index 30c99c631c..41e0a3c435 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
@@ -112,13 +112,13 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
// on the bundle.
let provider_id = graph.turn_models.provider_id().to_string();
with_current_sandbox_mode(graph.sandbox_mode, async {
+ let mut run_context =
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();
+ run_context.progress = graph.on_progress.clone().or(run_context.progress);
+ run_context.workspace = graph.workspace_descriptor.clone().or(run_context.workspace);
+ run_context.sandbox_mode = Some(graph.sandbox_mode);
run_turn_via_tinyagents_shared(
- crate::agent::tinyagents::host::OpenHumanRunContext {
- progress: graph.on_progress.clone(),
- workspace: graph.workspace_descriptor.clone(),
- sandbox_mode: Some(graph.sandbox_mode),
- ..Default::default()
- },
+ run_context,
graph.turn_models,
provider_id,
&graph.model,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
index 45634b92d0..e9f27a85ec 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
@@ -259,12 +259,16 @@ pub(in super::super) async fn run_subagent_via_graph(
// (and the telemetry id) before `turn_models` is moved into the runner.
let native_tools = turn_models.native_tools();
let provider_id = turn_models.provider_id().to_string();
+ // This graph is entered from a parent tool call on the same task. Snapshot
+ // that owned carrier and fork it so cancellation, origin, thread, progress,
+ // workspace grants, and dispatch state follow the child while its route and
+ // subagent-usage slots remain isolated.
+ let mut child_context =
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes().child();
+ child_context.progress = on_progress.clone().or(child_context.progress);
+ child_context.workspace = workspace_descriptor.clone().or(child_context.workspace);
let run_result = Box::pin(run_turn_via_tinyagents_shared(
- crate::agent::tinyagents::host::OpenHumanRunContext {
- progress: on_progress.clone(),
- workspace: workspace_descriptor.clone(),
- ..Default::default()
- },
+ child_context,
turn_models,
provider_id,
model,
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 198584f101..a82b113e8e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -79,6 +79,30 @@ impl Default for OpenHumanRunContext {
}
impl OpenHumanRunContext {
+ /// Snapshot the values already scoped by a live legacy entrypoint.
+ ///
+ /// This is the transition boundary: roots construct one owned carrier from
+ /// their current scopes, then recursive paths pass [`Self::child`] instead
+ /// of depending on task-local inheritance. Explicit root inputs overwrite
+ /// these snapshots only when they intentionally own the same value.
+ pub(crate) fn from_current_scopes() -> Self {
+ let mut context = Self::new();
+ context.origin = crate::agent::turn_origin::current();
+ context.progress = crate::agent::progress_sink::current_progress_sink();
+ context.dispatch = crate::agent::harness::turn_dispatch_guard::current();
+ context.thread_id = crate::agent::tinyagents::thread_context::current_thread_id();
+ if let Some(slot) = crate::agent::tinyagents::current_route_slot() {
+ context.resolved_route = slot;
+ }
+ if let Some(cancellation) = crate::agent::tinyagents::current_run_cancellation() {
+ context.cancellation = cancellation;
+ }
+ context.workspace = crate::agent::turn_workspace::current()
+ .filter(|root| root.is_dir())
+ .map(|root| tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"));
+ context
+ }
+
/// Builds an unbound context. Entry points set only the values their turn
/// actually owns; `None` is an explicit absence, not an ambient fallback.
pub fn new() -> Self {
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index 3839afefe9..63505c5345 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -47,3 +47,60 @@ fn child_inherits_tree_handles_but_isolates_observations_and_usage() {
parent.cancellation.cancel();
assert!(child.cancellation.is_cancelled());
}
+
+#[tokio::test]
+async fn snapshots_live_root_scopes_before_child_dispatch() {
+ let root = tempfile::tempdir().expect("workspace");
+ let (progress, _rx) = tokio::sync::mpsc::channel(1);
+ let cancellation = tinyagents_harness::cancel::CancellationToken::new();
+ let route = std::sync::Arc::new(std::sync::Mutex::new(None));
+
+ crate::agent::turn_origin::with_origin(
+ crate::agent::turn_origin::AgentTurnOrigin::Cli,
+ crate::agent::turn_workspace::with_workspace(
+ root.path().to_path_buf(),
+ crate::agent::progress_sink::with_progress_sink(
+ progress.clone(),
+ crate::agent::tinyagents::thread_context::with_thread_id(
+ "thread-a",
+ crate::agent::tinyagents::with_route_slot(
+ route.clone(),
+ crate::agent::tinyagents::run_cancellation_context::with_run_cancellation(
+ cancellation.clone(),
+ crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(
+ None,
+ async {
+ let expected_dispatch =
+ crate::agent::harness::turn_dispatch_guard::current()
+ .expect("dispatch scope");
+ let captured = OpenHumanRunContext::from_current_scopes();
+ assert!(matches!(
+ captured.origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)
+ ));
+ assert!(captured.progress.is_some());
+ assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));
+ assert_eq!(
+ captured.workspace.expect("workspace").root,
+ root.path()
+ );
+ assert!(std::sync::Arc::ptr_eq(
+ captured.dispatch.as_ref().expect("dispatch"),
+ &expected_dispatch,
+ ));
+ assert!(std::sync::Arc::ptr_eq(
+ &captured.resolved_route,
+ &route
+ ));
+ cancellation.cancel();
+ assert!(captured.cancellation.is_cancelled());
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ )
+ .await;
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index fe5d7b53f2..c8fd373878 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -29,6 +29,7 @@ use crate::agent::tinyagents::host::steering::shared_steering_registry;
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::middleware::TurnContextMiddleware;
use crate::agent::tinyagents::observability::{CapPauser, OpenhumanEventBridge, SubagentScope};
+use crate::agent::tinyagents::run_cancellation_context::with_run_cancellation;
use crate::agent::tinyagents::turn_models::TurnModels;
use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;
use crate::agent::tinyagents::turn_policy::effective_max_iterations;
@@ -581,30 +582,47 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// nested inside its parent's drive future — leaving it inline on the stack
// overflows when the parent + child drives compose. Boxing keeps only a
// pointer on the stack at each level.
- let run_result = if streaming {
- let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
- let mut terminal = None;
- while let Some(item) = stream.next().await {
- match item {
- AgentStreamItem::Event(_) => {}
- AgentStreamItem::Completed(run) => {
- terminal = Some(Ok(*run));
- break;
+ // The generic model and middleware APIs still read thread/route scopes.
+ // Re-establish the values from the owned carrier here rather than relying
+ // on task-local inheritance from the root. This keeps detached/nested
+ // drives attached to the intended thread and route slot until the generic
+ // APIs accept `OpenHumanRunContext` directly.
+ let run_thread_id = run_context.thread_id.clone().unwrap_or_default();
+ let run_route_slot = run_context.resolved_route.clone();
+ let run_result = crate::agent::tinyagents::with_route_slot(run_route_slot, async move {
+ crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {
+ with_run_cancellation(cancellation.clone(), async {
+ if streaming {
+ let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));
+ let mut terminal = None;
+ while let Some(item) = stream.next().await {
+ match item {
+ AgentStreamItem::Event(_) => {}
+ AgentStreamItem::Completed(run) => {
+ terminal = Some(Ok(*run));
+ break;
+ }
+ AgentStreamItem::Failed { error, .. } => {
+ terminal =
+ Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
+ break;
+ }
+ }
+ }
+ terminal.unwrap_or_else(|| {
+ Err(tinyagents_harness::TinyAgentsError::Model(
+ "tinyagents stream ended without terminal run".to_string(),
+ ))
+ })
+ } else {
+ Box::pin(harness.invoke_in_context(&(), ctx, input)).await
}
- AgentStreamItem::Failed { error, .. } => {
- terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));
- break;
- }
- }
- }
- terminal.unwrap_or_else(|| {
- Err(tinyagents_harness::TinyAgentsError::Model(
- "tinyagents stream ended without terminal run".to_string(),
- ))
+ })
+ .await
})
- } else {
- Box::pin(harness.invoke_in_context(&(), ctx, input)).await
- };
+ .await
+ })
+ .await;
// Drive future returned: run cleanup now (abort poll task + deregister +
// requeue residual steers) rather than deferring to end-of-scope so the poll
// loop cannot deliver into the no-longer-drained handle during post-run
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index daa42e3297..dca258d471 100644
--- a/gitbooks/developing/architecture/agent-harness.md
+++ b/gitbooks/developing/architecture/agent-harness.md
@@ -488,14 +488,16 @@ When the backend doesn't surface a charged amount (older builds, providers that
## Explicit run context and host capabilities
-Phase B1 defines and tests an explicit `OpenHumanRunContext`, which converts to
-the canonical `RunContext`. It carries the future explicit values for origin,
-parent execution state, progress, attachment/artifact scope, dispatch and
-recency state, sandbox/depth, route observation, cancellation, thread,
-workspace and stop hooks. The live task-local and public-route cutovers remain
-deferred: no current turn receives this context yet. Its child rule will inherit
-shared tree handles while isolating child route observation and usage
-accounting, so a child cannot overwrite the parent turn's persisted facts.
+`OpenHumanRunContext` is now the live carrier at the shared chat, channel, and
+sub-agent turn seam. Roots snapshot their currently scoped origin, progress,
+dispatch state, thread, route slot, cancellation token, and workspace grant,
+then pass an owned context to the runner; a recursive sub-agent forks it with
+`child()`, preserving shared cancellation/policy handles while isolating route
+observation and usage accounting. The TinyAgents middleware registry is still
+specialized to `RunContext<()>`, so the seam currently maps its canonical
+cancellation and workspace values into that runtime context. Deleting the
+legacy scopes and using `RunContext<OpenHumanRunContext>` throughout remains a
+follow-up once that registry is generic.
`OpenHumanHostBundleFactory` is the B1 host composition point. It constructs
the context, definition, security, model, memory, budget, progress, learning,