The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(subagent): consolidate spawn depth tracking into tinyagents run context
Steven Enamakelf132691b401a
diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rsindex 952ef10aa6..ec7bf11fdb 100644--- a/crates/openhuman-core/src/agent/harness/mod.rs+++ b/crates/openhuman-core/src/agent/harness/mod.rs@@ -26,7 +26,6 @@ pub mod definition;pub(crate) mod definition_loader;pub mod fork_context;pub(crate) mod graph;-pub(crate) mod spawn_depth_context;pub(crate) mod tool_result_artifacts;// NOTE: deliberately no flat re-export here. `artifact_offload::ArtifactKind`@@ -39,6 +38,5 @@ pub use definition::{pub use fork_context::{current_parent, with_parent_context, AgentContextPreparedSource, ParentExecutionContext,};-pub(crate) use spawn_depth_context::{with_spawn_depth, MAX_SPAWN_DEPTH};pub(crate) use graph::run_channel_turn_via_graph;diff --git a/crates/openhuman-core/src/agent/harness/spawn_depth_context.rs b/crates/openhuman-core/src/agent/harness/spawn_depth_context.rsdeleted file mode 100644index 8338b75df1..0000000000--- a/crates/openhuman-core/src/agent/harness/spawn_depth_context.rs+++ /dev/null@@ -1,66 +0,0 @@-//! Task-local spawn-depth tracking for nested sub-agent delegation.-//!-//! Loader-time tier validation prevents built-in and workspace agent-//! definitions from declaring recursive hierarchies, but runtime calls can-//! still arrive through tools and MCP surfaces. This task-local is the-//! defence-in-depth layer that caps the active `run_subagent` chain.-//!-//! ## Relationship to the crate recursion authority (issue #4249, 07.3)-//!-//! The single *value* authority for the depth cap is [`MAX_SPAWN_DEPTH`]: the-//! TinyAgents run is configured with `RunPolicy.limits.max_depth = MAX_SPAWN_DEPTH`-//! (`tinyagents::mod::run_policy_for`) and `RunConfig::with_max_depth`, and the-//! crate rejects an over-deep sub-agent invocation with-//! `TinyAgentsError::SubAgentDepth`, which is mapped back onto the *same*-//! [`crate::agent::subagent_host::SubagentRunError::SpawnDepthExceeded`] surface as the-//! pre-dispatch check (`tinyagents::mod::tinyagents_depth_error`). So there is one-//! error shape and one cap constant.-//!-//! This module stays a thin **reader/projector** rather than collapsing into the-//! crate's in-process recursion stack because two things the crate stack does not-//! see still need the depth:-//!-//! 1. **Cross-process transport.** OpenHuman spawns child `claude` processes that-//! re-enter the core over the loopback MCP HTTP hop; the crate's per-run-tree-//! recursion stack does not cross that boundary. `current_spawn_depth` feeds-//! `mcp::server::subagent_depth` which stamps/reads the depth on that hop.-//! 2. **Synchronous pre-dispatch surface.** `subagent_host` rejects an over-deep-//! spawn *before* building the TinyAgents run (so the caller gets the depth-//! error without a provider round-trip); tests assert this surface directly.-//!-//! Both consumers read this task-local against [`MAX_SPAWN_DEPTH`] — they do not-//! introduce a second, divergent cap.--/// Maximum number of nested `run_subagent` scopes allowed in one task.-///-/// Depth counts sub-agent runs, not the root user-facing agent turn, so the-/// intended deepest path is `chat -> reasoning -> worker`:-///-/// * reasoning sub-agent: depth 1-/// * worker spawned by reasoning: depth 2-/// * one final worker handoff: depth 3-pub(crate) const MAX_SPAWN_DEPTH: usize = 3;--tokio::task_local! {- /// Current active `run_subagent` nesting depth for this task.- static CURRENT_SPAWN_DEPTH: usize;-}--/// Return the active sub-agent nesting depth for this task.-///-/// Direct callers outside [`with_spawn_depth`] are at depth 0.-pub(crate) fn current_spawn_depth() -> usize {- CURRENT_SPAWN_DEPTH.try_with(|depth| *depth).unwrap_or(0)-}--/// Run `future` with a specific active sub-agent depth.-pub(crate) async fn with_spawn_depth<F, R>(depth: usize, future: F) -> R-where- F: std::future::Future<Output = R>,-{- CURRENT_SPAWN_DEPTH.scope(depth, future).await-}--#[cfg(test)]-#[path = "spawn_depth_context_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/spawn_depth_context_tests.rs b/crates/openhuman-core/src/agent/harness/spawn_depth_context_tests.rsdeleted file mode 100644index 51f8036ab1..0000000000--- a/crates/openhuman-core/src/agent/harness/spawn_depth_context_tests.rs+++ /dev/null@@ -1,26 +0,0 @@-use super::*;--#[tokio::test]-async fn current_spawn_depth_defaults_to_zero() {- assert_eq!(current_spawn_depth(), 0);-}--#[tokio::test]-async fn with_spawn_depth_scopes_value_to_future() {- let observed = with_spawn_depth(2, async { current_spawn_depth() }).await;- assert_eq!(observed, 2);- assert_eq!(current_spawn_depth(), 0);-}--#[tokio::test]-async fn nested_spawn_depth_scope_restores_outer_value() {- with_spawn_depth(1, async {- assert_eq!(current_spawn_depth(), 1);- with_spawn_depth(2, async {- assert_eq!(current_spawn_depth(), 2);- })- .await;- assert_eq!(current_spawn_depth(), 1);- })- .await;-}diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rsindex d0bd445c7d..9c44ae4963 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/mod.rs@@ -64,7 +64,7 @@ pub(super) use crate::agent::harness::definition::{AgentDefinition, PromptSource#[cfg(test)]pub(super) use crate::agent::harness::fork_context::ParentExecutionContext;#[cfg(test)]-pub(super) use crate::agent::harness::{with_spawn_depth, MAX_SPAWN_DEPTH};+pub(super) use crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;#[cfg(test)]use tinytools::ToolSpec;diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex 15dfa98366..6762c49802 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -19,9 +19,8 @@ use crate::agent::harness::definition::{PromptSource, SandboxMode as AgentSandboxMode,};use crate::agent::harness::fork_context::ParentExecutionContext;-use crate::agent::harness::{- spawn_depth_context::current_spawn_depth, with_spawn_depth, MAX_SPAWN_DEPTH,-};+use crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;+use tinyagents_harness::context::{current_run_depth, with_run_depth, RunConfig, RunDepth};use crate::agent::prompts::{render_subagent_system_prompt_with_format, PromptContext, SubagentRenderOptions,};@@ -115,7 +114,7 @@ use result_cap::apply_max_result_chars;pub(crate) async fn run_subagent_direct(definition: &AgentDefinition,task_prompt: &str,- options: SubagentRunOptions,+ mut options: SubagentRunOptions,) -> Result<SubagentRunOutcome, SubagentRunError> {// Unconditionally heap-allocate the entire run_subagent body so// every caller doesn't have to carry this future's state inline.@@ -223,32 +222,17 @@ pub(crate) async fn run_subagent_direct(.clone().ok_or(SubagentRunError::NoParentContext)?;let started = Instant::now();- // Typed callers carry their depth in the run context. Direct callers- // are scoped by `with_spawn_depth`; honor both authorities and count- // this child spawn exactly once.- let attempted_depth = options- .run_context- .spawn_depth- .max(current_spawn_depth().saturating_add(1));-- // Synchronous pre-dispatch projection of the single depth authority- // (`MAX_SPAWN_DEPTH`, also fed to the crate's `RunPolicy.limits.max_depth`).- // This surfaces `SpawnDepthExceeded` before a provider round-trip and- // across the MCP process hop; the crate's `TinyAgentsError::SubAgentDepth`- // maps onto this same error shape for over-deep in-process runs.- if attempted_depth > crate::agent::tinyagents::budget::depth(&options.run_context) {- tracing::warn!(- agent_id = %definition.id,- task_id = %task_id,- attempted_depth,- max_depth = MAX_SPAWN_DEPTH,- "[subagent_host] spawn depth exceeded"- );- return Err(SubagentRunError::SpawnDepthExceeded {- attempted_depth,- max_depth: crate::agent::tinyagents::budget::depth(&options.run_context),- });- }+ // The host carries an already-derived child depth; native and MCP+ // callers expose their parent depth through TinyAgents' context.+ let parent_depth = options.run_context.spawn_depth.saturating_sub(1)+ .max(current_run_depth().map_or(0, |facts| facts.depth));+ let max_depth = crate::agent::tinyagents::budget::depth(&options.run_context);+ let attempted_depth = RunConfig::checked_child_depth(parent_depth, max_depth)+ .map_err(|_| SubagentRunError::SpawnDepthExceeded {+ attempted_depth: parent_depth.saturating_add(1),+ max_depth,+ })?;+ options.run_context.spawn_depth = attempted_depth;// Runtime spawn-hierarchy (tier) gate — defense-in-depth alongside the// depth gate above. The loader validates *declared* `subagents` pairs@@ -334,7 +318,7 @@ pub(crate) async fn run_subagent_direct("[subagent_host] worktree-isolated worker: descriptor will route acting-tool CWD");}- let run_result = Box::pin(with_spawn_depth(attempted_depth, async {+ let run_result = Box::pin(with_run_depth(RunDepth { depth: attempted_depth, max_depth }, async {crate::memory::scope::within_agent(&definition.id, with_file_state_agent_id(task_id.clone(), async {async {Box::pin(run_typed_mode(diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rsindex 45a89c181f..c2264393f2 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_model_resolution_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::agent::harness::spawn_depth_context::current_spawn_depth;+use tinyagents_harness::context::{current_run_depth, with_run_depth, RunDepth};use crate::agent::subagent_host::run_subagent;#[tokio::test]@@ -9,7 +9,7 @@ async fn runner_rejects_spawn_beyond_max_depth() {let def = make_def_named_tools(&[]);let result = with_parent_context(parent, async {- with_spawn_depth(MAX_SPAWN_DEPTH, async {+ with_run_depth(RunDepth { depth: MAX_SPAWN_DEPTH, max_depth: MAX_SPAWN_DEPTH }, async {run_subagent(&def, "x", SubagentRunOptions::default()).await}).await@@ -31,8 +31,8 @@ async fn runner_rejects_spawn_beyond_max_depth() {"depth rejection must happen before provider dispatch");assert_eq!(- current_spawn_depth(),- 0,+ current_run_depth(),+ None,"depth task-local must not leak after rejection");}diff --git a/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rsindex b4d76d8de8..162d09350c 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops_tests_slug_filter_typed_mode_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::agent::harness::spawn_depth_context::current_spawn_depth;+use tinyagents_harness::context::{current_run_depth, with_run_depth, RunDepth};use crate::agent::subagent_host::run_subagent;#[test]@@ -580,7 +580,7 @@ async fn runner_allows_spawn_at_max_depth() {let def = make_def_named_tools(&[]);let outcome = with_parent_context(parent, async {- with_spawn_depth(MAX_SPAWN_DEPTH - 1, async {+ with_run_depth(RunDepth { depth: MAX_SPAWN_DEPTH - 1, max_depth: MAX_SPAWN_DEPTH }, async {run_subagent(&def, "x", SubagentRunOptions::default()).await}).await@@ -591,8 +591,8 @@ async fn runner_allows_spawn_at_max_depth() {assert_eq!(outcome.output, "ok");assert_eq!(provider.captured.lock().len(), 1);assert_eq!(- current_spawn_depth(),- 0,+ current_run_depth(),+ None,"depth task-local must not leak after the run");}diff --git a/crates/openhuman-core/src/agent/tinyagents/budget.rs b/crates/openhuman-core/src/agent/tinyagents/budget.rsindex 8f4b2ff886..a711a539f6 100644--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs@@ -1,5 +1,8 @@//! Host budget policy, scoped once at admission and carried explicitly to children.use std::sync::Arc;++/// Product recursion ceiling shared by native and MCP delegation.+pub(crate) const MAX_SPAWN_DEPTH: usize = 3;pub use tinyinference_llm::model::budget::{Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits,};@@ -53,8 +56,8 @@ pub(crate) fn spawn_depth_limit() -> Option<usize> {pub(crate) fn depth(context: &super::host::OpenHumanRunContext) -> usize {context.max_spawn_depth- .unwrap_or(crate::agent::harness::MAX_SPAWN_DEPTH)- .min(crate::agent::harness::MAX_SPAWN_DEPTH)+ .unwrap_or(crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH)+ .min(crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH)}pub(super) fn install_depth(harness: &mut tinyagents_harness::runtime::AgentHarness<(), super::host::OpenHumanRunContext>,diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 62830f22f6..fccb1a1022 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -552,9 +552,16 @@ impl OpenHumanRunContext {/// `tinytools::WorkspaceDescriptor`; no type alias, re-export or task-local/// bridge is involved.pub fn into_tinyagents(- self,+ mut self,mut config: tinyagents_harness::context::RunConfig,) -> tinyagents_harness::context::RunContext<Self> {+ // Imported transport facts and explicit child context must survive entry+ // into the native driver, which scopes the depth recorded in RunConfig.+ let depth = config.depth().max(self.spawn_depth).max(+ tinyagents_harness::context::current_run_depth().map_or(0, |facts| facts.depth),+ );+ self.spawn_depth = depth;+ config = config.with_depth(depth);if config.thread_id.is_none() {if let Some(thread_id) = self.thread_id.as_deref() {config = config.with_thread(thread_id);diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rsindex cc1c2f83eb..2ef283db3b 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs@@ -5,7 +5,7 @@use tinyagents_harness::retry::RetryPolicy;use tinyagents_harness::runtime::{InvalidArgsPolicy, RunPolicy, UnknownToolPolicy};-use crate::agent::harness::MAX_SPAWN_DEPTH;+use crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;/// The builder-configured [`ToolPolicy`](crate::agent::tool_policy::ToolPolicy)/// plus the session context a policy check needs, handed to the shared turn seamdiff --git a/crates/openhuman-core/src/mcp/server/subagent_depth.rs b/crates/openhuman-core/src/mcp/server/subagent_depth.rsindex 90c1ddb52e..96e1bb5235 100644--- a/crates/openhuman-core/src/mcp/server/subagent_depth.rs+++ b/crates/openhuman-core/src/mcp/server/subagent_depth.rs@@ -33,23 +33,22 @@ pub const HEADER_SUBAGENT_DEPTH: &str = "X-OpenHuman-Subagent-Depth";/// Keep this as an alias to the harness limit so MCP, OpenHuman subagent/// execution, and TinyAgents `RunLimits.max_depth` all reject at the same/// nesting boundary.-pub const MAX_SUBAGENT_DEPTH: usize = crate::agent::harness::MAX_SPAWN_DEPTH;--tokio::task_local! {- static CHAIN_DEPTH: usize;-}+pub const MAX_SUBAGENT_DEPTH: usize = crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;/// Depth of the current delegation chain, or 0 when not inside one (top-level/// chat turns, ordinary tool calls).pub fn current_depth() -> usize {- CHAIN_DEPTH.try_with(|d| *d).unwrap_or(0)+ tinyagents_harness::context::current_run_depth().map_or(0, |facts| facts.depth)}/// Run `fut` with the delegation-chain depth set to `depth`. Nested awaits in/// the same task (the spawned agent's run, its Claude Code turns, …) observe it/// via [`current_depth`].pub async fn scope<F: Future>(depth: usize, fut: F) -> F::Output {- CHAIN_DEPTH.scope(depth, fut).await+ tinyagents_harness::context::with_run_depth(+ tinyagents_harness::context::RunDepth { depth, max_depth: MAX_SUBAGENT_DEPTH },+ fut,+ ).await}/// Parse the incoming depth header value. The header is external input, sodiff --git a/crates/openhuman-core/src/mcp/server/subagent_depth_tests.rs b/crates/openhuman-core/src/mcp/server/subagent_depth_tests.rsindex 007fb30471..10b9e7d5ca 100644--- a/crates/openhuman-core/src/mcp/server/subagent_depth_tests.rs+++ b/crates/openhuman-core/src/mcp/server/subagent_depth_tests.rs@@ -45,6 +45,9 @@ async fn incoming_mcp_depth_is_visible_to_the_native_harness_and_refuses_a_fourtscope(incoming, async {let facts = tinyagents_harness::context::current_run_depth().expect("MCP ingress installs native recursion facts");+ let native = crate::agent::tinyagents::host::OpenHumanRunContext::new()+ .into_tinyagents(tinyagents_harness::context::RunConfig::new("mcp-ingress").with_max_depth(MAX_SUBAGENT_DEPTH));+ assert_eq!(native.config.depth(), 3);assert_eq!(facts.depth, 3);assert_eq!(facts.max_depth, MAX_SUBAGENT_DEPTH);assert!(matches!(diff --git a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs b/crates/openhuman-core/src/mcp/server/tools/dispatch.rsindex 889731f61a..627cb05205 100644--- a/crates/openhuman-core/src/mcp/server/tools/dispatch.rs+++ b/crates/openhuman-core/src/mcp/server/tools/dispatch.rs@@ -330,13 +330,12 @@ async fn run_subagent_tool(params: &Map<String, Value>) -> Result<Value, ToolCal// Guard BEFORE incrementing so a forged/clamped depth at the cap cannot// overflow `chain_depth + 1` (panic in debug, wrap-to-0 in release).let chain_depth = subagent_depth::current_depth();- if chain_depth >= subagent_depth::MAX_SUBAGENT_DEPTH {- return Err(ToolCallError::Internal(format!(- "agent.run_subagent delegation depth limit reached (chain depth {chain_depth} ≥ {}); refusing to spawn another nested subagent",- subagent_depth::MAX_SUBAGENT_DEPTH- )));- }- let child_depth = chain_depth + 1;+ let child_depth = tinyagents_harness::context::RunConfig::checked_child_depth(+ chain_depth, subagent_depth::MAX_SUBAGENT_DEPTH,+ ).map_err(|_| ToolCallError::Internal(format!(+ "agent.run_subagent delegation depth limit reached (chain depth {chain_depth} ≥ {}); refusing to spawn another nested subagent",+ subagent_depth::MAX_SUBAGENT_DEPTH+ )))?;let config = load_config_and_init_registry().await?;let mut agent =diff --git a/crates/openhuman-core/src/security/approval/gate_intercept.rs b/crates/openhuman-core/src/security/approval/gate_intercept.rsindex ec6e6c1157..8ab9f1fabe 100644--- a/crates/openhuman-core/src/security/approval/gate_intercept.rs+++ b/crates/openhuman-core/src/security/approval/gate_intercept.rs@@ -295,7 +295,7 @@ impl ApprovalGate {// Any park raised inside a sub-agent run — detached or inline — gets// the shorter `SUBAGENT_APPROVAL_TTL` window.let subagent_park = !forced- && (detached || crate::agent::harness::spawn_depth_context::current_spawn_depth() > 0);+ && (detached || tinyagents_harness::context::current_run_depth().is_some_and(|facts| facts.depth > 0));let chat_thread_id = chat_ctx.as_ref().map(|c| c.thread_id.clone())diff --git a/crates/openhuman-core/src/security/approval/gate_subagent_tests.rs b/crates/openhuman-core/src/security/approval/gate_subagent_tests.rsindex 2719315987..a2ac90d6d8 100644--- a/crates/openhuman-core/src/security/approval/gate_subagent_tests.rs+++ b/crates/openhuman-core/src/security/approval/gate_subagent_tests.rs@@ -178,8 +178,8 @@ async fn an_inline_subagent_park_uses_the_short_window_without_being_detached()web_origin(),APPROVAL_CHAT_CONTEXT.scope(chat_ctx(),- crate::agent::harness::with_spawn_depth(- 1,+ tinyagents_harness::context::with_run_depth(+ tinyagents_harness::context::RunDepth { depth: 1, max_depth: crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH },g.intercept("skill_registry_install", "install", serde_json::json!({})),),),