Skip to content

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

refactor(agent): carry shared turn context explicitly

Steven Enamakel41b614dcda05
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index 652da75d5f..2a41fae6cd 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -115,6 +115,10 @@ pub(crate) async fn run_channel_turn_via_graph(
"[channel:graph] routing channel turn through tinyagents harness"
);
let outcome = run_turn_via_tinyagents_shared(
+ crate::agent::tinyagents::host::OpenHumanRunContext {
+ progress: on_progress.clone(),
+ ..Default::default()
+ },
turn_models,
provider_id,
model,
@@ -122,9 +126,6 @@ pub(crate) async fn run_channel_turn_via_graph(
vec![extra_arc, tools_registry],
allowed,
max_iterations,
- // Mirror the harness event stream onto AgentProgress when the caller
- // (e.g. channel dispatch) supplied a progress sink.
- on_progress,
// Top-level (parent) turn — no child-progress attribution.
None,
// Resolved above — drives the context-window summarization step.
@@ -147,8 +148,6 @@ pub(crate) async fn run_channel_turn_via_graph(
crate::agent::tinyagents::TurnContextMiddleware::defaults(),
// Channel/CLI path carries its own gating; no session `.tool_policy()`.
None,
- // Channel turns do not yet carry SDK workspace descriptors.
- None,
// Interactive channel/CLI turn — never serve a cached model response.
false,
// #4457 (defect C): the channel/CLI path has no post-run wrap-up and does
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 fb73577612..30c99c631c 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
@@ -113,6 +113,12 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
let provider_id = graph.turn_models.provider_id().to_string();
with_current_sandbox_mode(graph.sandbox_mode, async {
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()
+ },
graph.turn_models,
provider_id,
&graph.model,
@@ -126,8 +132,6 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
vec![graph.tools, graph.synthesized_tools],
visible_tool_names,
graph.max_iterations,
- // Mirror the harness event stream onto this session's progress sink.
- graph.on_progress,
// Top-level chat turn — no child-progress attribution.
None,
graph.context_window,
@@ -156,10 +160,6 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
graph.context_mw,
// Builder-configured tool policy enforcement (session chat path).
graph.tool_policy,
- // Per-profile dedicated workspace descriptor (section D). `None` for the
- // common shared-`action_dir` case; `Some` binds acting tools' default
- // cwd to `<action_dir>/profiles/<id>` for a `dedicated_workspace` profile.
- graph.workspace_descriptor,
// Interactive chat turn — response caching MUST stay off so a live user
// turn is never served a cached model response (correctness/safety).
false,
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 3d4a45c624..45634b92d0 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
@@ -260,6 +260,11 @@ pub(in super::super) async fn run_subagent_via_graph(
let native_tools = turn_models.native_tools();
let provider_id = turn_models.provider_id().to_string();
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()
+ },
turn_models,
provider_id,
model,
@@ -279,8 +284,6 @@ pub(in super::super) async fn run_subagent_via_graph(
// inheriting the parent's full surface (shell/file-write/spawn).
Some(allowed_names),
max_iterations,
- // Parent's progress sink — child events ride it, scoped below.
- on_progress,
subagent_scope,
// Resolved above — drives the sub-agent context-window summarization step.
context_window,
@@ -312,8 +315,6 @@ pub(in super::super) async fn run_subagent_via_graph(
// Sub-agents gate via their own SubagentToolSource policy path, not the
// session `.tool_policy()`; no enforcement threaded here.
None,
- // Isolated worker descriptor, when worktree isolation prepared one.
- workspace_descriptor,
// Sub-agent turns run tools with external effects; not a deterministic
// internal run, so response caching stays off (safe default).
false,
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 59b75a0eaa..198584f101 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -4,8 +4,11 @@
//! This type owns the product values that used to be recovered from ambient
//! task-locals: approval origin, host progress, attachment and artifact scope,
//! parent dispatch state, and the handles a tool needs to continue a run.
-//! Phase B1 defines and tests this canonical conversion; it is not yet the live
-//! turn carrier. The task-local and public-route cutovers remain later work.
+//! The shared turn seam receives this as its live OpenHuman carrier. The
+//! existing middleware registry still uses `RunContext<()>`, so that seam maps
+//! only canonical TinyAgents values (cancellation and workspace) while the
+//! remaining host-local consumers migrate. `into_tinyagents` is the target
+//! conversion once the middleware registry becomes generic over this carrier.
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -23,8 +26,7 @@ use crate::agent::tinyagents::resolved_route::RouteSlot;
use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
use crate::agent::turn_origin::AgentTurnOrigin;
-/// Explicit OpenHuman data carried by a prospective top-level or child agent
-/// run once the Phase B task-local cutover wires it into live invocation.
+/// Explicit OpenHuman data carried by a top-level or child agent run.
///
/// Shared members (`Arc`s, cancellation and workspace descriptor) retain the
/// identity required by a recursive run tree. [`Self::child`] deliberately
diff --git a/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs b/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs
index eda475617b..b92877b87e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs
@@ -21,7 +21,6 @@ async fn selected_model_records_concrete_route_and_fallback_overwrites_primary()
let primary = RouteRecordingModel::new(Arc::new(SuccessfulModel), "openhuman", "chat-v1");
let fallback =
RouteRecordingModel::new(Arc::new(SuccessfulModel), "anthropic", "claude-sonnet-4");
-
let observed = with_resolved_provider_route_scope(async {
primary
.invoke(&(), ModelRequest::default())
@@ -47,7 +46,6 @@ async fn selected_model_records_concrete_route_and_fallback_overwrites_primary()
#[tokio::test]
async fn streamed_model_records_concrete_route_before_stream_consumption() {
let model = RouteRecordingModel::new(Arc::new(SuccessfulModel), "openhuman", "reasoning-v1");
-
let observed = with_resolved_provider_route_scope(async {
let _stream = model
.stream(&(), ModelRequest::default())
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index da412bc7e9..fe5d7b53f2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -20,18 +20,15 @@ use tinyagents_harness::context::{RunConfig, RunContext};
use tinyagents_harness::events::EventSink;
use tinyagents_harness::store::StoreRegistry;
use tinyagents_registry::DiagnosticSeverity;
-use tinytools::WorkspaceDescriptor;
-use tokio::sync::mpsc::Sender;
use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
use crate::agent::harness::{run_queue::RunQueue, MAX_SPAWN_DEPTH};
use crate::agent::messages::ChatMessage;
-use crate::agent::progress::AgentProgress;
use crate::agent::tinyagents::harness_assembly::{assemble_turn_harness, AssembledTurnHarness};
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;
@@ -199,6 +196,7 @@ pub(crate) async fn run_turn_via_tinyagents(
/// the question via [`TinyagentsTurnOutcome::early_exit_tool`].
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_turn_via_tinyagents_shared(
+ run_context: OpenHumanRunContext,
turn_models: TurnModels,
provider_id: String,
model: &str,
@@ -206,7 +204,6 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,
allowed: Option<HashSet<String>>,
max_iterations: usize,
- on_progress: Option<Sender<AgentProgress>>,
subagent_scope: Option<SubagentScope>,
context_window: Option<u64>,
run_queue: Option<Arc<RunQueue>>,
@@ -215,7 +212,6 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
max_output_tokens: Option<u32>,
context_mw: TurnContextMiddleware,
tool_policy: Option<ToolPolicyEnforcement>,
- workspace_descriptor: Option<WorkspaceDescriptor>,
deterministic_cacheable: bool,
// #4457 (defect C): when `true`, the seam does NOT emit the terminal
// `TurnCompleted` — the caller emits it itself *after* its post-run wrap-up
@@ -227,6 +223,10 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// `false` and rely on this seam's emit for parity with the legacy engine.
defer_turn_completed_to_caller: bool,
) -> Result<TinyagentsTurnOutcome> {
+ // The host context is the sole turn carrier. Pulling the sender into this
+ // local keeps the event bridge API compact without creating a second
+ // parameter path for progress.
+ let on_progress = run_context.progress.clone();
// `0` means "unset" → the legacy default (a native-bus / test convention);
// otherwise the harness model-call cap would be zero and abort the run before
// the first provider call.
@@ -360,15 +360,14 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// Build the run context: an optional event sink feeds the progress/cost
// bridge (streaming) and/or the model-call-cap pauser; the shared steering
// handle carries mid-flight, early-exit, and cap pauses.
- let cancellation = tinyagents_harness::CancellationToken::new();
+ let cancellation = run_context.cancellation.clone();
+ // The OpenHuman carrier remains the entry boundary even while the current
+ // harness middleware inventory is specialized to `()`. Map only the
+ // canonical generic values here; the follow-up changes every middleware to
+ // `OpenHumanRunContext` and replaces this bridge with `into_tinyagents`.
let mut ctx = RunContext::new(config, ()).with_cancellation(cancellation.clone());
- if let Some(descriptor) = workspace_descriptor {
- tracing::debug!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[tinyagents] attaching workspace descriptor"
- );
- ctx = ctx.with_workspace(descriptor);
+ if let Some(workspace) = run_context.workspace.clone() {
+ ctx = ctx.with_workspace(workspace);
}
// Assemble the run's store registry: the tool-result artifact index (when
// present) and — behind the default-ON session dual-write flag — the
@@ -473,7 +472,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
// The child still gets its advisory `Pause` either way.
let dispatch_guard = subagent_scope
.is_none()
- .then(crate::agent::harness::turn_dispatch_guard::current)
+ .then(|| run_context.dispatch.clone())
.flatten();
events.subscribe(CapPauser::new(
handle.clone(),
@@ -506,7 +505,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {
request_id: Some(request_id),
..
- }) = crate::agent::turn_origin::current()
+ }) = run_context.origin.as_ref()
{
journal::register_request_journal_run(&request_id, journal_run_id.as_str());
}
@@ -527,14 +526,14 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
let steer_thread_label = subagent_scope
.as_ref()
.map(|s| s.task_id.clone())
- .or_else(|| match crate::agent::turn_origin::current() {
+ .or_else(|| match run_context.origin.as_ref() {
Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {
- Some(thread_id)
+ Some(thread_id.clone())
}
Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
reply_target,
..
- }) => Some(reply_target),
+ }) => Some(reply_target.clone()),
_ => None,
})
.unwrap_or_default();
@@ -582,33 +581,30 @@ 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 = 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;
- }
+ 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;
+ }
+ 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
}
- })
- .await;
+ 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
+ };
// 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/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
index 9e86798faf..c411fda94e 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
@@ -441,9 +441,10 @@ fn project_managed_usage(mut response: ModelResponse) -> ModelResponse {
response
}
-/// Inject the ambient `thread_id` (when set) into the request's
-/// `provider_options` so the crate emits it as a top-level `thread_id` body field
-/// — parity with the host `with_openhuman_thread_id` extension.
+/// Inject the current run's thread into provider options. Root entrypoints that
+/// have not yet migrated to the explicit run carrier still establish this
+/// scope; the shared-runner cutover preserves that boundary until those routes
+/// pass `OpenHumanRunContext.thread_id` end-to-end.
fn with_thread_id(mut request: ModelRequest) -> ModelRequest {
let Some(thread_id) = thread_context::current_thread_id() else {
return request;
@@ -455,8 +456,7 @@ fn with_thread_id(mut request: ModelRequest) -> ModelRequest {
if let Some(map) = options.as_object_mut() {
map.insert("thread_id".to_string(), Value::String(thread_id));
}
- request = request.with_provider_options(options);
- request
+ request.with_provider_options(options)
}
/// Publish a `SessionExpired` event when the local `exp` precheck in
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
index c900d3f0d3..d6ec531ccb 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
@@ -25,7 +25,6 @@ async fn with_thread_id_injects_when_ambient_thread_present() {
#[test]
fn with_thread_id_is_noop_without_ambient_thread() {
- // No thread scope active → provider_options stays whatever it was (null).
let request = ModelRequest::new(vec![Message::user("hi")]);
let updated = with_thread_id(request);
assert!(updated.provider_options.get("thread_id").is_none());