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(agent): carry turn accounting in run context
Steven Enamakele24d0d06cb52
diff --git a/.sdd-progress.md b/.sdd-progress.mdindex 3d2943e9ea..21b1929a7a 100644--- a/.sdd-progress.md+++ b/.sdd-progress.md@@ -9,6 +9,7 @@ Wave 2: complete (direct canonical imports, explicit recursive context, executioWave 3: complete in TinyAgents (all ten host capabilities, truthful unary/stream terminal lifecycle, parent-authority-preserving recursion, budget compression/accounting, and upstream Claude provider merge; independent Terra Gate 3 and merge reviews PASS).Wave 4 Phase A: complete at OpenHuman commit 9baad52086 (canonical direct imports, behavior-free facade deletion, host-only conversion/tracing seams retained; independent Terra review PASS).Wave 4 Phase B1: complete through OpenHuman commit a3dcf3f897 (explicit OpenHumanRunContext foundation, ten-capability host bundle, canonical shared-tool adapter, call-identity-safe middleware migration, truthful routing-role projection, and boundary baseline reduced from 377 to 358; independent Terra re-review PASS). The context is intentionally not live yet; Phase B2 owns task-local and route cutover.+Wave 4 Phase B2g: complete (root `RunContext<OpenHumanRunContext>` now carries the shared dispatch guard, attachment placeholders, and explicit child-usage ledger; synchronous descendants read and write those handles directly, `LastTurnUsage` is populated from the root ledger, and the three ambient turn-local modules are deleted). The guard keeps its host-owned pause and wall-clock policy, while deterministic tests cover pause/budget refusal and sibling-ledger isolation.Task -1: complete (git_attribution removed; focused behavioral Git-hardening test passed; re-review spec PASS and quality PASS with no findings).Task 0: complete (temporary exact baseline reduced from 455 to 377 after Phase A; checker scans all OpenHuman crates and TinyAgents facades; vendored dependency boundary 6/6; Terra re-review PASS).Task 1: in progress (TinyTools final is merged `7a40010` in PR #6; the source-breaking/tool-controlled trust experiment was removed and empty PR #7 closed; TinyAgents and OpenHuman direct-import consumers complete; final runtime deletion remains).diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rsindex 50597fc7ce..4633b54830 100644--- a/crates/openhuman-core/src/agent/harness/mod.rs+++ b/crates/openhuman-core/src/agent/harness/mod.rs@@ -41,9 +41,6 @@ mod spawn_depth_context;pub mod subagent_runner;pub mod task_recency_context;pub(crate) mod tool_result_artifacts;-pub mod turn_attachments_context;-pub mod turn_dispatch_guard;-pub mod turn_subagent_usage;pub use agent_graph::{AgentGraph, AgentTurnRequest, AgentTurnResult, AgentTurnUsage};// NOTE: deliberately no flat re-export here. `artifact_offload::ArtifactKind`@@ -61,7 +58,6 @@ pub use sandbox_context::{current_sandbox_mode, with_current_sandbox_mode};pub(crate) use spawn_depth_context::{current_spawn_depth, with_spawn_depth, MAX_SPAWN_DEPTH};pub use subagent_runner::{run_subagent, SubagentRunError, SubagentRunOptions};pub use task_recency_context::{current_task_recency_window, with_task_recency_window};-pub use turn_subagent_usage::{LastTurnUsage, SubagentUsageEntry};pub(crate) use graph::run_channel_turn_via_graph;diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs b/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rsindex ed0ceb7d52..288d209033 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/turn_results.rs@@ -14,9 +14,7 @@ impl Agent {/// hosting platform's cost-metering hook) can read per-turn token and USD/// totals after [`Agent::turn`](crate::agent::Agent) returns,/// while leaving the value in place for the web-channel drain path.- pub fn last_turn_usage(- &self,- ) -> Option<&crate::agent::harness::turn_subagent_usage::LastTurnUsage> {+ pub fn last_turn_usage(&self) -> Option<&crate::agent::tinyagents::host::LastTurnUsage> {self.last_turn_usage_totals.as_ref()}@@ -25,7 +23,7 @@ impl Agent {/// Consumed by web-channel delivery to populate the `chat_done` usage fields.pub(crate) fn take_last_turn_usage_totals(&mut self,- ) -> Option<crate::agent::harness::turn_subagent_usage::LastTurnUsage> {+ ) -> Option<crate::agent::tinyagents::host::LastTurnUsage> {self.last_turn_usage_totals.take()}diff --git a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rsindex 3eb9ff94b5..8599d5b08e 100644--- a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs+++ b/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs@@ -566,11 +566,11 @@ async fn last_turn_usage_is_public_and_non_draining() {// The accessor now yields totals, and the return type's fields are all// publicly readable (this closure would not compile if they were not).- let peeked: crate::agent::harness::LastTurnUsage = {+ let peeked: crate::agent::tinyagents::host::LastTurnUsage = {let usage = agent.last_turn_usage().expect("usage should be populated after a turn");- crate::agent::harness::LastTurnUsage {+ crate::agent::tinyagents::host::LastTurnUsage {input_tokens: usage.input_tokens,output_tokens: usage.output_tokens,cached_input_tokens: usage.cached_input_tokens,diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rsindex bd773f4ebf..c88d9c7390 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs@@ -36,6 +36,7 @@ impl Agent {max_iterations: usize,artifact_store: Option<ToolResultArtifactStore>,suppress_tools: bool,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> Result<String> {let snapshot = TranscriptSnapshotSink::default();let result = Box::pin(self.run_turn_via_tinyagents_session_inner(@@ -45,6 +46,7 @@ impl Agent {max_iterations,artifact_store,suppress_tools,+ run_context,snapshot.clone(),)).await;diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rsindex 3ce92a3932..fca0a604e8 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs@@ -45,6 +45,7 @@ impl Agent {crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore,>,suppress_tools: bool,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,transcript_snapshot: crate::agent::tinyagents::TranscriptSnapshotSink,) -> Result<String> {let turn_started = std::time::Instant::now();@@ -160,67 +161,43 @@ impl Agent {transcript_snapshot: Some(transcript_snapshot.clone()),};- // Gather any sub-agent spend delegated during this turn (synchronous- // `spawn_subagent` runs inline on this task and records into the collector)- // so the turn's usage meters + the `chat_done` per-child breakdown include- // it — the collector scope the legacy engine installed.- // Install the turn's sub-agent dispatch guard around the same future- // (#5804). It records two facts the turn already produces but never- // wrote down — that a graceful pause has been requested at the- // model-call cap, and how long this turn's sub-agents actually take —- // so `run_subagent` can refuse a dispatch that cannot finish inside the- // remaining wall-clock budget instead of taking the whole turn down- // with it. Boxed at the call site: `with_dispatch_guard` takes its- // future by value, and the collector future wraps the entire turn- // generator, so passing it unboxed would move hundreds of KiB through- // this frame — the same hazard `with_turn_collector`'s own comment- // documents, with the gdb measurements behind it.- let turn_future = Box::pin(- crate::agent::harness::turn_subagent_usage::with_turn_collector(- graph::run_chat_turn_graph(graph::ChatTurnGraph {- turn_models,- model: effective_model.to_string(),- messages,- tools: turn_tools,- synthesized_tools: turn_synthesized_tools,- visible_tool_names: turn_visible_tool_names,- max_iterations,- on_progress: self.on_progress.clone(),- context_window,- run_queue: self.run_queue.clone(),- context_mw,- // Enforce the builder-configured tool policy at the tool- // boundary (the tinyagents path otherwise bypasses it).- tool_policy: Some(crate::agent::tinyagents::ToolPolicyEnforcement {- policy: self.tool_policy.clone(),- session: self.tool_policy_session.clone(),- session_id: self.event_session_id.clone(),- channel: self.event_channel().to_string(),- agent_definition_id: self.agent_definition_id.clone(),- }),- // Section D: forward the session's per-profile workspace- // descriptor (if any) so the top-level chat turn's acting- // tools default their cwd to the profile's dedicated dir.- workspace_descriptor: self.workspace_descriptor.clone(),- // Scope direct Master-Agent calls under its declared- // sandbox. `agent_definition_name` can carry a thread- // suffix, so resolve with the stable definition id.- sandbox_mode: self- .resolved_definition()- .map(|definition| definition.sandbox_mode)- .unwrap_or(crate::agent::harness::definition::SandboxMode::None),- thread_id: self.thread_id.clone(),- }),- ),- );- let (outcome, subagent_usage_entries) =- crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(- crate::agent::tinyagents::agent_turn_wall_clock_ms()- .map(std::time::Duration::from_millis),- turn_future,- )- .await;- let outcome = outcome?;+ let outcome = graph::run_chat_turn_graph(graph::ChatTurnGraph {+ turn_models,+ model: effective_model.to_string(),+ messages,+ tools: turn_tools,+ synthesized_tools: turn_synthesized_tools,+ visible_tool_names: turn_visible_tool_names,+ max_iterations,+ on_progress: self.on_progress.clone(),+ context_window,+ run_queue: self.run_queue.clone(),+ context_mw,+ // Enforce the builder-configured tool policy at the tool+ // boundary (the tinyagents path otherwise bypasses it).+ tool_policy: Some(crate::agent::tinyagents::ToolPolicyEnforcement {+ policy: self.tool_policy.clone(),+ session: self.tool_policy_session.clone(),+ session_id: self.event_session_id.clone(),+ channel: self.event_channel().to_string(),+ agent_definition_id: self.agent_definition_id.clone(),+ }),+ // Section D: forward the session's per-profile workspace+ // descriptor (if any) so the top-level chat turn's acting+ // tools default their cwd to the profile's dedicated dir.+ workspace_descriptor: self.workspace_descriptor.clone(),+ // Scope direct Master-Agent calls under its declared+ // sandbox. `agent_definition_name` can carry a thread+ // suffix, so resolve with the stable definition id.+ sandbox_mode: self+ .resolved_definition()+ .map(|definition| definition.sandbox_mode)+ .unwrap_or(crate::agent::harness::definition::SandboxMode::None),+ thread_id: self.thread_id.clone(),+ run_context: run_context.clone(),+ })+ .await?;+ let subagent_usage_entries = run_context.subagent_usage_entries();// The run handed back its own transcript, folded into history below, so// an error after this point must not replay the snapshot's rounds again.transcript_snapshot@@ -474,15 +451,14 @@ impl Agent {cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);charged_amount_usd += entry.usage.charged_amount_usd;}- self.last_turn_usage_totals =- Some(crate::agent::harness::turn_subagent_usage::LastTurnUsage {- input_tokens,- output_tokens,- cached_input_tokens,- cost_usd: charged_amount_usd,- context_window: context_window.unwrap_or(0),- subagents: subagent_usage_entries,- });+ self.last_turn_usage_totals = Some(crate::agent::tinyagents::host::LastTurnUsage {+ input_tokens,+ output_tokens,+ cached_input_tokens,+ cost_usd: charged_amount_usd,+ context_window: context_window.unwrap_or(0),+ subagents: subagent_usage_entries,+ });let mut persisted = crate::agent::message_convert::provider_messages_from_conversation(self.tool_dispatcher.as_ref(),diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rsindex 78fe1fc275..ddd25d9089 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs@@ -605,6 +605,31 @@ impl Agent {// background archivist fork at end-of-turn.self.context.tick_turn();+ // The root host carrier is constructed before the turn starts and is+ // passed through TinyAgents' `RunContext` to every synchronous child.+ // These values used to be recovered through nested Tokio scopes.+ let mut turn_run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ turn_run_context.parent = Some(parent_context.clone());+ turn_run_context.prepared_context_sources = std::sync::Arc::new(agent_context_prepared_sources.clone());+ turn_run_context.attachment_placeholders = std::sync::Arc::new(+ crate::agent::multimodal::extract_image_placeholders_in_text(user_message),+ );+ turn_run_context.dispatch = Some(std::sync::Arc::new(+ crate::agent::tinyagents::host::TurnDispatchState::new(+ crate::agent::tinyagents::agent_turn_wall_clock_ms()+ .map(std::time::Duration::from_millis),+ ),+ ));+ let mut turn_stop_hooks = crate::agent::stop_hooks::current_stop_hooks();+ if let Some(ref goal) = active_goal {+ if let Some(hook) =+ crate::agent::goals::runtime::GoalBudgetStopHook::for_goal(&goal_workspace_dir, goal)+ {+ turn_stop_hooks.push(std::sync::Arc::new(hook));+ }+ }+ turn_run_context.stop_hooks = turn_stop_hooks;+let turn_body = async {// Keep the scalar turn settings outside the pinned future arguments;// the TinyAgents session path reads provider/tool/multimodal state@@ -629,68 +654,12 @@ impl Agent {max_iterations,artifact_store,turn_overrides.suppress_tools,+ turn_run_context.clone(),)).await}; // end of `turn_body` async block- // Run the turn body inside the parent-execution-context scope so- // that any `spawn_subagent` tool call fired during the loop can- // read the parent's provider, tools, model, and workspace via- // the PARENT_CONTEXT task-local.- // Arm the thread-goal budget stop hook for this turn when an active,- // budgeted goal exists — it votes to stop the loop as soon as running- // usage would exceed the cap. #4469 item 1: the stop is a graceful pause- // drained at the next iteration boundary, not an instantaneous abort, so- // the current tool round + one wrap-up summary call can still run past the- // cap (a small, bounded overshoot) before the partial transcript returns.- // Merge with any ambient stop hooks rather than clobbering them. No- // budgeted active goal → no extra hook, no wrap.- let mut turn_stop_hooks = crate::agent::stop_hooks::current_stop_hooks();- if let Some(ref goal) = active_goal {- if let Some(hook) =- crate::agent::goals::runtime::GoalBudgetStopHook::for_goal(- &goal_workspace_dir,- goal,- )- {- turn_stop_hooks.push(std::sync::Arc::new(hook));- }- }- // Surface this turn's image-attachment placeholders so a delegation to a- // vision sub-agent (which reads `current_turn_image_placeholders()` in- // `agent_orchestration::tools::dispatch`) can forward the user's attached- // image — the orchestrator itself keeps it as a text placeholder. Scoped- // around the harness turn (the delegating tool fires inside it).- let image_placeholders =- crate::agent::multimodal::extract_image_placeholders_in_text(user_message);- let result = if turn_stop_hooks.is_empty() {- harness::with_parent_context(- parent_context,- harness::with_agent_context_prepared_sources(- agent_context_prepared_sources.clone(),- harness::turn_attachments_context::with_current_turn_image_placeholders(- image_placeholders,- turn_body,- ),- ),- )- .await- } else {- harness::with_parent_context(- parent_context,- harness::with_agent_context_prepared_sources(- agent_context_prepared_sources.clone(),- harness::turn_attachments_context::with_current_turn_image_placeholders(- image_placeholders,- crate::agent::stop_hooks::with_stop_hooks(- turn_stop_hooks,- turn_body,- ),- ),- ),- )- .await- };+ let result = turn_body.await;// Session transcript persistence lives INSIDE the turn body —// one write per provider response, fired right after thediff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/harness/session/turn/graph.rsindex 1b71160c10..e57e4eb050 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs@@ -92,6 +92,9 @@ pub(crate) struct ChatTurnGraph {pub sandbox_mode: SandboxMode,/// Explicit backend/persistence thread for this root turn.pub thread_id: Option<String>,+ /// The root host carrier, built before the turn begins and retained by all+ /// synchronous descendant dispatches.+ pub run_context: crate::agent::tinyagents::host::OpenHumanRunContext,}/// Drive the chat turn graph: a thin wrapper over the shared tinyagents seam@@ -114,7 +117,7 @@ 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::new();+ let mut run_context = graph.run_context;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);diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rsindex 5826c563f6..e5a4ee3ab5 100644--- a/crates/openhuman-core/src/agent/harness/session/types.rs+++ b/crates/openhuman-core/src/agent/harness/session/types.rs@@ -205,8 +205,7 @@ pub struct Agent {/// any sub-agents spawned during it). Consumed by web-channel delivery to/// surface session token/cost/context meters in the UI footer. `None` until/// the first turn completes.- pub(super) last_turn_usage_totals:- Option<crate::agent::harness::turn_subagent_usage::LastTurnUsage>,+ pub(super) last_turn_usage_totals: Option<crate::agent::tinyagents::host::LastTurnUsage>,/// Whether the most recent turn's tinyagents loop paused because it hit/// `max_tool_iterations` (`TinyagentsTurnOutcome::hit_cap`), rather than/// finishing naturally. `false` until the first turn completes, and resetdiff --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.rsindex d89b659a17..1456091a19 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@@ -271,11 +271,11 @@ 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 = run_context.child();+ // `SubagentRunOptions` already carries the child context built at the tool+ // dispatch boundary. Reusing that owned value preserves its immediate+ // parent-ledger link; forking again here would hide nested child usage in a+ // second, unreachable ledger.+ let mut child_context = run_context;// A parallel task may omit `thread_id`; that means inherit the parent// conversation, not erase it. Only an explicit task thread may replace// the typed carrier's inherited affinity.diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rsindex 9a185605e4..3cfaf28411 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs@@ -68,9 +68,9 @@ 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::turn_dispatch_guard;-#[cfg(test)]pub(super) use crate::agent::harness::{current_spawn_depth, with_spawn_depth, MAX_SPAWN_DEPTH};+#[cfg(test)]+use tinytools::ToolSpec;// Test companion modules — path references relative to their original location.#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rsindex df8827801d..ff54666594 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs@@ -21,9 +21,7 @@ use crate::agent::harness::definition::{validate_tier_transition, AgentDefinition, AgentDefinitionRegistry, AgentTier, IterationPolicy,PromptSource, SandboxMode as AgentSandboxMode,};-use crate::agent::harness::fork_context::{- current_parent, with_parent_context, ParentExecutionContext,-};+use crate::agent::harness::fork_context::ParentExecutionContext;use crate::agent::harness::subagent_runner::extract_tool::ExtractFromResultTool;use crate::agent::harness::subagent_runner::handoff::ResultHandoffCache;use crate::agent::harness::subagent_runner::subagent_iter_cap_with_autonomous_lift;@@ -36,10 +34,7 @@ use crate::agent::harness::subagent_runner::types::{SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,SubagentUsage,};-use crate::agent::harness::turn_dispatch_guard;-use crate::agent::harness::{- current_spawn_depth, with_current_sandbox_mode, with_spawn_depth, MAX_SPAWN_DEPTH,-};+use crate::agent::harness::{with_current_sandbox_mode, with_spawn_depth, MAX_SPAWN_DEPTH};use crate::agent::prompts::{render_subagent_system_prompt_with_format, PromptContext, PromptTool, SubagentRenderOptions,};@@ -362,10 +357,11 @@ async fn try_deterministic_memory_retrieval(/// This is the primary entry point for agent delegation. It performs the following:/// 1. Generates a unique `task_id` if one wasn't provided./// 2. Asks the turn's-/// [dispatch guard](crate::agent::harness::turn_dispatch_guard)+/// explicit root-turn dispatch guard/// whether a delegation can still succeed, and refuses before spending/// anything if it cannot (#5804).-/// 3. Resolves the [`ParentExecutionContext`] task-local.+/// 3. Reads the parent's explicit [`ParentExecutionContext`] from its run+/// carrier./// 4. Dispatches to `run_typed_mode`.////// On success returns a [`SubagentRunOutcome`] whose `output` is the@@ -408,9 +404,12 @@ pub async fn run_subagent(// cap, or less wall-clock remains than this turn's slowest completed// sub-agent took. Outside a turn scope the guard is absent and this is// a no-op, so CLI and direct invocations are unaffected.- match turn_dispatch_guard::check() {- turn_dispatch_guard::DispatchDecision::Allow => {}- turn_dispatch_guard::DispatchDecision::RefusePaused {+ match options.run_context.dispatch.as_deref().map_or(+ crate::agent::tinyagents::host::DispatchDecision::Allow,+ crate::agent::tinyagents::host::TurnDispatchState::check,+ ) {+ crate::agent::tinyagents::host::DispatchDecision::Allow => {}+ crate::agent::tinyagents::host::DispatchDecision::RefusePaused {completed_model_calls,cap,} => {@@ -426,7 +425,7 @@ pub async fn run_subagent(cap,});}- turn_dispatch_guard::DispatchDecision::RefuseBudget {+ crate::agent::tinyagents::host::DispatchDecision::RefuseBudget {remaining_ms,observed_max_ms,observed_samples,@@ -448,10 +447,13 @@ pub async fn run_subagent(}}- let parent = current_parent().ok_or(SubagentRunError::NoParentContext)?;+ let parent = options+ .run_context+ .parent+ .clone()+ .ok_or(SubagentRunError::NoParentContext)?;let started = Instant::now();- let current_depth = current_spawn_depth();- let attempted_depth = current_depth.saturating_add(1);+ let attempted_depth = options.run_context.spawn_depth;// Synchronous pre-dispatch projection of the single depth authority// (`MAX_SPAWN_DEPTH`, also fed to the crate's `RunPolicy.limits.max_depth`).@@ -462,7 +464,6 @@ pub async fn run_subagent(tracing::warn!(agent_id = %definition.id,task_id = %task_id,- current_depth,attempted_depth,max_depth = MAX_SPAWN_DEPTH,"[subagent_runner] spawn depth exceeded"@@ -554,7 +555,9 @@ pub async fn run_subagent(// the opposite and was wrong about its own statistic. What it// does buy is a correct `observed_samples` count and a gate// that arms on a turn shaped entirely from fast-path work.- turn_dispatch_guard::record_subagent_elapsed(started.elapsed());+ if let Some(dispatch) = options.run_context.dispatch.as_deref() {+ dispatch.record_subagent_elapsed(started.elapsed());+ }return Ok(outcome);}}@@ -598,17 +601,14 @@ pub async fn run_subagent(let run_result = with_spawn_depth(attempted_depth, async {with_file_state_agent_id(task_id.clone(), async {with_current_sandbox_mode(definition.sandbox_mode, async {- with_parent_context(parent_for_subagent.clone(), async {- Box::pin(run_typed_mode(- definition,- task_prompt,- &options,- &parent_for_subagent,- &task_id,- &loaded_config,- ))- .await- })+ Box::pin(run_typed_mode(+ definition,+ task_prompt,+ &options,+ &parent_for_subagent,+ &task_id,+ &loaded_config,+ )).await}).await@@ -633,7 +633,9 @@ pub async fn run_subagent(// the config load and the tier/hook gates are inside the figure — the// question the gate asks is how long a *dispatch* takes end to end,// not how long the child's own loop ran.- turn_dispatch_guard::record_subagent_elapsed(started.elapsed());+ if let Some(dispatch) = options.run_context.dispatch.as_deref() {+ dispatch.record_subagent_elapsed(started.elapsed());+ }let mut outcome = run_result?;@@ -1721,19 +1723,34 @@ async fn run_typed_mode(};// Surface this run's token/cost totals so the parent turn can roll them- // into the session-level meters and the global cost tracker. Also push the- // breakdown into any active turn-scoped collector (see- // `turn_subagent_usage`) so a delegating parent attributes per-child spend.- let usage = crate::agent::harness::subagent_runner::types::SubagentUsage {+ // into the session-level meters and the global cost tracker. The caller's+ // explicit host carrier owns the ledger; no Tokio task scope is involved.+ let mut usage = crate::agent::harness::subagent_runner::types::SubagentUsage {input_tokens: agg_usage.input_tokens,output_tokens: agg_usage.output_tokens,cached_input_tokens: agg_usage.cached_input_tokens,charged_amount_usd: agg_usage.charged_amount_usd,};- crate::agent::harness::turn_subagent_usage::record_subagent_usage(- task_id,- &definition.id,- usage,+ // A nested child records on this run's isolated ledger. Fold those totals+ // into the completed child before writing the immediate parent's ledger so+ // the root always receives complete subtree spend without siblings sharing+ // mutable in-flight state.+ for entry in options.run_context.subagent_usage_entries() {+ usage.input_tokens = usage.input_tokens.saturating_add(entry.usage.input_tokens);+ usage.output_tokens = usage+ .output_tokens+ .saturating_add(entry.usage.output_tokens);+ usage.cached_input_tokens = usage+ .cached_input_tokens+ .saturating_add(entry.usage.cached_input_tokens);+ usage.charged_amount_usd += entry.usage.charged_amount_usd;+ }+ options.run_context.record_completed_subagent_usage(+ crate::agent::tinyagents::host::SubagentUsageEntry {+ task_id: task_id.to_string(),+ agent_id: definition.id.clone(),+ usage,+ },);Ok(SubagentRunOutcome {diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_tier_gate_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_tier_gate_tests.rsindex a944c8cea8..c90f624cad 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_tier_gate_tests.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_tier_gate_tests.rs@@ -131,18 +131,13 @@ fn tier_gate_allows_upward_reasoning_to_chat() {#[tokio::test]async fn dispatch_is_refused_after_the_turn_requests_a_graceful_pause() {let definition = make_def_named_tools(&[]);- let outcome = turn_dispatch_guard::with_dispatch_guard(+ let dispatch = std::sync::Arc::new(crate::agent::tinyagents::host::TurnDispatchState::new(Some(std::time::Duration::from_secs(600)),- async {- // Stands in for `CapPauser`, which writes through a clone of this- // same `Arc` when the model-call cap is reached.- turn_dispatch_guard::current()- .expect("guard installed")- .record_pause_requested(15, 15);- run_subagent(&definition, "task", SubagentRunOptions::default()).await- },- )- .await;+ ));+ dispatch.record_pause_requested(15, 15);+ let mut options = SubagentRunOptions::default();+ options.run_context.dispatch = Some(dispatch);+ let outcome = run_subagent(&definition, "task", options).await;assert!(matches!(@@ -159,17 +154,13 @@ async fn dispatch_is_refused_after_the_turn_requests_a_graceful_pause() {#[tokio::test]async fn dispatch_is_refused_when_the_remaining_budget_cannot_fit_an_observed_subagent() {let definition = make_def_named_tools(&[]);- let outcome = turn_dispatch_guard::with_dispatch_guard(- Some(std::time::Duration::from_millis(1)),- async {- // One completed sub-agent took a minute; the turn's whole ceiling- // is a millisecond and it has already elapsed.- turn_dispatch_guard::record_subagent_elapsed(std::time::Duration::from_secs(60));- tokio::time::sleep(std::time::Duration::from_millis(5)).await;- run_subagent(&definition, "task", SubagentRunOptions::default()).await- },- )- .await;+ let dispatch = std::sync::Arc::new(crate::agent::tinyagents::host::TurnDispatchState::new(+ Some(std::time::Duration::ZERO),+ ));+ dispatch.record_subagent_elapsed(std::time::Duration::from_secs(60));+ let mut options = SubagentRunOptions::default();+ options.run_context.dispatch = Some(dispatch);+ let outcome = run_subagent(&definition, "task", options).await;assert!(matches!(@@ -188,14 +179,11 @@ async fn dispatch_is_not_refused_while_the_guard_has_no_evidence() {// `NoParentContext` is exactly that — the gate declined to interfere and// the normal path ran.let definition = make_def_named_tools(&[]);- let outcome = turn_dispatch_guard::with_dispatch_guard(- Some(std::time::Duration::from_millis(1)),- async {- tokio::time::sleep(std::time::Duration::from_millis(5)).await;- run_subagent(&definition, "task", SubagentRunOptions::default()).await- },- )- .await;+ let mut options = SubagentRunOptions::default();+ options.run_context.dispatch = Some(std::sync::Arc::new(+ crate::agent::tinyagents::host::TurnDispatchState::new(Some(std::time::Duration::ZERO)),+ ));+ let outcome = run_subagent(&definition, "task", options).await;assert!(matches!(outcome, Err(SubagentRunError::NoParentContext)),diff --git a/crates/openhuman-core/src/agent/harness/turn_attachments_context.rs b/crates/openhuman-core/src/agent/harness/turn_attachments_context.rsdeleted file mode 100644index 341c7182a1..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_attachments_context.rs+++ /dev/null@@ -1,49 +0,0 @@-//! Task-local carrier for the **current turn's image-attachment placeholders**-//! (`[Image: … #att:<id>]`), so a delegation to a vision sub-agent can forward-//! the user's attached image into the sub-agent's prompt.-//!-//! The orchestrator runs on a non-vision tier (`chat-v1`): its turn keeps the-//! image as a text placeholder and never rehydrates it (see the image gate in-//! [`crate::agent::harness::session`]). When it delegates to the-//! vision sub-agent via `analyze_image`, the sub-agent only receives the-//! orchestrator's text task — not the conversation history. This task-local-//! surfaces the current user message's placeholders to-//! [`crate::agent::orchestration::tools::dispatch`], which prepends-//! them to the sub-agent prompt so the (vision-capable) sub-agent's turn-//! rehydrates the image from the on-disk sidecar.-//!-//! A task-local carrier scoped around the orchestrator's-//! turn future (`run_turn_via_tinyagents_shared`);-//! [`current_turn_image_placeholders`] returns an empty vec when no scope is-//! active (CLI / direct invocation / tests) — strictly additive.--tokio::task_local! {- /// Image-attachment placeholder tokens from the current turn's user message.- pub static CURRENT_TURN_IMAGE_PLACEHOLDERS: Vec<String>;-}--/// Placeholders for the current turn, or an empty vec when no scope is active.-pub fn current_turn_image_placeholders() -> Vec<String> {- CURRENT_TURN_IMAGE_PLACEHOLDERS- .try_with(|v| v.clone())- .unwrap_or_default()-}--/// Run `future` with `placeholders` installed as the current turn's image-/// placeholders. Intended call site is around the orchestrator's turn-/// (`run_turn_via_tinyagents_shared`) invocation.-pub async fn with_current_turn_image_placeholders<F, R>(placeholders: Vec<String>, future: F) -> R-where- F: std::future::Future<Output = R>,-{- // Box before `scope` so only a pointer moves into the task-local frame- // rather than the whole nested turn generator — see the measurements on- // `with_turn_collector` in `turn_subagent_usage.rs`.- CURRENT_TURN_IMAGE_PLACEHOLDERS- .scope(placeholders, Box::pin(future))- .await-}--#[cfg(test)]-#[path = "turn_attachments_context_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/turn_attachments_context_tests.rs b/crates/openhuman-core/src/agent/harness/turn_attachments_context_tests.rsdeleted file mode 100644index c6b77bc68a..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_attachments_context_tests.rs+++ /dev/null@@ -1,25 +0,0 @@-use super::*;--#[tokio::test]-async fn empty_outside_scope() {- assert!(current_turn_image_placeholders().is_empty());-}--#[tokio::test]-async fn installs_and_reads_back() {- let observed = with_current_turn_image_placeholders(- vec!["[Image: image #att:abc123]".to_string()],- async { current_turn_image_placeholders() },- )- .await;- assert_eq!(observed, vec!["[Image: image #att:abc123]".to_string()]);-}--#[tokio::test]-async fn does_not_leak_across_scopes() {- with_current_turn_image_placeholders(vec!["x".to_string()], async {- assert_eq!(current_turn_image_placeholders().len(), 1);- })- .await;- assert!(current_turn_image_placeholders().is_empty());-}diff --git a/crates/openhuman-core/src/agent/harness/turn_dispatch_guard.rs b/crates/openhuman-core/src/agent/harness/turn_dispatch_guard.rsdeleted file mode 100644index a15eabcaaa..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_dispatch_guard.rs+++ /dev/null@@ -1,290 +0,0 @@-//! Turn-scoped guard that decides whether a **new sub-agent dispatch can still-//! succeed** before it is attempted.-//!-//! # The failure this exists to prevent-//!-//! A turn that reaches its model-call cap asks the harness to stop gracefully-//! ([`CapPauser`](crate::agent::tinyagents::observability), which-//! sends `SteeringCommand::Pause`) so the caller can summarise a resumable-//! checkpoint instead of erroring. That command is **advisory**: it is honoured-//! at the harness loop boundary, and nothing consulted it before dispatching a-//! new sub-agent. A dispatch issued in the same instant as the pause request-//! then runs as a tool call wrapped by the run's *remaining* wall-clock budget-//! (`run_policy_for`'s `max_wall_clock_ms`). When that remainder is smaller-//! than the child needs, the harness raises `TinyAgentsError::Timeout` for the-//! whole run — and every result the turn had accumulated is discarded rather-//! than checkpointed. The mechanism designed to degrade gracefully became the-//! cause of the hard failure (issue #5804).-//!-//! # What this guard does-//!-//! It records two facts a turn already knows but never wrote down, and turns-//! them into a decision at the one chokepoint every synchronous delegation-//! passes through (`subagent_runner::ops::runner::run_subagent`):-//!-//! 1. **Has a graceful pause been requested?** Once it has, further fan-out-//! cannot help: the loop is going to stop at its next boundary regardless,-//! so a child dispatched now can only burn budget the checkpoint needs.-//! 2. **Is there still enough wall-clock left for a dispatch to finish?**-//! Judged against what *this turn's own* sub-agents have actually taken —-//! never a configured constant.-//!-//! # Scope semantics-//!-//! Installed as a `tokio::task_local` around the parent's turn future, next to-//! [`turn_subagent_usage`](super::turn_subagent_usage) and with deliberately-//! identical visibility rules. The line is **same task or not**, which is not-//! the same line as serial or parallel:-//!-//! * **Serial delegation** (`spawn_subagent` → `run_subagent`) runs inline on-//! the turn's task and is covered.-//! * **Parallel fan-out is also covered.** `spawn_parallel_agents` drives its-//! workers through `tinyagents_graph::parallel::map_reduce`, which bounds-//! concurrency with `futures`' `buffer_unordered`-//! (`vendor/tinyagents/src/graph/parallel/mod.rs:86`) rather than-//! `tokio::spawn`. `buffer_unordered` polls every worker on the **caller's**-//! task, so each one inherits this task-local and passes the same gate. Its-//! serial fallback for shared-workspace writes is covered for the obvious-//! reason. Both call `run_subagent`-//! (`openhuman:crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs:1386`).-//! * **Detached background sub-agents** (`spawn_async_subagent`) run on tasks-//! that do not inherit the task-local, deliberately — their spend already-//! completes after the parent's `chat_done` and is accounted globally, the-//! same carve-out `turn_subagent_usage` makes.-//!-//! [`current`] returns `None` outside any scope (CLI, direct invocation,-//! tests), and **every read degrades to "allow"** — this guard can only ever-//! refuse a dispatch it has positive evidence against, so a missing scope-//! restores exactly the previous behaviour.--use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};-use std::sync::Arc;-use std::time::{Duration, Instant};--/// Per-turn dispatch state, shared between the turn scope, the harness's-/// cap-pause listener, and the sub-agent runner.-#[derive(Debug)]-pub struct TurnDispatchState {- /// Set once the harness has been asked to pause gracefully at the- /// model-call cap. Written by the cap-pause listener through a clone of- /// this `Arc` rather than through the task-local, so correctness does not- /// depend on which task the crate dispatches listeners from.- pause_requested: AtomicBool,- /// Model calls completed when the pause was requested, and the cap that- /// triggered it. Carried only so the refusal can explain itself.- pause_completed_calls: AtomicU64,- pause_cap: AtomicU64,- /// When this turn's wall-clock budget started, and how long it is. `None`- /// budget means the ceiling is disabled (`OPENHUMAN_AGENT_TURN_TIMEOUT_SECS=0`),- /// in which case no dispatch can ever be refused for want of time.- started: Instant,- budget: Option<Duration>,- /// Longest sub-agent this turn has actually completed, in milliseconds.- /// `0` means "no sample yet". A running maximum rather than a stored list:- /// the decision only ever needs the extreme, and a `u64` keeps the whole- /// state lock-free.- observed_max_ms: AtomicU64,- /// How many completed sub-agents fed `observed_max_ms`, for the log line- /// and the refusal text.- observed_samples: AtomicU64,-}--impl TurnDispatchState {- fn new(budget: Option<Duration>) -> Self {- Self {- pause_requested: AtomicBool::new(false),- pause_completed_calls: AtomicU64::new(0),- pause_cap: AtomicU64::new(0),- started: Instant::now(),- budget,- observed_max_ms: AtomicU64::new(0),- observed_samples: AtomicU64::new(0),- }- }-- /// Record that a graceful pause has been requested at the model-call cap.- ///- /// Called from the harness's event listener. The crate dispatches listeners- /// synchronously on the emitting task, in insertion order- /// (`vendor/tinyagents/src/harness/events/mod.rs:163-195`), so this write- /// happens-before any later tool dispatch in the same run — which is what- /// makes the gate deterministic rather than a second race against the- /// advisory `SteeringCommand::Pause`.- pub fn record_pause_requested(&self, completed_model_calls: u64, cap: u64) {- self.pause_completed_calls- .store(completed_model_calls, Ordering::SeqCst);- self.pause_cap.store(cap, Ordering::SeqCst);- self.pause_requested.store(true, Ordering::SeqCst);- }-- /// Fold one completed sub-agent's wall-clock duration into the running- /// maximum.- fn record_subagent_elapsed(&self, elapsed: Duration) {- let ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64;- self.observed_samples.fetch_add(1, Ordering::SeqCst);- self.observed_max_ms.fetch_max(ms, Ordering::SeqCst);- }-- /// Wall-clock still available to this turn, or `None` when no ceiling is- /// configured.- fn remaining(&self) -> Option<Duration> {- self.budget- .map(|b| b.saturating_sub(self.started.elapsed()))- }-- /// Longest completed sub-agent so far, or `None` when none has completed.- fn observed_max(&self) -> Option<Duration> {- match self.observed_max_ms.load(Ordering::SeqCst) {- 0 => None,- ms => Some(Duration::from_millis(ms)),- }- }-- fn snapshot(&self) -> DispatchInputs {- DispatchInputs {- pause_requested: self.pause_requested.load(Ordering::SeqCst),- pause_completed_calls: self.pause_completed_calls.load(Ordering::SeqCst),- pause_cap: self.pause_cap.load(Ordering::SeqCst),- remaining: self.remaining(),- observed_max: self.observed_max(),- observed_samples: self.observed_samples.load(Ordering::SeqCst),- }- }-}--/// Everything [`decide`] is allowed to look at. Extracted as a plain value so-/// the policy is unit-testable without a runtime, a clock, or a turn.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub struct DispatchInputs {- pub pause_requested: bool,- pub pause_completed_calls: u64,- pub pause_cap: u64,- pub remaining: Option<Duration>,- pub observed_max: Option<Duration>,- pub observed_samples: u64,-}--/// Outcome of the pre-dispatch check.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum DispatchDecision {- /// Nothing known contradicts this dispatch. The default in every uncertain- /// case.- Allow,- /// A graceful pause has already been requested for this turn.- RefusePaused {- completed_model_calls: u64,- cap: u64,- },- /// Less wall-clock remains than this turn's slowest completed sub-agent- /// took.- RefuseBudget {- remaining_ms: u64,- observed_max_ms: u64,- observed_samples: u64,- },-}--/// Decide whether a sub-agent dispatch should be attempted.-///-/// Two independent refusals, in order of certainty:-///-/// 1. **A pause was requested.** This is a fact about intent, not an estimate:-/// the loop will stop at its next boundary whatever we do, so a child-/// started now cannot contribute to the answer and can only consume the-/// budget the checkpoint summary needs.-///-/// 2. **The remaining budget is smaller than the longest sub-agent this turn-/// has actually completed.** The predictor is the turn's own measured-/// maximum — never a configured constant, a model name, a task shape, or-/// the number of children so far — so it is equally meaningful for a turn-/// with three fast children and one with three hundred slow ones, and it-/// means nothing at all until this turn has produced its first sample.-///-/// The maximum is used rather than a mean or a percentile because the two-/// errors are not symmetric. Refusing a dispatch that would have fit costs one-/// delegation and still returns every result gathered so far; allowing one that-/// does not fit costs **the entire turn**. Under that asymmetry the-/// conservative estimator is the correct one, and it is also the only one that-/// needs no tunable.-///-/// Both refusals are strictly evidence-based: with no pause requested, no-/// configured ceiling, or no completed sub-agent to learn from, the answer is-/// [`DispatchDecision::Allow`].-pub fn decide(inputs: DispatchInputs) -> DispatchDecision {- if inputs.pause_requested {- return DispatchDecision::RefusePaused {- completed_model_calls: inputs.pause_completed_calls,- cap: inputs.pause_cap,- };- }-- // `remaining` is `None` when the wall-clock ceiling is disabled, and- // `observed_max` is `None` until a sub-agent has finished. Either one- // absent means there is nothing to compare, so nothing to refuse.- let (Some(remaining), Some(observed_max)) = (inputs.remaining, inputs.observed_max) else {- return DispatchDecision::Allow;- };-- if remaining < observed_max {- return DispatchDecision::RefuseBudget {- remaining_ms: remaining.as_millis().min(u128::from(u64::MAX)) as u64,- observed_max_ms: observed_max.as_millis().min(u128::from(u64::MAX)) as u64,- observed_samples: inputs.observed_samples,- };- }-- DispatchDecision::Allow-}--tokio::task_local! {- /// Dispatch state for the turn currently executing on this task. Absent- /// outside a turn scope.- static TURN_DISPATCH_STATE: Arc<TurnDispatchState>;-}--/// The dispatch state for the current turn, or `None` outside any scope.-pub fn current() -> Option<Arc<TurnDispatchState>> {- TURN_DISPATCH_STATE.try_with(|s| s.clone()).ok()-}--/// Ask the guard whether a sub-agent may be dispatched now.-///-/// Returns [`DispatchDecision::Allow`] when no guard is installed, so every-/// path that does not run under a turn scope behaves exactly as before.-pub fn check() -> DispatchDecision {- match current() {- Some(state) => decide(state.snapshot()),- None => DispatchDecision::Allow,- }-}--/// Fold a finished sub-agent's wall-clock duration into the current turn's-/// observed maximum. No-op outside a turn scope.-pub fn record_subagent_elapsed(elapsed: Duration) {- if let Some(state) = current() {- state.record_subagent_elapsed(elapsed);- }-}--/// Run `future` with a fresh dispatch guard installed for `budget`.-///-/// `budget` is the turn's wall-clock ceiling — the same value the harness-/// policy receives as `max_wall_clock_ms`. Measuring from here rather than from-/// the harness run means the guard's idea of "elapsed" starts marginally-/// *earlier* than the harness's, so its remaining-budget figure is-/// conservative: it can under-estimate the time left, never over-estimate it.-pub async fn with_dispatch_guard<F, R>(budget: Option<Duration>, future: F) -> R-where- F: std::future::Future<Output = R>,-{- let state = Arc::new(TurnDispatchState::new(budget));- // `scope` takes the inner future by value; the turn generator is hundreds- // of KiB in a debug build, so pin it to the heap first and move only a- // pointer through this frame. See the same note (and the stack-overflow- // measurements behind it) in `turn_subagent_usage::with_turn_collector`.- TURN_DISPATCH_STATE.scope(state, Box::pin(future)).await-}--#[cfg(test)]-#[path = "turn_dispatch_guard_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/turn_dispatch_guard_tests.rs b/crates/openhuman-core/src/agent/harness/turn_dispatch_guard_tests.rsdeleted file mode 100644index a40beae5f8..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_dispatch_guard_tests.rs+++ /dev/null@@ -1,318 +0,0 @@-//! Tests for the turn-scoped sub-agent dispatch guard (issue #5804).-//!-//! The policy ([`decide`]) is exercised as a pure function so every branch is-//! reachable without a runtime, a clock, or a model. The scope helpers are-//! exercised under `#[tokio::test]` because a `task_local` needs a task.--use std::time::Duration;--use super::{- check, current, decide, record_subagent_elapsed, with_dispatch_guard, DispatchDecision,- DispatchInputs,-};--/// Baseline inputs: nothing known, nothing to refuse.-fn inputs() -> DispatchInputs {- DispatchInputs {- pause_requested: false,- pause_completed_calls: 0,- pause_cap: 0,- remaining: None,- observed_max: None,- observed_samples: 0,- }-}--#[test]-fn allows_when_nothing_is_known() {- assert_eq!(decide(inputs()), DispatchDecision::Allow);-}--#[test]-fn refuses_once_a_graceful_pause_has_been_requested() {- let decision = decide(DispatchInputs {- pause_requested: true,- pause_completed_calls: 15,- pause_cap: 15,- ..inputs()- });- assert_eq!(- decision,- DispatchDecision::RefusePaused {- completed_model_calls: 15,- cap: 15,- },- "a dispatch issued after the cap-pause request is the #5804 failure"- );-}--#[test]-fn pause_refusal_does_not_depend_on_the_remaining_budget() {- // The whole point: at the moment of the observed failure there was budget- // left (26s), it just was not enough. The pause arm must fire on intent- // alone, with an hour to spare.- let decision = decide(DispatchInputs {- pause_requested: true,- pause_completed_calls: 3,- pause_cap: 3,- remaining: Some(Duration::from_secs(3600)),- observed_max: Some(Duration::from_secs(1)),- observed_samples: 9,- });- assert!(- matches!(decision, DispatchDecision::RefusePaused { .. }),- "pause is a fact about intent, not an estimate — budget must not overrule it"- );-}--#[test]-fn refuses_when_less_remains_than_the_slowest_observed_subagent() {- // The observed run: ~26s left, children averaging ~68s.- let decision = decide(DispatchInputs {- remaining: Some(Duration::from_millis(26_375)),- observed_max: Some(Duration::from_secs(68)),- observed_samples: 17,- ..inputs()- });- assert_eq!(- decision,- DispatchDecision::RefuseBudget {- remaining_ms: 26_375,- observed_max_ms: 68_000,- observed_samples: 17,- },- "a dispatch that cannot fit in the remaining budget must not be attempted"- );-}--#[test]-fn allows_when_the_remaining_budget_still_covers_the_slowest_observed_subagent() {- let decision = decide(DispatchInputs {- remaining: Some(Duration::from_secs(300)),- observed_max: Some(Duration::from_secs(68)),- observed_samples: 17,- ..inputs()- });- assert_eq!(decision, DispatchDecision::Allow);-}--#[test]-fn allows_on_the_exact_boundary() {- // `remaining == observed_max` is not evidence the dispatch cannot finish,- // so the guard must not refuse it. Only a strict shortfall refuses.- let decision = decide(DispatchInputs {- remaining: Some(Duration::from_secs(68)),- observed_max: Some(Duration::from_secs(68)),- observed_samples: 2,- ..inputs()- });- assert_eq!(decision, DispatchDecision::Allow);-}--#[test]-fn allows_the_first_dispatch_however_little_budget_remains() {- // No sub-agent has completed, so there is no sample to judge against and- // the guard has no evidence. Refusing here would be a guess, and would- // break every short turn that delegates exactly once.- let decision = decide(DispatchInputs {- remaining: Some(Duration::from_millis(1)),- observed_max: None,- observed_samples: 0,- ..inputs()- });- assert_eq!(decision, DispatchDecision::Allow);-}--#[test]-fn allows_when_the_wall_clock_ceiling_is_disabled() {- // `OPENHUMAN_AGENT_TURN_TIMEOUT_SECS=0` → no ceiling → nothing can run out.- let decision = decide(DispatchInputs {- remaining: None,- observed_max: Some(Duration::from_secs(600)),- observed_samples: 40,- ..inputs()- });- assert_eq!(decision, DispatchDecision::Allow);-}--#[test]-fn the_budget_rule_is_scale_free() {- // Same rule, three orders of magnitude apart and at both fan-out extremes:- // the decision depends only on remaining-vs-observed, never on how many- // children have run or how long they took in absolute terms.- let fast_small = decide(DispatchInputs {- remaining: Some(Duration::from_millis(40)),- observed_max: Some(Duration::from_millis(50)),- observed_samples: 3,- ..inputs()- });- let slow_large = decide(DispatchInputs {- remaining: Some(Duration::from_secs(40)),- observed_max: Some(Duration::from_secs(50)),- observed_samples: 300,- ..inputs()- });- assert!(matches!(fast_small, DispatchDecision::RefuseBudget { .. }));- assert!(matches!(slow_large, DispatchDecision::RefuseBudget { .. }));-}--#[tokio::test]-async fn no_guard_outside_a_turn_scope() {- assert!(current().is_none());- assert_eq!(- check(),- DispatchDecision::Allow,- "an absent guard must restore the previous behaviour exactly"- );- // Must not panic when there is nothing to record into.- record_subagent_elapsed(Duration::from_secs(1));-}--#[tokio::test]-async fn pause_recorded_through_the_shared_handle_is_visible_to_the_dispatch_check() {- // This is the wiring the fix depends on: the cap-pause listener holds a- // clone of the same `Arc` and writes through it, while the sub-agent- // runner reads the task-local. Both must see one state.- with_dispatch_guard(Some(Duration::from_secs(600)), async {- assert_eq!(check(), DispatchDecision::Allow);-- let state = current().expect("guard installed");- state.record_pause_requested(15, 15);-- assert_eq!(- check(),- DispatchDecision::RefusePaused {- completed_model_calls: 15,- cap: 15,- },- "the runner must observe a pause the listener recorded"- );- })- .await;-}--#[tokio::test]-async fn observed_durations_accumulate_as_a_running_maximum() {- with_dispatch_guard(Some(Duration::from_secs(600)), async {- record_subagent_elapsed(Duration::from_secs(5));- record_subagent_elapsed(Duration::from_secs(90));- record_subagent_elapsed(Duration::from_secs(30));-- // Read the real recorded state, not a hand-built copy of it: the claim- // under test is that `record_subagent_elapsed` keeps the maximum- // rather than the mean or the most recent value.- let snapshot = current().expect("guard installed").snapshot();- assert_eq!(- snapshot.observed_max,- Some(Duration::from_secs(90)),- "the running maximum must survive a later, shorter sub-agent"- );- assert_eq!(snapshot.observed_samples, 3);- })- .await;-}--#[tokio::test]-async fn the_remaining_budget_is_measured_from_the_scope_and_shrinks() {- with_dispatch_guard(Some(Duration::from_millis(400)), async {- let state = current().expect("guard installed");- let before = state.snapshot().remaining.expect("a ceiling is configured");- tokio::time::sleep(Duration::from_millis(60)).await;- let after = state.snapshot().remaining.expect("a ceiling is configured");- assert!(- after < before,- "remaining budget must shrink with elapsed wall-clock ({after:?} !< {before:?})"- );-- // With a sample longer than the whole ceiling, the guard now has- // positive evidence and must refuse.- record_subagent_elapsed(Duration::from_secs(60));- assert!(- matches!(check(), DispatchDecision::RefuseBudget { .. }),- "a sub-agent longer than the entire remaining budget must block dispatch"- );- })- .await;-}--#[tokio::test]-async fn the_guard_does_not_leak_into_a_detached_task() {- // Background sub-agents run on tasks that do not inherit the task-local,- // deliberately — same rule as the usage collector. They must degrade to- // "allow", not panic.- with_dispatch_guard(Some(Duration::from_secs(600)), async {- current()- .expect("guard installed")- .record_pause_requested(1, 1);- let detached = tokio::spawn(async { check() });- assert_eq!(- detached.await.expect("task joined"),- DispatchDecision::Allow,- "a detached task sees no guard and must behave as it did before"- );- })- .await;-}--#[tokio::test]-async fn concurrent_same_task_dispatches_share_one_guard() {- // `spawn_parallel_agents` fans out through `map_reduce`, which bounds- // concurrency with `futures`' `buffer_unordered` rather than- // `tokio::spawn` — so every parallel worker is polled on the caller's task- // and inherits this task-local. `tokio::join!` has the same property, and- // this pins the consequence: concurrency does not bypass the gate, and the- // sample one worker records is visible to the next worker's check.- with_dispatch_guard(Some(Duration::from_millis(50)), async {- // Order matters, and getting it wrong here is what an earlier revision- // of this test did: it recorded the 60s sample *before* its own- // `check()`, so the first worker judged itself against a duration it- // had just written and the `Allow` assertion could never hold. A worker- // checks on the way in and records on the way out — mirror that.- let a = async {- let decision = check();- record_subagent_elapsed(Duration::from_secs(60));- decision- };- let b = async {- tokio::time::sleep(Duration::from_millis(60)).await;- check()- };- let (first, second) = tokio::join!(a, b);-- // The first worker had no sample of its own to judge against yet.- assert_eq!(first, DispatchDecision::Allow);- // The second sees the first's sample through the shared guard, and the- // budget is gone — exactly the refusal a serial run would produce.- assert!(- matches!(second, DispatchDecision::RefuseBudget { .. }),- "a concurrently-polled dispatch must see the shared guard, not a fresh one: {second:?}"- );- })- .await;-}--#[tokio::test]-async fn a_parallel_batch_with_no_samples_is_never_refused() {- // The other direction, and the one that matters for throughput: the FIRST- // parallel batch has no completed sub-agent to learn from, so however many- // workers it fans out to and however little budget is left, none of them- // may be refused. A guard that blocked the opening fan-out would break- // every parallel task rather than fixing one.- with_dispatch_guard(Some(Duration::from_millis(1)), async {- tokio::time::sleep(Duration::from_millis(5)).await;- let worker = || async { check() };- let decisions = tokio::join!(worker(), worker(), worker(), worker(), worker());- let all = [- decisions.0,- decisions.1,- decisions.2,- decisions.3,- decisions.4,- ];- assert!(- all.iter().all(|d| *d == DispatchDecision::Allow),- "an opening fan-out has no evidence against it and must proceed: {all:?}"- );- })- .await;-}diff --git a/crates/openhuman-core/src/agent/harness/turn_subagent_usage.rs b/crates/openhuman-core/src/agent/harness/turn_subagent_usage.rsdeleted file mode 100644index 6936a57c4d..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_subagent_usage.rs+++ /dev/null@@ -1,147 +0,0 @@-//! Task-local collector for **sub-agent token/cost spend within the current-//! turn**.-//!-//! When a parent agent delegates to a sub-agent mid-turn, the sub-agent's-//! provider calls are accounted by its own [`SubagentObserver`] and never reach-//! the parent's `AgentObserver` cumulative totals (the two run on separate-//! observers). Without a bridge, sub-agent spend is invisible to the-//! session-level token/cost meters surfaced in the UI footer, and to the global-//! cost tracker.-//!-//! This module installs an [`Arc<Mutex<Vec<SubagentUsageEntry>>>`] as a-//! task-local around the parent's turn future (the-//! `run_turn_via_tinyagents_shared` drive). Synchronous delegations-//! (`spawn_subagent`) run inline on the same tokio task, so the sub-agent-//! runner can [`record_subagent_usage`] its totals into the active collector.-//! After the turn returns, the parent [`drain`]s the collector to:-//!-//! 1. fold child tokens + USD into the turn's cumulative meters, and-//! 2. attribute per-child spend for the `chat_done` breakdown (hover detail).-//!-//! Background / async sub-agents (`spawn_async_subagent`) run on detached tasks-//! that do **not** inherit this task-local; their spend completes after the-//! parent turn's `chat_done` and is captured by the global cost tracker-//! instead. [`current_collector`] returns `None` outside any scope (CLI /-//! direct invocation / tests), so recording is strictly additive.--use std::sync::{Arc, Mutex};--use super::subagent_runner::SubagentUsage;--/// One sub-agent's spend, tagged with its identity for the per-child breakdown.-#[derive(Debug, Clone, PartialEq)]-pub struct SubagentUsageEntry {- pub task_id: String,- pub agent_id: String,- pub usage: SubagentUsage,-}--/// Holistic token/cost accounting for a single completed turn, including any-/// sub-agent spend rolled in. Captured on the session at turn end and consumed-/// by the web-channel delivery layer, which forwards it on the `chat_done`-/// event so the UI footer can show session tokens, context-window utilisation,-/// USD cost, and a per-sub-agent hover breakdown.-#[derive(Debug, Clone, Default, PartialEq)]-pub struct LastTurnUsage {- /// Input (prompt) tokens for the turn, parent + sub-agents.- pub input_tokens: u64,- /// Output (completion) tokens for the turn, parent + sub-agents.- pub output_tokens: u64,- /// Cached-input tokens for the turn, parent + sub-agents.- pub cached_input_tokens: u64,- /// USD cost for the turn (backend-charged where available, else estimated),- /// parent + sub-agents.- pub cost_usd: f64,- /// The model's context window for this turn (`0` when unknown, e.g. a cloud- /// model whose window the core couldn't resolve). Lets the UI show real- /// context utilisation instead of a hard-coded default.- pub context_window: u64,- /// Per-sub-agent spend gathered during the turn, for the hover breakdown.- pub subagents: Vec<SubagentUsageEntry>,-}--/// Shared, mutable list of sub-agent spend gathered during one parent turn.-type TurnSubagentUsage = Arc<Mutex<Vec<SubagentUsageEntry>>>;--tokio::task_local! {- /// Active per-turn sub-agent usage collector, installed around the parent's- /// turn future (`run_turn_via_tinyagents_shared`). Absent outside a turn- /// scope.- static TURN_SUBAGENT_USAGE: TurnSubagentUsage;-}--/// The collector active for the current turn, or `None` when no scope is in-/// effect (e.g. a sub-agent running on a detached background task, or a direct-/// CLI invocation).-fn current_collector() -> Option<TurnSubagentUsage> {- TURN_SUBAGENT_USAGE.try_with(|c| c.clone()).ok()-}--/// Record a finished sub-agent's token/cost totals into the active turn-/// collector. No-op when there is no active scope. Called by the sub-agent-/// runner once it has the run's aggregated usage.-pub(crate) fn record_subagent_usage(task_id: &str, agent_id: &str, usage: SubagentUsage) {- let Some(collector) = current_collector() else {- tracing::trace!(- task_id,- agent_id,- "[turn_subagent_usage] no active collector — sub-agent spend not rolled into parent turn"- );- return;- };- let entry = SubagentUsageEntry {- task_id: task_id.to_string(),- agent_id: agent_id.to_string(),- usage,- };- // Recover the inner vec on poison (a panic in another sub-agent) rather than- // dropping this turn's accounting entirely.- let mut guard = collector.lock().unwrap_or_else(|poisoned| {- tracing::warn!(- task_id,- agent_id,- "[turn_subagent_usage] collector mutex poisoned — recovering"- );- poisoned.into_inner()- });- tracing::debug!(- task_id,- agent_id,- input_tokens = usage.input_tokens,- output_tokens = usage.output_tokens,- charged_usd = usage.charged_amount_usd,- "[turn_subagent_usage] recorded sub-agent spend into parent turn"- );- guard.push(entry);-}--/// Run `future` with a fresh sub-agent usage collector installed, returning both-/// the future's output and the gathered per-child entries. Intended call site is-/// around the parent agent's turn (`run_turn_via_tinyagents_shared`) invocation.-pub(crate) async fn with_turn_collector<F, R>(future: F) -> (R, Vec<SubagentUsageEntry>)-where- F: std::future::Future<Output = R>,-{- let collector: TurnSubagentUsage = Arc::new(Mutex::new(Vec::new()));- // `scope` takes the inner future **by value**, so a debug build moves the- // whole nested turn generator through this frame on its way in. On the agent- // turn path that nesting is hundreds of KiB, and this wrapper was the most- // expensive of them: measured under gdb, its own frame was 239,184 bytes of- // a 2,090,360-byte stack, against the 2 MiB thread `libtest` hands a test.- // Pinning to the heap first means only a pointer moves. Boxing here and at- // the four sibling `scope` wrappers took the same stack to 731,928 bytes and- // fixed 131 tests that aborted on a stack overflow; the cost is one- // allocation per scope, against a turn that is about to call a model.- let out = TURN_SUBAGENT_USAGE- .scope(collector.clone(), Box::pin(future))- .await;- let entries = collector- .lock()- .map(|g| g.clone())- .unwrap_or_else(|p| p.into_inner().clone());- (out, entries)-}--#[cfg(test)]-#[path = "turn_subagent_usage_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/turn_subagent_usage_tests.rs b/crates/openhuman-core/src/agent/harness/turn_subagent_usage_tests.rsdeleted file mode 100644index 44a9d3eccd..0000000000--- a/crates/openhuman-core/src/agent/harness/turn_subagent_usage_tests.rs+++ /dev/null@@ -1,69 +0,0 @@-use super::*;--fn usage(input: u64, output: u64, usd: f64) -> SubagentUsage {- SubagentUsage {- input_tokens: input,- output_tokens: output,- cached_input_tokens: 0,- charged_amount_usd: usd,- }-}--#[tokio::test]-async fn no_collector_outside_scope() {- assert!(current_collector().is_none());- // Must not panic when there is nothing to record into.- record_subagent_usage("t1", "researcher", usage(10, 5, 0.01));-}--#[tokio::test]-async fn collects_entries_within_scope() {- let ((), entries) = with_turn_collector(async {- record_subagent_usage("t1", "researcher", usage(10, 5, 0.01));- record_subagent_usage("t2", "coder", usage(20, 8, 0.02));- })- .await;- assert_eq!(entries.len(), 2);- assert_eq!(entries[0].task_id, "t1");- assert_eq!(entries[0].usage.input_tokens, 10);- assert_eq!(entries[1].agent_id, "coder");- assert_eq!(entries[1].usage.charged_amount_usd, 0.02);-}--#[tokio::test]-async fn map_reduce_fanout_preserves_scope() {- use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};-- let (result, entries) = with_turn_collector(async {- map_reduce(- vec![- ("t1", "researcher", usage(10, 5, 0.01)),- ("t2", "coder", usage(20, 8, 0.02)),- ],- ParallelOptions::default()- .with_max_concurrency(2)- .with_failure_policy(FailurePolicy::CollectAll),- |_index, (task_id, agent_id, usage)| async move {- record_subagent_usage(task_id, agent_id, usage);- Ok::<_, tinyagents_harness::TinyAgentsError>(task_id)- },- )- .await- })- .await;-- let outcome = result.expect("map_reduce should complete");- assert_eq!(outcome.outcomes.len(), 2);- assert_eq!(entries.len(), 2);- assert_eq!(entries[0].task_id, "t1");- assert_eq!(entries[1].agent_id, "coder");-}--#[tokio::test]-async fn scope_does_not_leak() {- let _ = with_turn_collector(async {- record_subagent_usage("t1", "researcher", usage(1, 1, 0.0));- })- .await;- assert!(current_collector().is_none());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs b/crates/openhuman-core/src/agent/tinyagents/host/mod.rsindex 1adfcb18ec..e7b2b23e62 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/mod.rs@@ -51,6 +51,9 @@ pub use experience_store::OpenHumanExperienceStore;pub use learning_sink::OpenHumanLearningSink;pub use model_resolver::OpenHumanModelResolver;pub use progress_sink::OpenHumanProgressSink;-pub use run_context::OpenHumanRunContext;+pub use run_context::{+ decide_dispatch, DispatchDecision, DispatchInputs, LastTurnUsage, OpenHumanRunContext,+ SubagentUsageEntry, TurnDispatchState,+};pub use security_gate::OpenHumanSecurityGate;pub use tool_outcome_classifier::OpenHumanToolOutcomeClassifier;diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex b62b0addbc..bce77a78db 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -9,22 +9,153 @@//! so every host seam receives the same explicit carrier rather than recovering//! product state from a task-local.+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;+use std::time::Instant;use tokio::sync::mpsc::Sender;use crate::agent::harness::definition::SandboxMode;use crate::agent::harness::fork_context::{AgentContextPreparedSource, ParentExecutionContext};+use crate::agent::harness::subagent_runner::SubagentUsage;use crate::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore;-use crate::agent::harness::turn_dispatch_guard::TurnDispatchState;-use crate::agent::harness::turn_subagent_usage::SubagentUsageEntry;use crate::agent::progress::AgentProgress;use crate::agent::stop_hooks::StopHook;use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;use crate::agent::turn_origin::AgentTurnOrigin;use tinyinference_llm::model::ResolvedModelRoute;+/// One delegated run's token and cost totals, retained for the parent-turn+/// usage breakdown.+#[derive(Debug, Clone, PartialEq)]+pub struct SubagentUsageEntry {+ pub task_id: String,+ pub agent_id: String,+ pub usage: SubagentUsage,+}++/// Complete usage for a completed root turn, including synchronous children.+#[derive(Debug, Clone, Default, PartialEq)]+pub struct LastTurnUsage {+ pub input_tokens: u64,+ pub output_tokens: u64,+ pub cached_input_tokens: u64,+ pub cost_usd: f64,+ pub context_window: u64,+ pub subagents: Vec<SubagentUsageEntry>,+}++/// Immutable inputs to the host's pre-dispatch policy.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DispatchInputs {+ pub pause_requested: bool,+ pub pause_completed_calls: u64,+ pub pause_cap: u64,+ pub remaining: Option<Duration>,+ pub observed_max: Option<Duration>,+ pub observed_samples: u64,+}++/// Outcome of the host's pre-dispatch policy.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DispatchDecision {+ Allow,+ RefusePaused {+ completed_model_calls: u64,+ cap: u64,+ },+ RefuseBudget {+ remaining_ms: u64,+ observed_max_ms: u64,+ observed_samples: u64,+ },+}++/// Decide whether a child can be started using only evidence recorded on this+/// turn. This stays host policy: TinyAgents owns the loop, not OpenHuman's+/// pause and wall-clock refusal rules.+pub fn decide_dispatch(inputs: DispatchInputs) -> DispatchDecision {+ if inputs.pause_requested {+ return DispatchDecision::RefusePaused {+ completed_model_calls: inputs.pause_completed_calls,+ cap: inputs.pause_cap,+ };+ }+ let (Some(remaining), Some(observed_max)) = (inputs.remaining, inputs.observed_max) else {+ return DispatchDecision::Allow;+ };+ if remaining < observed_max {+ return DispatchDecision::RefuseBudget {+ remaining_ms: remaining.as_millis().min(u128::from(u64::MAX)) as u64,+ observed_max_ms: observed_max.as_millis().min(u128::from(u64::MAX)) as u64,+ observed_samples: inputs.observed_samples,+ };+ }+ DispatchDecision::Allow+}++/// Shared root-turn state used by all synchronous descendants and siblings to+/// decide whether starting another delegate is still safe.+#[derive(Debug)]+pub struct TurnDispatchState {+ pause_requested: AtomicBool,+ pause_completed_calls: AtomicU64,+ pause_cap: AtomicU64,+ started: Instant,+ budget: Option<Duration>,+ observed_max_ms: AtomicU64,+ observed_samples: AtomicU64,+}++impl TurnDispatchState {+ pub fn new(budget: Option<Duration>) -> Self {+ Self {+ pause_requested: AtomicBool::new(false),+ pause_completed_calls: AtomicU64::new(0),+ pause_cap: AtomicU64::new(0),+ started: Instant::now(),+ budget,+ observed_max_ms: AtomicU64::new(0),+ observed_samples: AtomicU64::new(0),+ }+ }++ pub fn record_pause_requested(&self, completed_model_calls: u64, cap: u64) {+ self.pause_completed_calls+ .store(completed_model_calls, Ordering::SeqCst);+ self.pause_cap.store(cap, Ordering::SeqCst);+ self.pause_requested.store(true, Ordering::SeqCst);+ }++ pub fn record_subagent_elapsed(&self, elapsed: Duration) {+ let ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64;+ self.observed_samples.fetch_add(1, Ordering::SeqCst);+ self.observed_max_ms.fetch_max(ms, Ordering::SeqCst);+ }++ pub fn snapshot(&self) -> DispatchInputs {+ let observed_max = match self.observed_max_ms.load(Ordering::SeqCst) {+ 0 => None,+ ms => Some(Duration::from_millis(ms)),+ };+ DispatchInputs {+ pause_requested: self.pause_requested.load(Ordering::SeqCst),+ pause_completed_calls: self.pause_completed_calls.load(Ordering::SeqCst),+ pause_cap: self.pause_cap.load(Ordering::SeqCst),+ remaining: self+ .budget+ .map(|budget| budget.saturating_sub(self.started.elapsed())),+ observed_max,+ observed_samples: self.observed_samples.load(Ordering::SeqCst),+ }+ }++ pub fn check(&self) -> DispatchDecision {+ decide_dispatch(self.snapshot())+ }+}+/// Explicit OpenHuman data carried by a top-level or child agent run.////// Shared members (`Arc`s, cancellation and workspace descriptor) retain the@@ -59,6 +190,10 @@ pub struct OpenHumanRunContext {pub spawn_depth: usize,/// This run's subagent usage roll-up; intentionally isolated for children.pub subagent_usage: Arc<Mutex<Vec<SubagentUsageEntry>>>,+ /// The immediate parent's ledger. A child writes its own completed total to+ /// this explicit handle, while nested children first collect in this run's+ /// isolated ledger. It is never a task-local or a root-global collector.+ parent_subagent_usage: Option<Arc<Mutex<Vec<SubagentUsageEntry>>>>,/// Provider/model/host-route observation for this run, written from the/// canonical response metadata by typed model middleware. Intentionally/// isolated for children.@@ -97,6 +232,7 @@ impl OpenHumanRunContext {sandbox_mode: None,spawn_depth: 0,subagent_usage: Arc::new(Mutex::new(Vec::new())),+ parent_subagent_usage: None,resolved_route: Arc::new(Mutex::new(None)),cancellation: tinyagents_harness::cancel::CancellationToken::new(),thread_id: None,@@ -131,6 +267,7 @@ impl OpenHumanRunContext {let mut child = self.clone();child.spawn_depth = self.spawn_depth.saturating_add(1);child.file_state_agent_id = None;+ child.parent_subagent_usage = Some(self.subagent_usage.clone());child.subagent_usage = Arc::new(Mutex::new(Vec::new()));child.resolved_route = Arc::new(Mutex::new(None));child@@ -173,6 +310,30 @@ impl OpenHumanRunContext {.push(entry);}+ /// Record a completed child on the immediate parent's ledger. This makes+ /// completed children visible at the root without leaking siblings into one+ /// another's in-flight ledger. Direct/root callers retain their own entry.+ pub fn record_completed_subagent_usage(&self, entry: SubagentUsageEntry) {+ let ledger = self+ .parent_subagent_usage+ .as_ref()+ .unwrap_or(&self.subagent_usage);+ ledger+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .push(entry);+ }++ /// Snapshot child totals after the child has returned. A snapshot, rather+ /// than a task-local drain, preserves totals even when sibling futures are+ /// cancelled or one child fails after another has completed.+ pub fn subagent_usage_entries(&self) -> Vec<SubagentUsageEntry> {+ self.subagent_usage+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .clone()+ }+/// Resolves whether a file-state scope has been assigned to this context./// Keeping the conversion here makes file-state callers use the explicit/// context instead of discovering an ambient identifier.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.rsindex 6cf7f05b8a..af7d546a9d 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@@ -55,3 +55,65 @@ fn root_context_is_owned_and_children_inherit_thread() {root.thread_id = Some("thread-a".to_owned());assert_eq!(root.child().thread_id.as_deref(), Some("thread-a"));}++#[test]+fn dispatch_guard_refuses_pause_and_budget_without_a_task_scope() {+ let paused = TurnDispatchState::new(Some(std::time::Duration::from_secs(60)));+ paused.record_pause_requested(15, 15);+ assert_eq!(+ paused.check(),+ DispatchDecision::RefusePaused {+ completed_model_calls: 15,+ cap: 15,+ }+ );++ // A zero budget makes the time relationship deterministic: after an+ // observed child, any check is strictly short of that child's duration.+ let exhausted = TurnDispatchState::new(Some(std::time::Duration::ZERO));+ exhausted.record_subagent_elapsed(std::time::Duration::from_secs(1));+ assert!(matches!(+ exhausted.check(),+ DispatchDecision::RefuseBudget {+ observed_max_ms: 1_000,+ observed_samples: 1,+ ..+ }+ ));+}++#[test]+fn child_ledgers_are_isolated_and_parent_keeps_completed_child_totals() {+ let root = OpenHumanRunContext::new();+ let left = root.child();+ let right = root.child();+ left.append_subagent_usage(SubagentUsageEntry {+ task_id: "left-task".into(),+ agent_id: "researcher".into(),+ usage: crate::agent::harness::subagent_runner::SubagentUsage {+ input_tokens: 3,+ output_tokens: 2,+ cached_input_tokens: 1,+ charged_amount_usd: 0.01,+ },+ });+ assert!(right.subagent_usage_entries().is_empty());++ left.record_completed_subagent_usage(SubagentUsageEntry {+ task_id: "completed-child".into(),+ agent_id: "researcher".into(),+ usage: crate::agent::harness::subagent_runner::SubagentUsage::default(),+ });+ assert_eq!(root.subagent_usage_entries().len(), 1);+ assert_eq!(left.subagent_usage_entries().len(), 1);+}++#[test]+fn children_inherit_attachment_placeholders() {+ let mut root = OpenHumanRunContext::new();+ root.attachment_placeholders = std::sync::Arc::new(vec!["[Image: x #att:1]".into()]);+ assert_eq!(+ root.child().attachment_placeholders.as_slice(),+ ["[Image: x #att:1]"]+ );+}diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rsindex 1abaa10fab..d5dfeb368b 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs@@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex};use tinyagents_harness::events::{AgentEvent, EventListener, EventRecord};use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use crate::agent::harness::turn_dispatch_guard::TurnDispatchState;+use crate::agent::tinyagents::host::TurnDispatchState;/// Attribution for child (sub-agent) progress. When present, the bridge routes/// events to the `Subagent*` [`AgentProgress`](crate::agent::progress::AgentProgress)@@ -107,14 +107,14 @@ pub(crate) struct CapPauser {/// The current turn's dispatch guard, when this run is a turn (rather than/// a CLI/direct invocation). Recording the pause here is what makes it/// *binding* on new sub-agent dispatch instead of merely advisory — see- /// [`crate::agent::harness::turn_dispatch_guard`] and #5804.+ /// [`crate::agent::tinyagents::host::TurnDispatchState`] and #5804.dispatch_guard: Option<Arc<TurnDispatchState>>,}impl CapPauser {/// Pause `handle` once `cap` of run `run_id`'s own model calls complete,/// recording the pause on `dispatch_guard` when the run is executing inside- /// a turn scope.+ /// a root turn context.pub(crate) fn new(handle: SteeringHandle,cap: usize,diff --git a/crates/openhuman-core/src/platform/socket/medulla/mod.rs b/crates/openhuman-core/src/platform/socket/medulla/mod.rsindex 09fc288c60..f46a2ff767 100644--- a/crates/openhuman-core/src/platform/socket/medulla/mod.rs+++ b/crates/openhuman-core/src/platform/socket/medulla/mod.rs@@ -448,9 +448,7 @@ fn next_seq(seq: &AtomicI64) -> i64 {/// Project the crate-private [`LastTurnUsage`] into a compact JSON usage block/// for `medulla:task_result` (the type itself isn't `Serialize`).-fn usage_to_json(- usage: crate::agent::harness::turn_subagent_usage::LastTurnUsage,-) -> serde_json::Value {+fn usage_to_json(usage: crate::agent::tinyagents::host::LastTurnUsage) -> serde_json::Value {serde_json::json!({"inputTokens": usage.input_tokens,"outputTokens": usage.output_tokens,diff --git a/crates/openhuman-core/src/web_chat/presentation.rs b/crates/openhuman-core/src/web_chat/presentation.rsindex 96bcffccb5..fca2bb1ef6 100644--- a/crates/openhuman-core/src/web_chat/presentation.rs+++ b/crates/openhuman-core/src/web_chat/presentation.rs@@ -9,7 +9,7 @@//! 2. **Emoji reactions** — decide whether the assistant should react to the//! user's message with an emoji.-use crate::agent::harness::turn_subagent_usage::LastTurnUsage;+use crate::agent::tinyagents::host::LastTurnUsage;use crate::config::rpc as config_rpc;use crate::core::socketio::{SubagentUsagePayload, TurnUsagePayload, WebChannelEvent};diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rsindex 535cc3fbfc..0223343726 100644--- a/crates/openhuman-core/src/web_chat/types.rs+++ b/crates/openhuman-core/src/web_chat/types.rs@@ -78,7 +78,7 @@ pub(super) struct WebChatTaskResult {/// Holistic token/cost/context totals for the turn (parent + sub-agents),/// forwarded to the frontend on `chat_done`. `None` for synthetic results/// (e.g. budget-exhausted placeholders) that never ran a real turn.- pub(super) usage: Option<crate::agent::harness::turn_subagent_usage::LastTurnUsage>,+ pub(super) usage: Option<crate::agent::tinyagents::host::LastTurnUsage>,/// The workspace this turn actually ran in, carried to delivery so the/// reply is stored there before it is announced (#6034).///diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex 1205021720..4de2903004 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -23,7 +23,7 @@{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/harness/session/turn/graph.rs",- "line": 122,+ "line": 125,"text": "run_turn_via_tinyagents_shared(","occurrence": 1},@@ -247,42 +247,21 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 44,- "text": "pub mod turn_attachments_context;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 45,- "text": "pub mod turn_dispatch_guard;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 46,- "text": "pub mod turn_subagent_usage;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 60,+ "line": 57,"text": "pub use sandbox_context::{current_sandbox_mode, with_current_sandbox_mode};","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 61,+ "line": 58,"text": "pub(crate) use spawn_depth_context::{current_spawn_depth, with_spawn_depth, MAX_SPAWN_DEPTH};","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/mod.rs",- "line": 63,+ "line": 60,"text": "pub use task_recency_context::{current_task_recency_window, with_task_recency_window};","occurrence": 1},@@ -335,48 +314,6 @@"text": "if self.auto_save && crate::agent::turn_origin::current_is_user_authored() {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 667,- "text": "harness::with_parent_context(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 669,- "text": "harness::with_agent_context_prepared_sources(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 671,- "text": "harness::turn_attachments_context::with_current_turn_image_placeholders(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 679,- "text": "harness::with_parent_context(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 681,- "text": "harness::with_agent_context_prepared_sources(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs",- "line": 683,- "text": "harness::turn_attachments_context::with_current_turn_image_placeholders(",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/core/experience_context.rs",@@ -387,24 +324,10 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs",- "line": 79,+ "line": 81,"text": "crate::agent::turn_origin::current_request_id()","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs",- "line": 179,- "text": "crate::agent::harness::turn_subagent_usage::with_turn_collector(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs",- "line": 217,- "text": "crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/graph.rs",@@ -415,7 +338,7 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/turn/graph.rs",- "line": 116,+ "line": 119,"text": "with_current_sandbox_mode(graph.sandbox_mode, async {","occurrence": 1},@@ -457,73 +380,31 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/mod.rs",- "line": 73,+ "line": 71,"text": "pub(super) use crate::agent::harness::{current_spawn_depth, with_spawn_depth, MAX_SPAWN_DEPTH};","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 411,- "text": "match turn_dispatch_guard::check() {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 451,- "text": "let parent = current_parent().ok_or(SubagentRunError::NoParentContext)?;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 453,- "text": "let current_depth = current_spawn_depth();",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 557,- "text": "turn_dispatch_guard::record_subagent_elapsed(started.elapsed());",+ "line": 37,+ "text": "use crate::agent::harness::{with_current_sandbox_mode, with_spawn_depth, MAX_SPAWN_DEPTH};","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 598,+ "line": 601,"text": "let run_result = with_spawn_depth(attempted_depth, async {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 600,+ "line": 603,"text": "with_current_sandbox_mode(definition.sandbox_mode, async {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 601,- "text": "with_parent_context(parent_for_subagent.clone(), async {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 636,- "text": "turn_dispatch_guard::record_subagent_elapsed(started.elapsed());",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs",- "line": 1733,- "text": "crate::agent::harness::turn_subagent_usage::record_subagent_usage(",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/task_recency_context.rs",@@ -559,62 +440,6 @@"text": "let out = TASK_RECENCY_WINDOW.scope(window, future).await;","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_attachments_context.rs",- "line": 20,- "text": "tokio::task_local! {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_attachments_context.rs",- "line": 22,- "text": "pub static CURRENT_TURN_IMAGE_PLACEHOLDERS: Vec<String>;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_attachments_context.rs",- "line": 26,- "text": "pub fn current_turn_image_placeholders() -> Vec<String> {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_attachments_context.rs",- "line": 27,- "text": "CURRENT_TURN_IMAGE_PLACEHOLDERS",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_attachments_context.rs",- "line": 42,- "text": "CURRENT_TURN_IMAGE_PLACEHOLDERS",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_dispatch_guard.rs",- "line": 239,- "text": "tokio::task_local! {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_subagent_usage.rs",- "line": 66,- "text": "tokio::task_local! {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/harness/turn_subagent_usage.rs",- "line": 83,- "text": "pub(crate) fn record_subagent_usage(task_id: &str, agent_id: &str, usage: SubagentUsage) {",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs",