Skip to content

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

Merge upstream/main into ta-leaf-7609b

Steven Enamakelecd1c260789b
diff --cc crates/openhuman-core/src/agent/hooks_scope.rs
index 62ab4a3e7e,fce4e756f8..e3c2ac076f
--- a/crates/openhuman-core/src/agent/hooks_scope.rs
+++ b/crates/openhuman-core/src/agent/hooks_scope.rs
@@@ -41,25 -40,31 +41,25 @@@ impl HookScope
self.stop.push(hook);
}
- /// Build a session with scoped tool/post-turn callbacks. Stop policies
- /// enter through the asynchronous dispatch scope when the turn runs.
- pub fn sync_scope<T>(self, build: impl FnOnce() -> T) -> T {
- ACTIVE.sync_scope(self, build)
+ /// The scope's own tool callbacks, in registration order.
+ pub fn tool_hooks(&self) -> &[Arc<dyn ToolHook>] {
+ &self.tools
}
- /// Run a dispatch with this scope. Nested scopes replace tool/post-turn
- /// callbacks and append their stop policies to the ambient policies.
- pub async fn scope<F: Future>(self, future: F) -> F::Output {
- let mut stop = crate::agent::stop_hooks::current_stop_hooks();
- stop.extend(self.stop.iter().cloned());
- crate::agent::stop_hooks::with_stop_hooks(stop, ACTIVE.scope(self, future)).await
+ /// The scope's own completed-turn callbacks, in registration order.
+ pub fn post_turn_hooks(&self) -> &[Arc<dyn PostTurnHook>] {
+ &self.post_turn
}
-}
-/// Session snapshot: process-wide tool callbacks, then the dispatch's callbacks.
-pub fn turn_tool_hooks() -> Vec<Arc<dyn ToolHook>> {
- let mut hooks = super::embedder_tool_hooks();
- let _ = ACTIVE.try_with(|scope| hooks.extend(scope.tools.iter().cloned()));
- hooks
-}
+ /// The scope's own stop policies, in registration order.
+ pub fn stop_hooks(
+ &self,
- ) -> &[Arc<dyn tinyagents_harness::middleware::StopHook<crate::agent::cost::TurnCost>>] {
++ ) -> &[Arc<dyn tinyagents_harness::middleware::StopHook<tinyagents_harness::cost::TurnCost>>] {
+ &self.stop
+ }
-/// Session snapshot: process-wide post-turn callbacks, then dispatch callbacks.
-pub fn turn_post_turn_hooks() -> Vec<Arc<dyn PostTurnHook>> {
- let mut hooks = super::embedder_post_turn_hooks();
- let _ = ACTIVE.try_with(|scope| hooks.extend(scope.post_turn.iter().cloned()));
- hooks
+ /// Whether the scope carries no callback of any kind.
+ pub fn is_empty(&self) -> bool {
+ self.tools.is_empty() && self.post_turn.is_empty() && self.stop.is_empty()
+ }
}
diff --cc crates/openhuman-core/src/agent/mod.rs
index ce1abb1232,35fb0c0a92..ba37e1eb28
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@@ -77,14 -77,11 +77,10 @@@ pub mod stop_hooks
pub mod subagent_host;
pub mod tinyagents;
pub mod todos;
- pub mod tool_policy;
-pub mod tool_snapshot_scope;
pub mod tools;
pub mod triage;
--/// Wall-clock deadline of one top-level turn: the outer backstop and the
--/// harness wind-down / hard-stop points derived from it.
- pub mod turn_deadline;
+/// Explicit per-turn host environment handed to the session an entry point runs.
+pub mod turn_env;
/// Turn-origin task-local — explicit trust/routing label scoped by every
/// entry point that invokes the agent (web chat, channel runtime, cron,
/// background jobs, CLI). Read by the approval gate to make
diff --cc crates/openhuman-core/src/agent/session_host/turn_backstop.rs
index fc6de93670,406b7299d6..8533bb611c
--- a/crates/openhuman-core/src/agent/session_host/turn_backstop.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn_backstop.rs
@@@ -1,4 -1,6 +1,6 @@@
- //! Wall-clock deadline of one top-level agent turn.
+ //! Host side of the wall-clock deadline of one top-level agent turn: the env
-//! override and the task-local scope. The deadline itself (`close_budget`
++//! override. The deadline itself (`close_budget`
+ //! included) is `tinyagents_harness::turn_deadline::TurnDeadline`.
//!
//! A web-chat turn runs under an outer backstop (`web_chat::ops::turn_guards`)
//! that drops the turn future when it elapses. Dropping it discards
@@@ -22,10 -24,10 +24,10 @@@
//! typed `Timeout` before the backstop drops the turn.
//!
//! For every positive backstop, `wind_down < hard_stop < backstop`
- //! (see `turn_deadline_tests.rs`).
+ //! (see `turn_backstop_tests.rs`).
//!
-//! The web-turn guard scopes the deadline on a task-local
-//! ([`with_turn_deadline`]). The top-level session turn
+//! The web-turn guard builds the deadline and hands it to the session it runs
+//! (`HostTurnEnv::turn_deadline`). The top-level session turn
//! (`OpenHumanSessionHost::turn_with_origin`) copies it onto its explicit run
//! context. Turns with no backstop, such as other channels or the CLI, carry
//! `None` and keep their previous behaviour.
@@@ -56,6 -45,23 +44,6 @@@ pub fn configured_backstop() -> Option<
parse_backstop(std::env::var(TURN_BACKSTOP_ENV).ok().as_deref())
}
-tokio::task_local! {
- static CURRENT_TURN_DEADLINE: TurnDeadline;
-}
-
-/// The deadline scoped on the current task, if any.
-pub fn current() -> Option<TurnDeadline> {
- CURRENT_TURN_DEADLINE.try_with(|deadline| *deadline).ok()
-}
-
-/// Run `future` with `deadline` scoped on the task (a no-op scope for `None`).
-pub async fn with_turn_deadline<F: Future>(deadline: Option<TurnDeadline>, future: F) -> F::Output {
- match deadline {
- Some(deadline) => CURRENT_TURN_DEADLINE.scope(deadline, future).await,
- None => future.await,
- }
-}
-
#[cfg(test)]
- #[path = "turn_deadline_tests.rs"]
+ #[path = "turn_backstop_tests.rs"]
mod tests;
diff --cc crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rs
index 0000000000,17dd9ca306..9b79ddbc14
mode 000000,100644..100644
--- a/crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rs
@@@ -1,0 -1,27 +1,15 @@@
+ use super::*;
+
+ #[test]
+ fn parse_backstop_defaults_and_disables() {
+ assert_eq!(parse_backstop(None), Some(Duration::from_secs(900)));
+ assert_eq!(
+ parse_backstop(Some("garbage")),
+ Some(Duration::from_secs(900))
+ );
+ assert_eq!(
+ parse_backstop(Some(" 120 ")),
+ Some(Duration::from_secs(120))
+ );
+ assert_eq!(parse_backstop(Some("0")), None);
+ }
-
-#[tokio::test]
-async fn task_local_scope_is_visible_inside_and_absent_outside() {
- assert!(current().is_none());
- let deadline = TurnDeadline::starting_now(Duration::from_secs(60));
- let seen = with_turn_deadline(Some(deadline), async { current() }).await;
- assert_eq!(seen, Some(deadline));
- assert!(current().is_none());
- assert!(with_turn_deadline(None, async { current() })
- .await
- .is_none());
-}
diff --cc crates/openhuman-core/src/agent/stop_hooks.rs
index 920a30ff72,631a2f363e..a03d900765
--- a/crates/openhuman-core/src/agent/stop_hooks.rs
+++ b/crates/openhuman-core/src/agent/stop_hooks.rs
@@@ -16,11 -14,12 +16,11 @@@
//! goal-budget hook ([`crate::agent::goals::runtime::GoalBudgetStopHook`]) is
//! the live implementation.
//!
-//! The per-turn tool budget ([`with_tool_call_limit`]) also lives here, on a
-//! task-local.
+//! The per-turn tool budget ([`tool_call_limit`]) also lives here; a host
+//! narrows it through `HostTurnEnv::tool_call_limit`.
- pub use crate::agent::cost::TurnCost;
+ use tinyagents_harness::cost::TurnCost;
use async_trait::async_trait;
-use std::sync::Arc;
use tinyagents_harness::middleware::{StopDecision, StopHook, TurnState};
diff --cc crates/openhuman-core/src/agent/stop_hooks_tests.rs
index e125a7ab75,6f51721794..a7daa44065
--- a/crates/openhuman-core/src/agent/stop_hooks_tests.rs
+++ b/crates/openhuman-core/src/agent/stop_hooks_tests.rs
@@@ -1,39 -1,76 +1,39 @@@
use super::*;
+use std::sync::Arc;
-#[tokio::test]
-async fn scoped_tool_limits_narrow_restore_and_keep_zero() {
- assert_eq!(tool_call_limit(10), 80);
- with_tool_call_limit(Some(4), async {
- assert_eq!(tool_call_limit(10), 4);
- with_tool_call_limit(Some(12), async {
- assert_eq!(tool_call_limit(10), 4);
- })
- .await;
- with_tool_call_limit(Some(0), async {
- assert_eq!(tool_call_limit(10), 0);
- })
- .await;
- assert_eq!(tool_call_limit(10), 4);
- with_tool_call_limit(None, async {
- assert_eq!(tool_call_limit(10), 4);
- })
- .await;
- })
- .await;
- assert_eq!(tool_call_limit(10), 80);
- with_tool_call_limit(Some(100), async {
- assert_eq!(tool_call_limit(1), 8);
- })
- .await;
+#[test]
+fn host_tool_cap_only_narrows_the_default_and_keeps_zero() {
+ assert_eq!(tool_call_limit(10, None), 80);
+ assert_eq!(tool_call_limit(10, Some(4)), 4);
+ // A cap wider than the product default never widens it.
+ assert_eq!(tool_call_limit(10, Some(1_000)), 80);
+ assert_eq!(tool_call_limit(1, Some(100)), 8);
+ // Zero is a real cap: no tool may run.
+ assert_eq!(tool_call_limit(10, Some(0)), 0);
}
-#[tokio::test]
-async fn concurrent_turns_do_not_share_tool_limits() {
- let (a, b) = tokio::join!(
- with_tool_call_limit(Some(2), async {
- tokio::task::yield_now().await;
- tool_call_limit(10)
- }),
- with_tool_call_limit(Some(7), async {
- tokio::task::yield_now().await;
- tool_call_limit(10)
- })
- );
- assert_eq!((a, b), (2, 7));
- assert_eq!(tool_call_limit(10), 80);
-}
-
-#[tokio::test]
-async fn cancelled_scope_restores_the_callers_tool_limit() {
- let mut scoped = Box::pin(with_tool_call_limit(Some(0), async {
- assert_eq!(tool_call_limit(10), 0);
- std::future::pending::<()>().await;
- }));
- assert!(futures::poll!(&mut scoped).is_pending());
- drop(scoped);
- assert_eq!(tool_call_limit(10), 80);
-}
-
-#[tokio::test]
-async fn scoped_stop_hooks_are_visible_to_run_contexts() {
+#[test]
+fn host_tool_cap_and_stop_hooks_flow_into_the_run_context_and_its_children() {
- let hook: Arc<dyn StopHook<crate::agent::cost::TurnCost>> = Arc::new(BudgetStopHook::new(1.0));
+ let hook: Arc<dyn StopHook<tinyagents_harness::cost::TurnCost>> = Arc::new(BudgetStopHook::new(1.0));
- assert!(current_stop_hooks().is_empty());
- with_stop_hooks(vec![Arc::clone(&hook)], async {
- let active = current_stop_hooks();
- assert_eq!(active.len(), 1);
- assert_eq!(active[0].name(), "budget");
- assert_eq!(
- crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .stop_hooks
- .len(),
- 1
- );
- })
- .await;
- assert!(current_stop_hooks().is_empty());
+ let mut hooks = crate::agent::hooks::HookScope::default();
+ hooks.push_stop(Arc::clone(&hook));
+ let env = crate::agent::turn_env::HostTurnEnv {
+ tool_call_limit: Some(3),
+ hooks,
+ ..Default::default()
+ };
+ let context = crate::agent::tinyagents::host::OpenHumanRunContext::new().with_host_env(&env);
+ assert_eq!(context.tool_call_limit, Some(3));
+ assert_eq!(context.stop_hooks.len(), 1);
+ assert_eq!(context.stop_hooks[0].name(), "budget");
+ // Sub-agents inherit both through the explicit child carrier.
+ let child = context.child();
+ assert_eq!(child.tool_call_limit, Some(3));
+ assert_eq!(child.stop_hooks.len(), 1);
+ // A context built without an env carries nothing ambient.
+ let bare = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ assert_eq!(bare.tool_call_limit, None);
+ assert!(bare.stop_hooks.is_empty());
}
#[tokio::test]
diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 392ce55e1e,263e40ab25..24e81cd735
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@@ -282,15 -282,7 +282,15 @@@ pub struct OpenHumanRunContext
/// UI/event progress receiver for this turn tree.
pub progress: Option<Sender<AgentProgress>>,
/// Stop policies evaluated after each model call.
- pub stop_hooks: Vec<Arc<dyn StopHook<crate::agent::cost::TurnCost>>>,
+ pub stop_hooks: Vec<Arc<dyn StopHook<tinyagents_harness::cost::TurnCost>>>,
+ /// Agent/turn tool callbacks, registered after the runtime's global ones.
+ pub tool_hooks: Vec<Arc<dyn crate::agent::hooks::ToolHook>>,
+ /// Host cap on real tool invocations for this turn tree; `None` leaves the
+ /// product default. Inherited by children.
+ pub tool_call_limit: Option<usize>,
+ /// This turn's input is untrusted data (a host-only reviewer reading a PR
+ /// diff), so the security gate built for it does not screen the input.
+ pub untrusted_input_turn: bool,
/// Wall-clock deadline of the top-level turn this run belongs to, set
/// only by the session turn entry point from the web backstop
/// (`agent::turn_deadline`). The harness winds the run down and clamps
@@@ -388,18 -380,6 +388,18 @@@
pub(crate) memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
}
+/// The host callbacks and caps a turn's harness assembly installs, taken from
+/// the explicit run context.
+#[derive(Clone, Default)]
+pub(crate) struct HarnessHostPolicy {
+ /// Stop policies evaluated after each model call.
- pub(crate) stop_hooks: Vec<Arc<dyn StopHook<crate::agent::cost::TurnCost>>>,
++ pub(crate) stop_hooks: Vec<Arc<dyn StopHook<tinyagents_harness::cost::TurnCost>>>,
+ /// Agent/turn tool callbacks, registered after the runtime's global ones.
+ pub(crate) tool_hooks: Vec<Arc<dyn crate::agent::hooks::ToolHook>>,
+ /// The host's cap on real tool invocations.
+ pub(crate) tool_call_cap: Option<usize>,
+}
+
/// Minimal immutable authority view exposed to shared tools through the
/// harness's typed state-view seam.
#[derive(Clone, Debug, Default)]
diff --cc crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index 1da7d4b461,2e1cc0f2c4..2cfa38bea8
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@@ -77,12 -76,19 +77,12 @@@ wher
F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
{
match deadline {
- // Scope the deadline on the task so the session turn hands it to the
- // harness (`agent::session_host::turn_backstop`), which winds down before `d`. The
- // turn future is boxed: it is very large, and the scope wrapper would
- // otherwise hold it inline a second time and overflow the worker stack.
- Some(d) => match tokio::time::timeout(
- d,
- crate::agent::session_host::turn_backstop::with_turn_deadline(
- Some(tinyagents_harness::turn_deadline::TurnDeadline::starting_now(d)),
- Box::pin(fut),
- ),
- )
- .await
- {
+ // The session turn carries the matching `TurnDeadline` on its explicit
+ // host environment (`run_turn_under_cancel_and_deadline`), so the
- // harness (`agent::turn_deadline`) winds down before `d`. The turn
++ // harness (`agent::session_host::turn_backstop`) winds down before `d`. The turn
+ // future is boxed: it is very large and would otherwise be held inline
+ // by the timeout wrapper and overflow the worker stack.
+ Some(d) => match tokio::time::timeout(d, Box::pin(fut)).await {
Ok(res) => res,
Err(_elapsed) => {
log::warn!(
diff --cc scripts/ci/agent-runtime-boundary-baseline.json
index 12cadeef6b,bcd93de731..cdaca8b43e
--- a/scripts/ci/agent-runtime-boundary-baseline.json
+++ b/scripts/ci/agent-runtime-boundary-baseline.json
@@@ -239,8 -288,15 +239,8 @@@
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/session_host/builder/host_tools.rs",
- "line": 366,
- "text": "let root = crate::agent::turn_workspace::current()?;",
- "occurrence": 1
- },
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/session_host/runtime_session.rs",
- "line": 538,
+ "path": "crates/openhuman-core/src/agent/session_host/runtime_session/parent_snapshot.rs",
- "line": 34,
++ "line": 36,
"text": "workspace_descriptor: crate::agent::harness::current_parent()",
"occurrence": 1
},
@@@ -324,7 -380,7 +324,7 @@@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/turn_origin.rs",
-- "line": 390,
++ "line": 385,
"text": "pub fn current_request_id() -> Option<String> {",
"occurrence": 1
},
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 5d5e7bc7c1,d635b0d599..6355e354c6
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -27,16 -27,16 +27,16 @@@ const LEGACY_LIMIT_ENTRIES =
// under the general 750 limit, so it needs no exception at all.
// The session-todo integration added transcript metadata construction to
// this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1084],
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1124],
++ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1080],
// `[components] juice` test constructor (tokenjuice gate tests).
["crates/openhuman-core/src/core/runtime/context.rs", 753],
// Session-host factory still assembles the product's deliberately coupled
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 975],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 974],
["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1247],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1046],
+ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1045],
["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1261],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
diff --cc scripts/ci/saas-ambient-baseline.json
index bfde04be0c,2397431a84..d31b075586
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@@ -128,7 -128,7 +128,7 @@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/agent/turn_origin.rs",
-- "line": 382,
++ "line": 377,
"text": "tokio::spawn(propagate(fut))",
"occurrence": 1
},