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
feat(embed): scope hooks, permissions, tools and usage to agents and turns
Steven Enamakel917d2b2b4565
diff --git a/AGENTS.md b/AGENTS.mdindex e2ae8e2346..a927f0e2d1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -487,7 +487,9 @@ seed history by hand, or pick a transcript by recency.count. The host never shrinks a thread's tools because a cache went cold:`session_host/recorded_tools.rs` rebuilds recorded Composio actions asdeferred executors, and the prelude fetches integrations on the first turn- of every session instance, not only on a brand-new thread.+ of every session instance, not only on a brand-new thread. Explicit embed+ `Turn::tools` overrides and host-only belts are authoritative instead: they+ do not restore revoked tools from an earlier transcript.- **Pre-identity conversations are adopted once**, on first resume, from thetimestamped stems they were written to (`adopt_legacy_session_transcripts`).No legacy file is modified.diff --git a/crates/openhuman-core/src/agent/hooks.rs b/crates/openhuman-core/src/agent/hooks.rsindex e855e4d776..17b1d28963 100644--- a/crates/openhuman-core/src/agent/hooks.rs+++ b/crates/openhuman-core/src/agent/hooks.rs@@ -4,6 +4,10 @@//! what happened (user message, assistant response, tool calls with outcomes).//! The agent does not wait for hooks — they run in the background via `tokio::spawn`.+#[path = "hooks_scope.rs"]+mod scope;+pub use scope::{turn_post_turn_hooks, turn_tool_hooks, HookScope};+use async_trait::async_trait;use serde::{Deserialize, Serialize};use std::sync::Arc;@@ -171,6 +175,9 @@ pub struct ToolHookContext {/// Canonical agent definition id, when known.#[serde(default, skip_serializing_if = "Option::is_none")]pub agent_id: Option<String>,+ /// Working root of this tool dispatch, including a per-turn cwd override.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub cwd: Option<std::path::PathBuf>,}/// What a pre-tool hook decided about a call.diff --git a/crates/openhuman-core/src/agent/hooks_scope.rs b/crates/openhuman-core/src/agent/hooks_scope.rsnew file mode 100644index 0000000000..7d7a2b32cf--- /dev/null+++ b/crates/openhuman-core/src/agent/hooks_scope.rs@@ -0,0 +1,67 @@+//! Owned hooks carried by one dispatch task, never installed process-wide.++use std::future::Future;+use std::sync::Arc;++use super::{PostTurnHook, ToolHook};++tokio::task_local! {+ static ACTIVE: HookScope;+}++/// Agent/turn callbacks added after the runtime's global callbacks.+///+/// Sessions snapshot these while they are built; asynchronous post-turn+/// callbacks own that snapshot. Independently spawned tasks must explicitly+/// inherit the scope if they build further sessions.+#[derive(Clone, Default)]+pub struct HookScope {+ tools: Vec<Arc<dyn ToolHook>>,+ post_turn: Vec<Arc<dyn PostTurnHook>>,+ stop: Vec<Arc<dyn crate::agent::stop_hooks::StopHook>>,+}++impl HookScope {+ /// Append a tool callback, preserving registration order.+ pub fn push_tool(&mut self, hook: Arc<dyn ToolHook>) {+ self.tools.push(hook);+ }++ /// Append a completed-turn callback, preserving registration order.+ pub fn push_post_turn(&mut self, hook: Arc<dyn PostTurnHook>) {+ self.post_turn.push(hook);+ }++ /// Append a usage observer/budget policy checked after each model call.+ pub fn push_stop(&mut self, hook: Arc<dyn crate::agent::stop_hooks::StopHook>) {+ self.stop.push(hook);+ }++ /// Build a session with scoped tool/post-turn callbacks. Stop policies+ /// enter through the asynchronous dispatch scope when the turn runs.+ pub fn sync_scope<T>(self, build: impl FnOnce() -> T) -> T {+ ACTIVE.sync_scope(self, build)+ }++ /// Run a dispatch with this scope. Nested scopes replace tool/post-turn+ /// callbacks and append their stop policies to the ambient policies.+ pub async fn scope<F: Future>(self, future: F) -> F::Output {+ let mut stop = crate::agent::stop_hooks::current_stop_hooks();+ stop.extend(self.stop.iter().cloned());+ crate::agent::stop_hooks::with_stop_hooks(stop, ACTIVE.scope(self, future)).await+ }+}++/// Session snapshot: process-wide tool callbacks, then the dispatch's callbacks.+pub fn turn_tool_hooks() -> Vec<Arc<dyn ToolHook>> {+ let mut hooks = super::embedder_tool_hooks();+ let _ = ACTIVE.try_with(|scope| hooks.extend(scope.tools.iter().cloned()));+ hooks+}++/// Session snapshot: process-wide post-turn callbacks, then dispatch callbacks.+pub fn turn_post_turn_hooks() -> Vec<Arc<dyn PostTurnHook>> {+ let mut hooks = super::embedder_post_turn_hooks();+ let _ = ACTIVE.try_with(|scope| hooks.extend(scope.post_turn.iter().cloned()));+ hooks+}diff --git a/crates/openhuman-core/src/agent/host_agents.rs b/crates/openhuman-core/src/agent/host_agents.rsindex 4affadbece..f3c297ce08 100644--- a/crates/openhuman-core/src/agent/host_agents.rs+++ b/crates/openhuman-core/src/agent/host_agents.rs@@ -47,6 +47,8 @@ pub struct HostAgent {pub host_tools: Option<HostTools>,/// The context every read during the agent's turn must see.pub context: Arc<CoreContext>,+ /// Agent-owned callbacks inherited by core-scheduled turns.+ pub hooks: crate::agent::hooks::HookScope,}impl HostAgent {@@ -67,20 +69,25 @@ impl HostAgent {host_tools = self.host_tools.is_some(),"[host_agents] building session for host agent");- CoreContext::sync_scope(Arc::clone(&self.context), || match &self.host_tools {- Some(host) => OpenHumanSessionHost::from_config_with_host_tools(- config,- &self.definition,- host,- session_id,- ),- None => OpenHumanSessionHost::from_config_with_definition(config, &self.definition),+ self.hooks.clone().sync_scope(|| {+ CoreContext::sync_scope(Arc::clone(&self.context), || match &self.host_tools {+ Some(host) => OpenHumanSessionHost::from_config_with_host_tools(+ config,+ &self.definition,+ host,+ session_id,+ ),+ None => OpenHumanSessionHost::from_config_with_definition(config, &self.definition),+ })})}/// Run `fut` with this agent's context as the ambient [`CoreContext`].pub async fn scope<F: std::future::Future>(&self, fut: F) -> F::Output {- CoreContext::scope(Arc::clone(&self.context), fut).await+ self.hooks+ .clone()+ .scope(CoreContext::scope(Arc::clone(&self.context), fut))+ .await}}diff --git a/crates/openhuman-core/src/agent/host_agents_tests.rs b/crates/openhuman-core/src/agent/host_agents_tests.rsindex 489951c3f6..994a7b2568 100644--- a/crates/openhuman-core/src/agent/host_agents_tests.rs+++ b/crates/openhuman-core/src/agent/host_agents_tests.rs@@ -34,6 +34,7 @@ impl HostAgentResolver for OneAgent {definition: definition(&self.id),config: self.config.clone(),host_tools: None,+ hooks: Default::default(),context: CoreContext::for_test(DomainSet::full(), None),})}@@ -89,6 +90,7 @@ fn a_host_agent_debug_names_the_agent_and_hides_the_rest() {definition: definition("host-agents-debug"),config: Config::default(),host_tools: None,+ hooks: Default::default(),context: CoreContext::for_test(DomainSet::full(), None),};let rendered = format!("{host:?}");@@ -104,6 +106,7 @@ async fn scope_runs_the_future_under_the_agents_context() {definition: definition("host-agents-scope"),config: Config::default(),host_tools: None,+ hooks: Default::default(),context: Arc::clone(&context),};let seen = hostdiff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rsindex 32ad053a51..45de95d2d9 100644--- a/crates/openhuman-core/src/agent/mod.rs+++ b/crates/openhuman-core/src/agent/mod.rs@@ -78,6 +78,7 @@ pub mod subagent_host;pub mod tinyagents;pub mod todos;pub mod tool_policy;+pub mod tool_snapshot_scope;pub mod tools;pub mod triage;/// Wall-clock deadline of one top-level turn: the outer backstop and thediff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rsindex a50fd418eb..ced80b4f0c 100644--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@ -390,7 +390,7 @@ impl OpenHumanSessionHost {None => SystemPromptBuilder::with_defaults(),};let post_turn_hooks: Vec<Arc<dyn crate::agent::hooks::PostTurnHook>> =- crate::agent::hooks::embedder_post_turn_hooks();+ crate::agent::hooks::turn_post_turn_hooks();// Best-effort prewarm from the shared Composio cache. This avoids// building the session with a knowingly stale `&[]` integration viewdiff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 3a647f284d..d283dde453 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -11,6 +11,7 @@ mod memory_ingest;mod permanent;mod post_commit;mod tool_rules;+mod transcript;#[path = "runtime_session_turn.rs"]mod turn;pub(super) use turn::begin_turn_resume;@@ -22,10 +23,8 @@ use tinyagents_runtime::{CommitReceipt, ResumePreparation, SessionBuilder, SessionTerminal, ToolSnapshot,TranscriptTarget, TurnPreparation,};-use tinyagents_session::transcript::TranscriptMeta;use tinyinference_llm::message::Message;-use crate::agent::session_store::transcripts_or_files;use crate::agent::{message_convert::{user_message_from_text, user_text_with_markers},session_host::{@@ -1285,7 +1284,9 @@ impl OpenHumanSessionHost {let mut builder = SessionBuilder::new(driver).codec(Arc::new(OpenHumanTranscriptCodec)).hooks(hooks)- .retain_recorded_tools(true);+ .retain_recorded_tools(+ !self.host_only && crate::agent::tool_snapshot_scope::retain_recorded_tools(),+ );if let Some(session) = self.session.clone() {builder = builder.session(session_locator, session, self.runtime_transcript_meta());}@@ -1345,63 +1346,6 @@ impl OpenHumanSessionHost {agent_definition_name: self.agent_definition_name.clone(),});}-- fn runtime_transcript_stem(&self) -> String {- match &self.session_parent_prefix {- Some(prefix) => format!("{prefix}__{}", self.session_key),- None => self.session_key.clone(),- }- }-- pub(in crate::agent::session_host) fn session_locator(- &self,- ) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {- if let Some(injected) = self.session_history_locator.clone() {- return injected;- }- self.session_history_locator_memo- .get_or_init(|| {- let session_agent_id =- crate::agent::session_store::current_agent_key_or(&self.agent_definition_id);- transcripts_or_files(&session_agent_id, &self.workspace_dir)- })- .clone()- }-- fn runtime_transcript_meta(&self) -> TranscriptMeta {- let now = chrono::Utc::now().to_rfc3339();- TranscriptMeta {- agent_name: self.agent_definition_name.clone(),- agent_id: Some(self.agent_definition_id.clone()),- agent_type: Some(if self.session_parent_prefix.is_some() {- "subagent".into()- } else {- "root".into()- }),- dispatcher: if self.tool_dispatcher.should_send_tool_specs() {- "native".into()- } else {- "xml".into()- },- provider: None,- model: Some(self.model_name.clone()),- created: now.clone(),- updated: now,- turn_count: 0,- prefix_message_count: None,- input_tokens: 0,- output_tokens: 0,- cached_input_tokens: 0,- charged_amount_usd: 0.0,- thread_id: self.thread_id.clone(),- task_id: None,- session_id: self.session.as_ref().map(|session| session.session_id()),- parent_session_id: self- .session- .as_ref()- .and_then(|session| session.parent_session_id()),- }- }}#[path = "prelude_integrations.rs"]diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rsnew file mode 100644index 0000000000..f6e1b9fde5--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs@@ -0,0 +1,65 @@+//! Session transcript identity, locator and metadata construction.++use super::super::types::OpenHumanSessionHost;+use crate::agent::session_store::transcripts_or_files;+use std::sync::Arc;+use tinyagents_session::transcript::TranscriptMeta;++impl OpenHumanSessionHost {+ pub(super) fn runtime_transcript_stem(&self) -> String {+ match &self.session_parent_prefix {+ Some(prefix) => format!("{prefix}__{}", self.session_key),+ None => self.session_key.clone(),+ }+ }++ pub(in crate::agent::session_host) fn session_locator(+ &self,+ ) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {+ if let Some(injected) = self.session_history_locator.clone() {+ return injected;+ }+ self.session_history_locator_memo+ .get_or_init(|| {+ let session_agent_id =+ crate::agent::session_store::current_agent_key_or(&self.agent_definition_id);+ transcripts_or_files(&session_agent_id, &self.workspace_dir)+ })+ .clone()+ }++ pub(super) fn runtime_transcript_meta(&self) -> TranscriptMeta {+ let now = chrono::Utc::now().to_rfc3339();+ TranscriptMeta {+ agent_name: self.agent_definition_name.clone(),+ agent_id: Some(self.agent_definition_id.clone()),+ agent_type: Some(if self.session_parent_prefix.is_some() {+ "subagent".into()+ } else {+ "root".into()+ }),+ dispatcher: if self.tool_dispatcher.should_send_tool_specs() {+ "native".into()+ } else {+ "xml".into()+ },+ provider: None,+ model: Some(self.model_name.clone()),+ created: now.clone(),+ updated: now,+ turn_count: 0,+ prefix_message_count: None,+ input_tokens: 0,+ output_tokens: 0,+ cached_input_tokens: 0,+ charged_amount_usd: 0.0,+ thread_id: self.thread_id.clone(),+ task_id: None,+ session_id: self.session.as_ref().map(|session| session.session_id()),+ parent_session_id: self+ .session+ .as_ref()+ .and_then(|session| session.parent_session_id()),+ }+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 68f370f5cf..7ee49a40dc 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -316,10 +316,6 @@ pub(super) fn assemble_turn_harness(.as_ref().map(|_| Arc::new(ToolResultArtifactIndexStore::new()));- // The explicit run carrier supplies the stop hooks; no middleware needs to- // recover policy from a task-local while the harness is driving.- let stop_hooks_installed = stop_hooks;-// A steering handle is always created now: besides run-queue steering, the// early-exit / cap / stop-hook pauses, the repeated-tool-failure breaker// (below) also pauses through it, and it wants to fire on every path@@ -375,8 +371,7 @@ pub(super) fn assemble_turn_harness(harness.push_middleware(mw.clone());}- // Repeated-failure breaker: surface a root cause instead of burning the budget- // on failing calls; side effects come from the tools' own declarations.+ // Repeated failures stop the run using each tool's declared side effects.let repeated_failure = handle.as_ref().map(|handle| {let (t, halt) = (REPEATED_TOOL_FAILURE_THRESHOLD, halt_summary.clone());let mw = middleware::RepeatedToolFailureMiddleware::new(handle.clone(), t, halt);@@ -386,19 +381,14 @@ pub(super) fn assemble_turn_harness(harness.push_middleware(mw.clone());}- // Policy-driven stop hooks (budget cap, thread-goal budget, ad-hoc iteration- // ceiling): fire after each model call and pause the run on the first stop- // vote. Replaces the legacy tool-call-loop firing point.- if let Some(handle) = &handle {- if !stop_hooks_installed.is_empty() {- harness.push_middleware(Arc::new(stop_hooks::StopHookMiddleware::new(- handle.clone(),- model,- max_iterations,- stop_hooks_installed,- )));- }- }+ stop_hooks::install(+ &mut harness,+ handle.as_ref(),+ model,+ max_iterations,+ stop_hooks,+ halt_summary.clone(),+ );let early_exit_set: HashSet<&str> = early_exit_tools.iter().copied().collect();// One hook per run, shared by every early-exit adapter (records the first// early-exit and pauses). Requires the steering handle.@@ -709,7 +699,7 @@ pub(super) fn assemble_turn_harness(// observation-only (never mutates the result), so running first in the// reverse-order `after_tool` chain is safe — it cannot perturb the// summarization/cap or tool-outcome capture layers.- let embedder_tool_hooks = crate::agent::hooks::embedder_tool_hooks();+ let embedder_tool_hooks = crate::agent::hooks::turn_tool_hooks();if !embedder_tool_hooks.is_empty() {harness.push_middleware(Arc::new(middleware::EmbedderToolHooksMiddleware::new(embedder_tool_hooks,diff --git a/crates/openhuman-core/src/agent/tinyagents/live_harness.rs b/crates/openhuman-core/src/agent/tinyagents/live_harness.rsindex 79e2cfd1d4..92f3e715a6 100644--- a/crates/openhuman-core/src/agent/tinyagents/live_harness.rs+++ b/crates/openhuman-core/src/agent/tinyagents/live_harness.rs@@ -121,7 +121,7 @@ pub(crate) fn assemble_live_tool_harness(registered_tools,route_session,)));- let embedder_tool_hooks = crate::agent::hooks::embedder_tool_hooks();+ let embedder_tool_hooks = crate::agent::hooks::turn_tool_hooks();if !embedder_tool_hooks.is_empty() {harness.push_middleware(Arc::new(middleware::EmbedderToolHooksMiddleware::new(embedder_tool_hooks,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rsindex aca6086b22..90792af54b 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs@@ -41,7 +41,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>async fn before_tool(&self,- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,_state: &(),call: &mut TaToolCall,) -> TaResult<()> {@@ -54,8 +54,32 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>duration_ms: None,output: None,error: None,- session_id: None,- agent_id: None,+ session_id: ctx+ .data+ .thread_id+ .clone()+ .or_else(|| ctx.data.parent.as_ref().map(|p| p.session_id.clone())),+ agent_id: ctx+ .data+ .parent+ .as_ref()+ .map(|p| p.agent_definition_id.clone()),+ cwd: ctx+ .data+ .workspace+ .as_ref()+ .map(|w| w.root.clone())+ .or_else(|| {+ ctx.data+ .parent+ .as_ref()+ .and_then(|p| p.workspace_descriptor.as_ref().map(|w| w.root.clone()))+ })+ .or_else(|| {+ crate::core::runtime::CoreContext::with_current_embedder_config(|config| {+ config.action_dir.clone()+ })+ }),};for hook in &self.hooks {match hook.before_tool_decision(&context).await {@@ -120,7 +144,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>/// arguments through.async fn check_nested_tool(&self,- _ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,_state: &(),call: &TaToolCall,) -> TaResult<()> {@@ -133,8 +157,32 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>duration_ms: None,output: None,error: None,- session_id: None,- agent_id: None,+ session_id: ctx+ .data+ .thread_id+ .clone()+ .or_else(|| ctx.data.parent.as_ref().map(|p| p.session_id.clone())),+ agent_id: ctx+ .data+ .parent+ .as_ref()+ .map(|p| p.agent_definition_id.clone()),+ cwd: ctx+ .data+ .workspace+ .as_ref()+ .map(|w| w.root.clone())+ .or_else(|| {+ ctx.data+ .parent+ .as_ref()+ .and_then(|p| p.workspace_descriptor.as_ref().map(|w| w.root.clone()))+ })+ .or_else(|| {+ crate::core::runtime::CoreContext::with_current_embedder_config(|config| {+ config.action_dir.clone()+ })+ }),};for hook in &self.hooks {let refusal = match hook.before_tool_decision(&context).await {@@ -165,7 +213,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>async fn after_tool(&self,- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,_state: &(),invocation: &ToolInvocationIdentity,result: &mut TaToolResult,@@ -191,8 +239,32 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>error: result.is_error.then(|| crate::agent::tinyagents::middleware::tool_result_text(result)),- session_id: None,- agent_id: None,+ session_id: ctx+ .data+ .thread_id+ .clone()+ .or_else(|| ctx.data.parent.as_ref().map(|p| p.session_id.clone())),+ agent_id: ctx+ .data+ .parent+ .as_ref()+ .map(|p| p.agent_definition_id.clone()),+ cwd: ctx+ .data+ .workspace+ .as_ref()+ .map(|w| w.root.clone())+ .or_else(|| {+ ctx.data+ .parent+ .as_ref()+ .and_then(|p| p.workspace_descriptor.as_ref().map(|w| w.root.clone()))+ })+ .or_else(|| {+ crate::core::runtime::CoreContext::with_current_embedder_config(|config| {+ config.action_dir.clone()+ })+ }),};for hook in &self.hooks {// Text a hook returns is appended to the result the model reads —diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rsindex f40c7b1c46..230037fe07 100644--- a/crates/openhuman-core/src/agent/tinyagents/model.rs+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs@@ -274,7 +274,13 @@ pub(crate) fn usage_info_from_response(response: &ModelResponse) -> Option<Bille.raw.as_ref().and_then(|value| value.get("total_cost_usd"))- .and_then(serde_json::Value::as_f64);+ .and_then(serde_json::Value::as_f64)+ .or_else(|| response.raw.as_ref()?.get("usage")?.get("cost")?.as_f64())+ .or_else(|| {+ usage+ .charged_amount+ .map(|charge| charge.micros as f64 / 1_000_000.0)+ });}Some(BilledUsage::from_counts(usage.input_tokens, usage.output_tokens)diff --git a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rsindex bddd06d45f..2886980c13 100644--- a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs+++ b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs@@ -30,7 +30,26 @@ use tinyinference_llm::model::ModelResponse;use crate::agent::cost::TurnCost;use crate::agent::stop_hooks::{StopDecision, StopHook, TurnState};-use crate::inference::provider::BilledUsage;++/// Install after-call usage policies on the assembled turn harness.+pub(super) fn install(+ harness: &mut tinyagents_harness::runtime::AgentHarness<(), super::host::OpenHumanRunContext>,+ handle: Option<&SteeringHandle>,+ model: &str,+ max_iterations: usize,+ hooks: Vec<Arc<dyn StopHook>>,+ halt_summary: super::HaltSummarySlot,+) {+ if let Some(handle) = handle.filter(|_| !hooks.is_empty()) {+ harness.push_middleware(Arc::new(StopHookMiddleware::new(+ handle.clone(),+ model,+ max_iterations,+ hooks,+ halt_summary,+ )));+ }+}/// Fires openhuman [`StopHook`]s after each model call and pauses the run when/// any hook votes to stop.@@ -49,6 +68,7 @@ pub(super) struct StopHookMiddleware {hooks: Vec<Arc<dyn StopHook>>,/// Latches once a hook has voted to stop, so we send `Pause` exactly once.stopped: AtomicBool,+ halt_summary: super::HaltSummarySlot,}impl StopHookMiddleware {@@ -58,6 +78,7 @@ impl StopHookMiddleware {model: impl Into<String>,max_iterations: usize,hooks: Vec<Arc<dyn StopHook>>,+ halt_summary: super::HaltSummarySlot,) -> Self {Self {handle,@@ -67,6 +88,7 @@ impl StopHookMiddleware {cost: Mutex::new(TurnCost::new()),hooks,stopped: AtomicBool::new(false),+ halt_summary,}}}@@ -98,14 +120,8 @@ wherelet iteration = self.iteration.fetch_add(1, Ordering::SeqCst) + 1;let cost_snapshot = {let mut cost = self.cost.lock().expect("stop-hook cost mutex poisoned");- if let Some(usage) = &response.usage {- cost.add_call(- &self.model,- &BilledUsage::from_counts(usage.input_tokens, usage.output_tokens)- .with_cached_input_tokens(usage.cache_read_tokens)- .with_cache_creation_tokens(usage.cache_creation_tokens)- .with_reasoning_tokens(usage.reasoning_tokens),- );+ if let Some(usage) = super::model::usage_info_from_response(response) {+ cost.add_call(&self.model, &usage);}cost.clone()};@@ -117,26 +133,35 @@ wheremodel: &self.model,};+ // Every observer sees the completed call, including observers installed+ // after a budget policy. Preserve the first stop reason for the result.+ let mut stop = None;for hook in &self.hooks {if let StopDecision::Stop { reason } = hook.check(&turn_state).await {- // Latch first so a concurrent (streaming) after_model can't- // double-pause.- if self.stopped.swap(true, Ordering::SeqCst) {- return Ok(());+ if stop.is_none() {+ stop = Some((hook.name().to_owned(), reason));}- tracing::warn!(- target: "stop_hooks",- hook = hook.name(),- iteration,- model = %self.model,- "[stop_hooks] hook voted to stop the turn — pausing run: {reason}"- );- // Graceful stop: the loop drains steering at the top of the next- // iteration and `Pause` short-circuits it before the next model- // call. The partial transcript is returned to the caller.- self.handle.send(SteeringCommand::Pause);+ }+ }+ if let Some((hook, reason)) = stop {+ if self.stopped.swap(true, Ordering::SeqCst) {return Ok(());}+ tracing::warn!(+ target: "stop_hooks",+ hook,+ iteration,+ model = %self.model,+ "[stop_hooks] hook voted to stop the turn — pausing run: {reason}"+ );+ *self+ .halt_summary+ .lock()+ .expect("stop-hook halt mutex poisoned") = Some(format!(+ "Stopping after {} model call(s): {reason}",+ iteration+ ));+ self.handle.send(SteeringCommand::Pause);}Ok(())diff --git a/crates/openhuman-core/src/agent/tool_snapshot_scope.rs b/crates/openhuman-core/src/agent/tool_snapshot_scope.rsnew file mode 100644index 0000000000..497d7ad5b1--- /dev/null+++ b/crates/openhuman-core/src/agent/tool_snapshot_scope.rs@@ -0,0 +1,15 @@+//! Explicit one-turn tool authority over restored transcript declarations.++use std::future::Future;+tokio::task_local! { static FRESH: (); }++/// Run a turn with the current host belt as authoritative. Historical tool+/// declarations remain in the transcript but cannot restore a revoked tool.+/// Host-spawned dispatch tasks must explicitly carry this scope.+pub async fn with_fresh_snapshot<F: Future>(future: F) -> F::Output {+ FRESH.scope((), future).await+}++pub(crate) fn retain_recorded_tools() -> bool {+ FRESH.try_with(|_| ()).is_err()+}diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rsindex cfd6abbf0e..c4be6dbf20 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs@@ -235,6 +235,7 @@ impl HostAgentResolver for OneHostAgent {}),])})),+ hooks: Default::default(),context: CoreContext::for_test_with_config(DomainSet::full(), self.config.clone()),})}diff --git a/crates/openhuman-core/src/config/ops/loader_current_tests.rs b/crates/openhuman-core/src/config/ops/loader_current_tests.rsindex 4ced94e23b..bd049ede6b 100644--- a/crates/openhuman-core/src/config/ops/loader_current_tests.rs+++ b/crates/openhuman-core/src/config/ops/loader_current_tests.rs@@ -18,6 +18,7 @@ async fn a_context_route_follows_every_load_of_the_context_config() {config.ephemeral_route = Some(EphemeralRoute {endpoint: "http://127.0.0.1:9/v1".to_string(),api_key: "test-key".to_string(),+ headers: Vec::new(),});let loaded = CoreContext::scope(context_with(config), load_current_or_init())diff --git a/crates/openhuman-core/src/config/schema/ephemeral_route.rs b/crates/openhuman-core/src/config/schema/ephemeral_route.rsindex 964930e4b3..311ddab324 100644--- a/crates/openhuman-core/src/config/schema/ephemeral_route.rs+++ b/crates/openhuman-core/src/config/schema/ephemeral_route.rs@@ -60,6 +60,9 @@ pub struct EphemeralRoute {/// and only for [`EPHEMERAL_ROUTE_SLUG`], so it cannot be handed to a/// provider the caller did not name.pub api_key: String,+ /// Custom headers scoped to this endpoint, never copied to unrelated providers.+ #[serde(default)]+ pub headers: Vec<(String, String)>,}impl EphemeralRoute {@@ -71,7 +74,17 @@ impl EphemeralRoute {pub fn from_params(endpoint: Option<String>, api_key: Option<String>) -> Option<Self> {let endpoint = endpoint?.trim().to_string();let api_key = api_key?.trim().to_string();- (!endpoint.is_empty() && !api_key.is_empty()).then_some(Self { endpoint, api_key })+ (!endpoint.is_empty() && !api_key.is_empty()).then_some(Self {+ endpoint,+ api_key,+ headers: Vec::new(),+ })+ }++ /// Attach the embedding host's per-route headers.+ pub fn with_headers(mut self, headers: Vec<(String, String)>) -> Self {+ self.headers = headers;+ self}}diff --git a/crates/openhuman-core/src/config/schema/ephemeral_route_tests.rs b/crates/openhuman-core/src/config/schema/ephemeral_route_tests.rsindex c3e31c538c..ea5375a707 100644--- a/crates/openhuman-core/src/config/schema/ephemeral_route_tests.rs+++ b/crates/openhuman-core/src/config/schema/ephemeral_route_tests.rs@@ -15,6 +15,7 @@ fn route() -> EphemeralRoute {EphemeralRoute {endpoint: "http://127.0.0.1:41234/openai".to_string(),api_key: "mdl-token".to_string(),+ headers: Vec::new(),}}@@ -27,6 +28,7 @@ fn from_params_needs_both_halves() {Some(EphemeralRoute {endpoint: "http://x/openai".into(),api_key: "k".into(),+ headers: Vec::new(),}));// An endpoint with no credential and a credential with no endpoint are both@@ -55,6 +57,7 @@ fn from_params_treats_blank_as_absent_and_trims() {Some(EphemeralRoute {endpoint: "http://x/openai".into(),api_key: "k".into(),+ headers: Vec::new(),}));}@@ -155,6 +158,7 @@ fn apply_twice_leaves_one_entry() {EphemeralRoute {endpoint: "http://127.0.0.1:9999/openai".into(),api_key: "mdl-other".into(),+ headers: Vec::new(),},);let entries: Vec<_> = configdiff --git a/crates/openhuman-core/src/cron/scheduler_host_agent_tests.rs b/crates/openhuman-core/src/cron/scheduler_host_agent_tests.rsindex 2e175fb9f0..9daabe667e 100644--- a/crates/openhuman-core/src/cron/scheduler_host_agent_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_host_agent_tests.rs@@ -51,6 +51,7 @@ impl HostAgentResolver for Host {builds.fetch_add(1, Ordering::SeqCst);crate::agent::HostTurnTools::advertised(vec![Box::new(Marker)])})),+ hooks: Default::default(),context: CoreContext::for_test(DomainSet::full(),Some(self.config.workspace_dir.clone()),diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent_tests.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent_tests.rsindex 446e1119be..2428f9accd 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent_tests.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent_tests.rs@@ -48,6 +48,7 @@ impl crate::agent::host_agents::HostAgentResolver for FlowsHost {definition,config: crate::config::Config::default(),host_tools: None,+ hooks: Default::default(),context: crate::core::runtime::CoreContext::for_test(crate::core::runtime::DomainSet::full(),None,diff --git a/crates/openhuman-core/src/hooks/bridge_tests.rs b/crates/openhuman-core/src/hooks/bridge_tests.rsindex 10c060ce95..e5f0d3a1e4 100644--- a/crates/openhuman-core/src/hooks/bridge_tests.rs+++ b/crates/openhuman-core/src/hooks/bridge_tests.rs@@ -11,6 +11,7 @@ fn context(tool: &str, arguments: Value) -> ToolHookContext {output: None,error: None,session_id: Some("sess-1".into()),+ cwd: None,agent_id: None,}}diff --git a/crates/openhuman-core/src/inference/host_runtime/schemas.rs b/crates/openhuman-core/src/inference/host_runtime/schemas.rsindex 04e302f274..f4616504aa 100644--- a/crates/openhuman-core/src/inference/host_runtime/schemas.rs+++ b/crates/openhuman-core/src/inference/host_runtime/schemas.rs@@ -43,6 +43,8 @@ struct AgentChatParams {/// other provider.#[serde(default)]api_key: Option<String>,+ #[serde(default)]+ inference_headers: Vec<(String, String)>,}#[derive(Debug, Deserialize)]@@ -137,6 +139,12 @@ pub fn schemas(function: &str) -> ControllerSchema {"Bearer for inference_url. Scoped to this call and to that \endpoint alone.",),+ FieldSchema {+ name: "inference_headers",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::Json)))),+ comment: "Custom header name/value pairs for inference_url only; never persisted.",+ required: false,+ },],outputs: vec![json_output("response",@@ -232,7 +240,8 @@ fn handle_agent_chat(params: Map<String, Value>) -> ControllerFuture {p.temperature,p.thread_id,p.cwd,- crate::config::schema::EphemeralRoute::from_params(p.inference_url, p.api_key),+ crate::config::schema::EphemeralRoute::from_params(p.inference_url, p.api_key)+ .map(|route| route.with_headers(p.inference_headers)),).await?.into_rpc_json()diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rsindex a556573b50..03ba6980db 100644--- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs@@ -302,7 +302,15 @@ pub(super) fn try_create_cloud_slug_chat_model_from_string_with_native_tools(// legacy host's rare 404 → `/v1/responses` fallback for non-codex slugs is// not replicated).let mut endpoint = entry.endpoint.clone();- let mut extra_headers: Vec<(String, String)> = Vec::new();+ let mut extra_headers: Vec<(String, String)> = config+ .ephemeral_route+ .as_ref()+ .filter(|route| {+ slug == crate::config::schema::ephemeral_route::EPHEMERAL_ROUTE_SLUG+ && route.endpoint == entry.endpoint+ })+ .map(|route| route.headers.clone())+ .unwrap_or_default();let mut extra_query_params: Vec<(String, String)> = Vec::new();let mut user_agent: Option<String> = None;let mut responses_api_primary = false;diff --git a/crates/openhuman-core/src/inference/provider/factory_tests.rs b/crates/openhuman-core/src/inference/provider/factory_tests.rsindex f55e176cd9..c7357a4919 100644--- a/crates/openhuman-core/src/inference/provider/factory_tests.rs+++ b/crates/openhuman-core/src/inference/provider/factory_tests.rs@@ -167,6 +167,7 @@ fn routed_config(endpoint: &str, api_key: &str, model: &str) -> Config {EphemeralRoute {endpoint: endpoint.to_string(),api_key: api_key.to_string(),+ headers: Vec::new(),},);configdiff --git a/crates/openhuman-core/src/runtime/pool/node.rs b/crates/openhuman-core/src/runtime/pool/node.rsindex 7c22b78d92..ca5f7bd37e 100644--- a/crates/openhuman-core/src/runtime/pool/node.rs+++ b/crates/openhuman-core/src/runtime/pool/node.rs@@ -8,12 +8,23 @@ use tinyruntime_bus::Language;use super::{PoolExecOutcome, PoolRunError};use crate::config::{Config, RuntimePoolConfig};+/// A cancellable dispatch uses the owned-subprocess fallback: the pool has+/// no acknowledged per-job abort seam.+////// Whether inline `node` jobs should route through the pool.////// Node defaults **on**: each job runs in its own `worker_thread`, so reuse is/// safe — a fresh module graph and fresh globals per job.#[must_use]pub fn enabled(pool: &RuntimePoolConfig) -> bool {+ if crate::tools::timeout::ProcessCleanup::is_active()+ || crate::tools::timeout::CommandEnvironment::is_active()+ {+ tracing::debug!(+ "[node_exec] cancellable turn uses an owned subprocess instead of the pool"+ );+ return false;+ }pool.enabled && pool.node.is_enabled(true)}diff --git a/crates/openhuman-core/src/runtime/pool/python.rs b/crates/openhuman-core/src/runtime/pool/python.rsindex 82acbffb7e..420c85956c 100644--- a/crates/openhuman-core/src/runtime/pool/python.rs+++ b/crates/openhuman-core/src/runtime/pool/python.rs@@ -8,6 +8,9 @@ use tinyruntime_bus::Language;use super::{PoolExecOutcome, PoolRunError};use crate::config::{Config, RuntimePoolConfig};+/// A cancellable dispatch uses the owned-subprocess fallback: the pool has+/// no acknowledged per-job abort seam.+////// Whether inline `python` jobs should route through the pool.////// Python defaults **off**, and the asymmetry with Node is real rather than an@@ -19,6 +22,14 @@ use crate::config::{Config, RuntimePoolConfig};/// warm-worker memory saving.#[must_use]pub fn enabled(pool: &RuntimePoolConfig) -> bool {+ if crate::tools::timeout::ProcessCleanup::is_active()+ || crate::tools::timeout::CommandEnvironment::is_active()+ {+ tracing::debug!(+ "[python_exec] cancellable turn uses an owned subprocess instead of the pool"+ );+ return false;+ }pool.enabled && pool.python.is_enabled(false)}diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rsindex 72c3f01685..1c3a5f227f 100644--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/node_exec.rs@@ -294,7 +294,7 @@ impl NodeExecTool {cmd.env_clear();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended_path = if host_path.is_empty() {resolved.bin_dir.to_string_lossy().into_owned()@@ -304,7 +304,7 @@ impl NodeExecTool {cmd.env("PATH", &prepended_path);for var in SAFE_ENV_VARS {- if let Ok(val) = std::env::var(var) {+ if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {cmd.env(var, val);}}@@ -474,7 +474,7 @@ impl NodeExecTool {// process can resolve `node`, `npm`, `npx`, `corepack` consistently// with the unsandboxed path.let mut extra_env = std::collections::HashMap::new();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended = if host_path.is_empty() {bin_dir.to_string_lossy().into_owned()diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rsindex 479a4ffc50..215467b8cc 100644--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs@@ -285,7 +285,7 @@ impl NpmExecTool {cmd.env_clear();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended_path = if host_path.is_empty() {resolved.bin_dir.to_string_lossy().into_owned()@@ -295,7 +295,7 @@ impl NpmExecTool {cmd.env("PATH", &prepended_path);for var in SAFE_ENV_VARS {- if let Ok(val) = std::env::var(var) {+ if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {cmd.env(var, val);}}@@ -397,7 +397,7 @@ impl NpmExecTool {// (e.g. `npm run` spawning user scripts) resolve `node`/`npx`// consistently with the unsandboxed path.let mut extra_env = std::collections::HashMap::new();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended = if host_path.is_empty() {bin_dir.to_string_lossy().into_owned()diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rsindex 598f292d8c..6388006752 100644--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/python_exec.rs@@ -295,7 +295,7 @@ impl PythonExecTool {cmd.env_clear();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended_path = if host_path.is_empty() {resolved.bin_dir.to_string_lossy().into_owned()@@ -307,7 +307,7 @@ impl PythonExecTool {cmd.env("PYTHONUNBUFFERED", "1");for var in SAFE_ENV_VARS {- if let Ok(val) = std::env::var(var) {+ if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {cmd.env(var, val);}}@@ -442,7 +442,7 @@ impl PythonExecTool {}let mut extra_env = std::collections::HashMap::new();- let host_path = std::env::var("PATH").unwrap_or_default();+ let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();let sep = if cfg!(windows) { ";" } else { ":" };let prepended = if host_path.is_empty() {bin_dir.to_string_lossy().into_owned()diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex 0116805aaa..ed098cfb76 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -396,7 +396,7 @@ impl ShellTool {};cmd.env_clear();- for (var, val) in shell_child_env(|name| std::env::var_os(name)) {+ for (var, val) in shell_child_env(crate::tools::timeout::CommandEnvironment::var_os) {cmd.env(var, val);}diff --git a/crates/openhuman-core/src/tools/timeout/command_environment.rs b/crates/openhuman-core/src/tools/timeout/command_environment.rsnew file mode 100644index 0000000000..c787db920c--- /dev/null+++ b/crates/openhuman-core/src/tools/timeout/command_environment.rs@@ -0,0 +1,67 @@+//! Child-process environment carried by one dispatch task.++use std::{collections::BTreeMap, future::Future, sync::Arc};++tokio::task_local! { static ACTIVE: CommandEnvironment; }++/// A complete, turn-owned environment for builtin tool subprocesses.+/// This never mutates the host process environment. Host-spawned tasks must+/// explicitly inherit its scope. Interpreter pools cannot accept scoped work.+#[derive(Clone)]+pub struct CommandEnvironment(Arc<BTreeMap<String, String>>);++impl CommandEnvironment {+ /// Own the exact variables permitted in child processes.+ pub fn new(env: impl IntoIterator<Item = (String, String)>) -> Self {+ Self(Arc::new(env.into_iter().collect()))+ }+ /// Whether this task requires its own child environment.+ pub fn is_active() -> bool {+ ACTIVE.try_with(|_| ()).is_ok()+ }+ /// Run a future using this environment for builtin subprocesses.+ pub async fn scope<F: Future>(&self, future: F) -> F::Output {+ ACTIVE.scope(self.clone(), future).await+ }+ /// Read a functional child variable from the scoped map, falling back to+ /// the process only when no map was supplied.+ pub fn var_os(name: &str) -> Option<std::ffi::OsString> {+ ACTIVE+ .try_with(|environment| environment.0.get(name).map(Into::into))+ .unwrap_or_else(|_| std::env::var_os(name))+ }+ /// UTF-8 counterpart used by managed interpreter command builders.+ pub fn var(name: &str) -> Result<String, std::env::VarError> {+ ACTIVE+ .try_with(|environment| {+ environment+ .0+ .get(name)+ .cloned()+ .ok_or(std::env::VarError::NotPresent)+ })+ .unwrap_or_else(|_| std::env::var(name))+ }+ pub(super) fn apply(command: &mut tokio::process::Command) {+ let _ = ACTIVE.try_with(|environment| {+ // Explicit runtime/security additions (managed PATH, scratch TMP,+ // Git policy) remain authoritative over the base environment.+ let explicit: Vec<_> = command+ .as_std()+ .get_envs()+ .map(|(key, value)| (key.to_owned(), value.map(ToOwned::to_owned)))+ .collect();+ command.env_clear().envs(environment.0.iter());+ for (key, value) in explicit {+ match value {+ Some(value) => {+ command.env(key, value);+ }+ None => {+ command.env_remove(key);+ }+ }+ }+ });+ }+}diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rsindex 6144a7c2b5..ed1ca3d503 100644--- a/crates/openhuman-core/src/tools/timeout/mod.rs+++ b/crates/openhuman-core/src/tools/timeout/mod.rs@@ -18,6 +18,8 @@ use std::time::Duration;use tinyagents_harness::tool::ToolTimeoutSettings;use tinytools::ToolTimeout;+mod command_environment;+pub use command_environment::CommandEnvironment;mod process_cleanup;pub use process_cleanup::ProcessCleanup;@@ -243,62 +245,87 @@ pub async fn output_unbounded(.stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);+ CommandEnvironment::apply(cmd);own_process_group(cmd.as_std_mut());let child = cmd.spawn()?;- let pid = child.id();let reaped = process_cleanup::Reaped::register();let (cancel, cancellation) = tokio::sync::watch::channel(false);let waiter = tokio::spawn(async move {let _reaped = reaped;collect_command_output(child, cancellation).await});- let mut group = CommandGroup { pid, cancel };- let result = waiter.await.map_err(std::io::Error::other)?;- group.pid = None;- result+ let _cancel_on_drop = CancelOnDrop(cancel);+ waiter.await.map_err(std::io::Error::other)?}-struct CommandGroup {- pid: Option<u32>,- cancel: tokio::sync::watch::Sender<bool>,-}+// The caller signals only the owned waiter. It never retains a PID after+// that waiter reaps the child, so late future drops cannot kill a reused PID.+struct CancelOnDrop(tokio::sync::watch::Sender<bool>);-impl Drop for CommandGroup {+impl Drop for CancelOnDrop {fn drop(&mut self) {- if let Some(pid) = self.pid {+ self.0.send_replace(true);+ }+}++struct CommandGroup(Option<u32>);++impl CommandGroup {+ fn kill(&self) {+ if let Some(pid) = self.0 {kill_process_group(pid);- self.cancel.send_replace(true);}}}+impl Drop for CommandGroup {+ fn drop(&mut self) {+ self.kill();+ }+}+async fn collect_command_output(mut child: tokio::process::Child,mut cancellation: tokio::sync::watch::Receiver<bool>,) -> std::io::Result<std::process::Output> {use tokio::io::AsyncReadExt;+ let mut group = CommandGroup(child.id());let mut stdout = child.stdout.take().expect("command stdout is piped");let mut stderr = child.stderr.take().expect("command stderr is piped");let mut stdout_bytes = Vec::new();let mut stderr_bytes = Vec::new();- let wait = async {+ {+ let drain = async {+ tokio::try_join!(+ stdout.read_to_end(&mut stdout_bytes),+ stderr.read_to_end(&mut stderr_bytes),+ )+ };+ tokio::pin!(drain);tokio::select! {biased;_ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {- // Reap the direct child on every platform. On Unix the- // caller has also signalled the process group.- child.kill().await?;- child.wait().await+ // The leader has not been reaped, even if it already exited.+ // Its PID cannot be reused while signalling this group.+ group.kill();+ child.start_kill()?;+ drain.await?;}- result = child.wait() => result,+ result = &mut drain => { result?; }+ }+ }+ let status = tokio::select! {+ biased;+ _ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {+ group.kill();+ child.start_kill()?;+ child.wait().await?}+ result = child.wait() => result?,};- let (status, _, _) = tokio::try_join!(- wait,- stdout.read_to_end(&mut stdout_bytes),- stderr.read_to_end(&mut stderr_bytes),- )?;+ // No await between reaping and disarming. Only this waiter owns the PID.+ group.0 = None;Ok(std::process::Output {status,stdout: stdout_bytes,diff --git a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs b/crates/openhuman-core/src/tools/timeout/process_cleanup.rsindex 94535c0efc..471f484def 100644--- a/crates/openhuman-core/src/tools/timeout/process_cleanup.rs+++ b/crates/openhuman-core/src/tools/timeout/process_cleanup.rs@@ -16,6 +16,13 @@ tokio::task_local! {pub struct ProcessCleanup(Arc<Mutex<Vec<watch::Receiver<bool>>>>);impl ProcessCleanup {+ /// Whether the current task must acknowledge owned subprocess cleanup.+ /// Interpreter pools have no per-job cancellation acknowledgement and+ /// therefore cannot accept work from this scope.+ pub fn is_active() -> bool {+ ACTIVE.try_with(|_| ()).is_ok()+ }+/// Run a future with command waiters registered to this turn.pub async fn scope<T>(&self, future: impl Future<Output = T>) -> T {ACTIVE.scope(self.clone(), future).awaitdiff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.mdindex a1e18849c3..7e764f443d 100644--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@ -96,6 +96,12 @@ assert!(matches!(running.await?, Err(openhuman_embed::CoreError::TurnCancelled {```Cancellation is scoped to this turn, including while waiting for inference.+Turns with a cancellation handle use owned interpreter subprocesses rather+than the Node/Python pool, which has no acknowledged per-job abort API. This+trades warm-worker reuse for awaited cleanup; ordinary turns retain pooling.+The `meter` callback fires once on cancellation or a dropped send future,+with `None` when dispatch has not supplied usage yet.+Before send, cancellation prevents dispatch; after completion it is a no-op.On Unix, the built-in shell, Node, Python and npm commands kill their processgroup, including descendants. Other platforms stop the direct command. Host@@ -166,10 +172,28 @@ println!("{}", again.reply);# }```+Hooks can be supplied at three levels: `RuntimeBuilder::tool_hook` /+`post_turn_hook` for all agents, `AgentSpec::tool_hook` / `post_turn_hook`+for one agent, and `Turn::tool_hook` / `post_turn_hook` for one dispatch.+Tool callbacks run in that order; same-named scoped callbacks are additive.+`ToolHookContext` carries the agent/session identity when known, and `cwd`+follows the execution workspace descriptor (including `Turn::cwd`), falling+back to the embedding context's configured action root.+The agent and turn hooks are never installed in the global registry, so+concurrent workers and later turns do not pick up one another's callbacks.+Post-turn callbacks run asynchronously with an owned session snapshot.+Independently spawned tasks that build sessions must explicitly inherit+`openhuman_core::agent::hooks::HookScope` to carry scoped hooks.+`McpServer` and `AgentSpec::mcp` need the `mcp` feature; `skills_dir` needs`skills`. `Agent::run` always starts a new conversation. To continue one, passthe returned `session_id` to `Turn::session`.+Gateway attribution headers can be attached to `Route::header(name, value)`+and used with `Turn::route`, or with `Provider::routed(route)` on an agent.+They follow only that route's endpoint and are never saved to configuration,+sent to background providers, or included as values in `Route`'s `Debug`.+A `Turn` has more knobs than the example shows: `model` and `temperature`for one turn, `cwd` to root the file and shell tools somewhere else (use`openhuman_embed::absolute` for a relative path, since the core resolves a@@ -773,3 +797,36 @@ Attachments are shared by clones, always directly advertised, and update onlytheir managed system catalogue when a continuing conversation gains tools.See [agent attachment semantics and example](src/agent/README.md#attach-tools-to-an-existing-agent)for source identity, collision errors, policy composition, and runtime identity.++### Inline permission and usage policy++`AgentSpec::can_use_tool` and `Turn::can_use_tool` await a host callback before+executing each tool. The callback can wait for an approval UI and return+`ToolHookDecision::Proceed`, `Deny`, or `ProceedWith`. It owns that wait;+returning `Ask` denies execution. These callbacks add to existing tool policies,+and a turn callback cannot override an agent denial.++`AgentSpec::stop_hook` and `Turn::stop_hook` receive cumulative usage after each+completed model call. Return `StopDecision::Continue` to observe usage, or+`Stop` to prevent subsequent calls. Completed tool rounds may still execute;+this is an after-call budget boundary, so hosts must refuse an already exhausted+budget before sending a turn. Provider-reported charges remain authoritative,+including known zero; missing charges remain unknown unless pricing is known.+A policy stop uses a deterministic partial summary rather than spending on+final-answer repair calls.++### Per-turn tools and subprocess environment++`Turn::tools` replaces this turn's host tool belt, including attached sources.+An empty belt revokes host tools; the next turn returns to the agent's belt.+Builtin tools still follow the agent definition. This supplies dynamic tools for+in-process hosts; statically declared MCP servers retain their creation-time+configuration.++`Turn::tool_env` supplies the base environment of owned builtin subprocesses.+Variables absent from it are not inherited from the daemon. The builtin command+builders retain their own security/runtime additions, including Git restrictions,+managed interpreter paths and scratch directories. Scoped turns bypass Node and+Python pools, which cannot acknowledge per-job cancellation or swap a job's+process environment. A host tool that spawns a separate Tokio task must explicitly+carry the command environment and cleanup scopes into that task.diff --git a/crates/openhuman-embed/examples/linux_fleet.rs b/crates/openhuman-embed/examples/linux_fleet.rsnew file mode 100644index 0000000000..47008e6c1f--- /dev/null+++ b/crates/openhuman-embed/examples/linux_fleet.rs@@ -0,0 +1,128 @@+//! Reproducible Linux RSS and cold-turn measurement of runtime-owned agents.+//! Run the release binary in a fresh cgroup; inference is a loopback HTTP mock.++#![recursion_limit = "512"]++use std::time::Instant;++use openhuman_embed::{+ Access, AgentDefinitionSpec, AgentSpec, Provider, Runtime, ToolScopeSpec, Workspace,+};+use serde_json::json;+use wiremock::{Mock, MockServer, ResponseTemplate};++fn rss_kib() -> anyhow::Result<u64> {+ let status = std::fs::read_to_string("/proc/self/status")?;+ let line = status+ .lines()+ .find(|line| line.starts_with("VmRSS:"))+ .ok_or_else(|| anyhow::anyhow!("VmRSS missing"))?;+ Ok(line+ .split_whitespace()+ .nth(1)+ .ok_or_else(|| anyhow::anyhow!("VmRSS value missing"))?+ .parse()?)+}++fn main() -> anyhow::Result<()> {+ let count: usize = std::env::args()+ .nth(1)+ .unwrap_or_else(|| "100".into())+ .parse()?;+ anyhow::ensure!(count > 0, "agent count must be positive");+ openhuman_embed::process::tokio_runtime_builder()+ .worker_threads(2)+ .build()?+ .block_on(measure(count))+}++async fn measure(count: usize) -> anyhow::Result<()> {+ let mock = MockServer::start().await;+ Mock::given(wiremock::matchers::method("POST"))+ .and(wiremock::matchers::path("/v1/chat/completions"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "id":"linux-fleet", "object":"chat.completion", "created":1700000000,+ "model":"fixture", "choices":[{"index":0,"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}],+ "usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}+ })))+ .mount(&mock).await;+ let mut config = openhuman_embed::RuntimeConfig::default();+ config.local_ai.runtime_enabled = false;+ config.runtime_python.enabled = false;+ config.memory.conversations.enabled = false;+ config.agent.session_dual_write = false;+ config.agent.session_shadow_reads = false;+ config.default_temperature = 0.0;+ let before_boot = rss_kib()?;+ let boot_start = Instant::now();+ let runtime = Runtime::builder()+ .config(config)+ .workspace(Workspace::Ephemeral)+ .backend_url(mock.uri())+ .max_agents(count)+ .build()+ .await?;+ let boot_ms = boot_start.elapsed().as_secs_f64() * 1000.0;+ let baseline = rss_kib()?;+ let action = tempfile::tempdir()?;+ let agents = (0..count)+ .map(|index| {+ runtime.agent(+ AgentSpec::new(format!("linux-worker-{index}"))+ .provider(Provider::openai_compatible(+ format!("{}/v1", mock.uri()),+ "fixture",+ ))+ .model("fixture")+ .access(Access::full())+ .action_dir(action.path())+ .definition(+ AgentDefinitionSpec::new()+ .tools(ToolScopeSpec::Named(vec!["shell".into()])),+ ),+ )+ })+ .collect::<Result<Vec<_>, _>>()?;+ let registered = rss_kib()?;+ let cold_start = Instant::now();+ let first = agents[0]+ .turn("Say done.")+ .session("cold-session")+ .send()+ .await?;+ anyhow::ensure!(first.reply == "done", "unexpected cold reply");+ let cold_ms = cold_start.elapsed().as_secs_f64() * 1000.0;+ let mut tasks = tokio::task::JoinSet::new();+ let fleet_start = Instant::now();+ for (index, agent) in agents.iter().cloned().enumerate() {+ tasks.spawn(async move {+ let start = Instant::now();+ let outcome = agent+ .turn("Say done.")+ .session(format!("fleet-session-{index}"))+ .send()+ .await?;+ anyhow::ensure!(outcome.reply == "done", "unexpected fleet reply");+ Ok::<_, anyhow::Error>(start.elapsed().as_secs_f64() * 1000.0)+ });+ }+ let mut latencies = Vec::with_capacity(count);+ while let Some(result) = tasks.join_next().await {+ latencies.push(result??);+ }+ let elapsed_ms = fleet_start.elapsed().as_secs_f64() * 1000.0;+ latencies.sort_by(f64::total_cmp);+ let completed = rss_kib()?;+ let percentile = |p: f64| latencies[((count - 1) as f64 * p).round() as usize];+ println!(+ "{}",+ json!({+ "agents":count,"worker_threads":2,"inference":"loopback-http-mock","tool_scope":["shell"],+ "before_boot_rss_kib":before_boot,"runtime_rss_kib":baseline,"registered_rss_kib":registered,+ "after_turns_rss_kib":completed,"marginal_after_turns_mib":completed.saturating_sub(baseline) as f64 / count as f64 / 1024.0,+ "boot_ms":boot_ms,"cold_turn_ms":cold_ms,"fleet_elapsed_ms":elapsed_ms,+ "turn_p50_ms":percentile(0.5),"turn_p95_ms":percentile(0.95),"turn_p99_ms":percentile(0.99)+ })+ );+ Ok(())+}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex bda026f01a..aa937daa4a 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -202,6 +202,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnSome(route.base_url.clone()),Some(route.api_key.clone()),)+ .map(|scoped| scoped.with_headers(route.headers.clone()))});let overlay = ContextOverlay {config: context_config,@@ -249,6 +250,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnaccess,layout,host_tools: parts.host_tools,+ hooks: parts.hooks,lifecycle: super::lifecycle::Lifecycle::new(),host_only,})diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 94ac25e200..46e4078bd0 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -117,6 +117,7 @@ pub(crate) struct AgentInner {/// The agent's own in-process tools, rebuilt per turn. See/// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,+ pub(crate) hooks: openhuman_core::agent::hooks::HookScope,pub(crate) lifecycle: lifecycle::Lifecycle,/// Built from [`ToolScopeSpec::HostOnly`]: every turn's session is built/// from the host tools alone.@@ -206,7 +207,8 @@ impl Agent {/// alone.pub fn turn(&self, message: impl Into<String>) -> Turn {let mut turn = Turn::new(TurnTarget::Agent(Arc::clone(&self.inner)), message)- .with_agent_id(&self.inner.id);+ .with_agent_id(&self.inner.id)+ .with_hooks(self.inner.hooks.clone());if let Some(route) = self.inner.provider.route() {turn = turn.route(route.clone());}diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rsindex edc1d3c512..86569485d5 100644--- a/crates/openhuman-embed/src/agent/spec.rs+++ b/crates/openhuman-embed/src/agent/spec.rs@@ -51,6 +51,7 @@ pub struct AgentSpec {composio: Option<ComposioHostCredential>,config_fn: Option<ConfigEdit>,host_tools: Option<openhuman_core::agent::HostTools>,+ hooks: openhuman_core::agent::hooks::HookScope,memory: Option<MemoryBinding>,subagents: Vec<(String, AgentDefinitionSpec)>,}@@ -125,6 +126,7 @@ impl AgentSpec {composio: None,config_fn: None,host_tools: None,+ hooks: Default::default(),memory: None,subagents: Vec::new(),}@@ -271,6 +273,47 @@ impl AgentSpec {self}+ /// Add a tool callback to every turn of this agent alone.+ ///+ /// Runtime callbacks run first, then agent callbacks, then callbacks added+ /// on the turn. Same-named callbacks are additive, never replaced globally.+ pub fn tool_hook(mut self, hook: std::sync::Arc<dyn crate::seams::ToolHook>) -> Self {+ self.hooks.push_tool(hook);+ self+ }++ /// Await the host's permission decision before each tool executes.+ /// The callback may wait for UI approval, then return `Proceed`, `Deny`,+ /// or `ProceedWith`. Returning `Ask` denies the call; this callback itself+ /// owns the approval wait. Static tool/security restrictions still apply.+ /// Agent and turn callbacks are additive: a denial cannot be overridden.+ pub fn can_use_tool<F>(self, callback: F) -> Self+ where+ F: for<'a> Fn(&'a crate::seams::ToolHookContext) -> crate::PermissionFuture<'a>+ + Send+ + Sync+ + 'static,+ {+ self.tool_hook(std::sync::Arc::new(crate::permission::PermissionHook(+ callback,+ )))+ }++ /// Observe cumulative usage after each model call or vote to stop before+ /// the next call. Return `StopDecision::Continue` for observation alone;+ /// a budget policy can return `StopDecision::Stop`. Scoped to this agent; no runtime-global policy is replaced.+ pub fn stop_hook(mut self, hook: std::sync::Arc<dyn crate::seams::StopHook>) -> Self {+ self.hooks.push_stop(hook);+ self+ }++ /// Add a completed-turn callback to this agent alone. Runs asynchronously+ /// with an owned snapshot, after the runtime's callbacks.+ pub fn post_turn_hook(mut self, hook: std::sync::Arc<dyn crate::seams::PostTurnHook>) -> Self {+ self.hooks.push_post_turn(hook);+ self+ }+/// Arbitrary edits to the agent's config, applied last.////// The escape hatch for the config fields the spec does not model — not@@ -375,6 +418,7 @@ impl AgentSpec {composio: self.composio,config_fn: self.config_fn,host_tools: self.host_tools,+ hooks: self.hooks,memory: self.memory,subagents: self.subagents,}@@ -401,6 +445,7 @@ pub(crate) struct AgentSpecParts {pub(crate) composio: Option<ComposioHostCredential>,pub(crate) config_fn: Option<ConfigEdit>,pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,+ pub(crate) hooks: openhuman_core::agent::hooks::HookScope,pub(crate) memory: Option<MemoryBinding>,pub(crate) subagents: Vec<(String, AgentDefinitionSpec)>,}diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rsindex 38450dbb24..f10008f6e6 100644--- a/crates/openhuman-embed/src/complete.rs+++ b/crates/openhuman-embed/src/complete.rs@@ -413,8 +413,8 @@ impl Completer {/// A completer for `route`, with no timeout and no observer.pub fn new(route: Route) -> Self {Self {+ headers: route.headers.clone(),route,- headers: Vec::new(),timeout: None,observer: None,}diff --git a/crates/openhuman-embed/src/harness/provider.rs b/crates/openhuman-embed/src/harness/provider.rsindex 54c1d537af..283ca9ee32 100644--- a/crates/openhuman-embed/src/harness/provider.rs+++ b/crates/openhuman-embed/src/harness/provider.rs@@ -35,8 +35,13 @@ impl Provider {/// Both halves are required: the core ignores a route with only one, and/// taking them together here means a partial route cannot be expressed.pub fn openai_compatible(base_url: impl Into<String>, api_key: impl Into<String>) -> Self {+ Self::routed(Route::openai_compatible(base_url, api_key))+ }++ /// Use a route including its gateway attribution headers.+ pub fn routed(route: Route) -> Self {Self {- route: Some(Route::openai_compatible(base_url, api_key)),+ route: Some(route),model: None,}}diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 7eb65983ad..fb8466fe45 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -72,7 +72,7 @@ pub use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};// would build tools of a different, incompatible type.pub use openhuman_core::agent::tinyagents::host::LastTurnUsage;pub use openhuman_core::agent::{HostTools, HostTurnTools, TurnContext};-pub use openhuman_core::tools::{Tool, ToolExposure};+pub use openhuman_core::tools::{Tool, ToolExposure, ToolResult};pub use openhuman_core::{CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet, TokenSource,};@@ -113,12 +113,15 @@ pub mod identity;pub mod memory;#[cfg(feature = "modules")]pub mod modules;+mod permission;+pub use permission::PermissionFuture;pub mod process;#[cfg(feature = "channels")]pub mod profiles;mod runtime;mod turn;mod turn_cancellation;+mod turn_meter;/// Core internals for `openhuman-tinyhumans` and `openhuman-rpc` only; see/// the module docs. Not part of the host-facing API.@@ -179,6 +182,9 @@ pub use runtime::{pub mod seams {pub use openhuman_core::agent::hooks::{PostTurnHook, ToolHook};pub use openhuman_core::agent::hooks::{ToolHookContext, ToolHookDecision, TurnContext};+ pub use openhuman_core::agent::stop_hooks::{+ BudgetStopHook, StopDecision, StopHook, TurnState,+ };pub use openhuman_core::core::all::{ControllerExtension, DomainGroup};pub use openhuman_core::core::server_launcher::{HostBoot, ServeRequest, ServerLauncher};pub use openhuman_core::security::SecurityPolicy;diff --git a/crates/openhuman-embed/src/permission.rs b/crates/openhuman-embed/src/permission.rsnew file mode 100644index 0000000000..bd55bf0d0b--- /dev/null+++ b/crates/openhuman-embed/src/permission.rs@@ -0,0 +1,27 @@+//! Inline host approval carried by the agent/turn tool-hook scope.++use crate::seams::{ToolHook, ToolHookContext, ToolHookDecision};+/// A sendable asynchronous permission decision borrowing its tool context.+pub type PermissionFuture<'a> =+ std::pin::Pin<Box<dyn std::future::Future<Output = ToolHookDecision> + Send + 'a>>;++pub(crate) struct PermissionHook<F>(pub(crate) F);++#[async_trait::async_trait]+impl<F> ToolHook for PermissionHook<F>+where+ F: for<'a> Fn(&'a ToolHookContext) -> PermissionFuture<'a> + Send + Sync,+{+ fn name(&self) -> &str {+ "embed.can_use_tool"+ }+ async fn before_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> {+ Ok(())+ }+ async fn after_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> {+ Ok(())+ }+ async fn before_tool_decision(&self, context: &ToolHookContext) -> ToolHookDecision {+ (self.0)(context).await+ }+}diff --git a/crates/openhuman-embed/src/runtime/host_agents.rs b/crates/openhuman-embed/src/runtime/host_agents.rsindex fd631dab76..2546c2d727 100644--- a/crates/openhuman-embed/src/runtime/host_agents.rs+++ b/crates/openhuman-embed/src/runtime/host_agents.rs@@ -52,7 +52,9 @@ impl AgentInner {if let Some(route) = openhuman_core::config::schema::EphemeralRoute::from_params(Some(route.base_url.clone()),Some(route.api_key.clone()),- ) {+ )+ .map(|scoped| scoped.with_headers(route.headers.clone()))+ {openhuman_core::config::schema::ephemeral_route::apply(&mut config, route);}}@@ -61,6 +63,7 @@ impl AgentInner {config,host_tools: self.composed_host_tools(),context: Arc::clone(&self.ctx),+ hooks: self.hooks.clone(),})}}diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 5400b3e760..3ef4cfdb1d 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -71,6 +71,8 @@ pub struct Route {pub base_url: String,/// The bearer presented to `base_url`.pub api_key: String,+ /// Headers sent only to this route, never persisted or copied to other providers.+ pub headers: Vec<(String, String)>,}impl std::fmt::Debug for Route {@@ -82,6 +84,7 @@ impl std::fmt::Debug for Route {f.debug_struct("Route").field("base_url", &sanitize_url_for_display(&self.base_url)).field("api_key", &"<redacted>")+ .field("headers", &self.headers.len()).finish()}}@@ -139,8 +142,15 @@ impl Route {Self {base_url: base_url.into(),api_key: api_key.into(),+ headers: Vec::new(),}}++ /// Add a gateway attribution header to this endpoint's requests only.+ pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {+ self.headers.push((name.into(), value.into()));+ self+ }}/// Wire params for [`AGENT_CHAT`].@@ -173,6 +183,9 @@ pub struct TurnRequest {/// Bearer half of the per-call route. Paired with `inference_url`.#[serde(skip_serializing_if = "Option::is_none")]pub api_key: Option<String>,+ /// Custom headers for the per-call route. Ignored when no route is supplied.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub inference_headers: Vec<(String, String)>,/// The agent definition the turn runs as. Set by/// [`Agent::turn`](crate::Agent::turn); absent runs the orchestrator.#[serde(skip_serializing_if = "Option::is_none")]@@ -190,6 +203,7 @@ impl TurnRequest {cwd: None,inference_url: None,api_key: None,+ inference_headers: Vec::new(),agent_id: None,}}@@ -259,6 +273,9 @@ pub struct Turn {max_tokens: Option<u32>,untrusted_input: bool,cancellation: Option<crate::TurnCancellation>,+ hooks: openhuman_core::agent::hooks::HookScope,+ tools: Option<openhuman_core::agent::HostTools>,+ tool_env: Option<openhuman_core::tools::timeout::CommandEnvironment>,}impl Turn {@@ -275,6 +292,9 @@ impl Turn {max_tokens: None,untrusted_input: false,cancellation: None,+ hooks: Default::default(),+ tools: None,+ tool_env: None,}}@@ -283,6 +303,75 @@ impl Turn {self}+ pub(crate) fn with_hooks(mut self, hooks: openhuman_core::agent::hooks::HookScope) -> Self {+ self.hooks = hooks;+ self+ }++ /// Add a tool callback for this turn only, after runtime and agent hooks.+ /// Does not change the agent or any other concurrent turn.+ pub fn tool_hook(mut self, hook: Arc<dyn crate::seams::ToolHook>) -> Self {+ self.hooks.push_tool(hook);+ self+ }++ /// Replace this turn's host tools, including attached sources. An empty+ /// belt revokes them. Builtin tools remain governed by the agent definition;+ /// the agent's original host tools return on its next turn.+ pub fn tools(+ mut self,+ factory: impl for<'a> Fn(+ openhuman_core::agent::TurnContext<'a>,+ ) -> openhuman_core::agent::HostTurnTools+ + Send+ + Sync+ + 'static,+ ) -> Self {+ self.tools = Some(Arc::new(factory));+ self+ }++ /// Replace the environment of owned builtin tool subprocesses for this+ /// turn. Variables absent from this map are not inherited from the daemon.+ /// Interpreter pools are bypassed so a pooled process cannot carry another+ /// turn's environment. Independently spawned host tasks must carry the scope.+ pub fn tool_env(mut self, env: impl IntoIterator<Item = (String, String)>) -> Self {+ self.tool_env = Some(openhuman_core::tools::timeout::CommandEnvironment::new(env));+ self+ }++ /// Await the host's permission decision before each tool executes.+ /// The callback may wait for UI approval, then return `Proceed`, `Deny`,+ /// or `ProceedWith`. Returning `Ask` denies the call; this callback itself+ /// owns the approval wait. Static tool/security restrictions still apply.+ /// Agent and turn callbacks are additive: a denial cannot be overridden.+ pub fn can_use_tool<F>(self, callback: F) -> Self+ where+ F: for<'a> Fn(&'a crate::seams::ToolHookContext) -> crate::PermissionFuture<'a>+ + Send+ + Sync+ + 'static,+ {+ self.tool_hook(std::sync::Arc::new(crate::permission::PermissionHook(+ callback,+ )))+ }++ /// Observe cumulative usage after each model call or vote to stop before+ /// the next call. Return `StopDecision::Continue` for observation alone;+ /// a budget policy can return `StopDecision::Stop`. Scoped to this turn; no runtime-global policy is replaced.+ pub fn stop_hook(mut self, hook: std::sync::Arc<dyn crate::seams::StopHook>) -> Self {+ self.hooks.push_stop(hook);+ self+ }++ /// Add a completed-turn callback for this turn only. The callback runs+ /// asynchronously with an owned snapshot after the turn completes.+ pub fn post_turn_hook(mut self, hook: Arc<dyn crate::seams::PostTurnHook>) -> Self {+ self.hooks.push_post_turn(hook);+ self+ }+/// Continue an existing conversation. Without this a fresh session id is/// minted and returned in [`TurnOutcome::session_id`].pub fn session(mut self, session_id: impl Into<String>) -> Self {@@ -434,6 +523,7 @@ impl Turn {pub fn route(mut self, route: Route) -> Self {self.request.inference_url = Some(route.base_url);self.request.api_key = Some(route.api_key);+ self.request.inference_headers = route.headers;self}@@ -476,20 +566,47 @@ impl Turn {/// that is a build/composition fact, not a failure, and a host should hide/// the surface rather than report an error.pub async fn send(mut self) -> Result<TurnOutcome, CoreError> {- let Some(cancellation) = self.cancellation.take() else {- return self.send_inner().await;+ let hooks = std::mem::take(&mut self.hooks);+ let environment = self.tool_env.take();+ let fresh_tools = self.tools.is_some();+ let dispatch = hooks.scope(Box::pin(self.send_with_cancellation()));+ let dispatch = async move {+ if fresh_tools {+ openhuman_core::agent::tool_snapshot_scope::with_fresh_snapshot(dispatch).await+ } else {+ dispatch.await+ }+ };+ match environment {+ Some(environment) => environment.scope(dispatch).await,+ None => dispatch.await,+ }+ }++ async fn send_with_cancellation(mut self) -> Result<TurnOutcome, CoreError> {+ let session_id = self+ .session_id+ .take()+ .filter(|id| !id.trim().is_empty())+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));+ self.request.thread_id = Some(session_id.clone());+ // Drop the meter before publishing cancellation's finished phase.+ let cancellation = self.cancellation.take();+ let _guard = cancellation.as_ref().map(crate::TurnCancellation::enter);+ let meter = crate::turn_meter::TurnMeter::new(self.meter.take());+ let Some(cancellation) = cancellation else {+ return self.send_inner(&meter.usage).await;};- let _guard = cancellation.enter();let outcome = cancellation.cleanup().scope(async {tokio::select! {biased;_ = cancellation.cancelled() => {- log::debug!("[embed][agent] turn cancelled");+ log::debug!("[embed][agent] turn_cancelled session={session_id} method={AGENT_CHAT}");Err(CoreError::TurnCancelled { method: AGENT_CHAT })}- outcome = Box::pin(self.send_inner()) => outcome,+ outcome = Box::pin(self.send_inner(&meter.usage)) => outcome,}}).await;@@ -507,17 +624,12 @@ impl Turn {.clone()}- async fn send_inner(mut self) -> Result<TurnOutcome, CoreError> {- // The core neither mints nor returns a session id, so continuing a- // conversation would otherwise be impossible without the caller- // inventing an id scheme — which every embedder has then done- // differently. Mint one here and hand it back.+ async fn send_inner(mut self, usage: &UsageSink) -> Result<TurnOutcome, CoreError> {let session_id = self- .session_id- .take()- .filter(|id| !id.trim().is_empty())- .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));- self.request.thread_id = Some(session_id.clone());+ .request+ .thread_id+ .clone()+ .expect("send assigned a session id");log::debug!("[embed][agent] turn session={session_id} model={:?} routed={} cwd_set={}",@@ -552,11 +664,6 @@ impl Turn {}}- // Filled by the turn itself, before any error is raised, so a failed- // turn is still metered. Read back below whether the dispatch returned- // a reply or an error.- let usage: UsageSink = std::sync::Mutex::new(None);- let meter = self.meter.take();let wants_json = self.response_format.as_ref()@@ -572,8 +679,9 @@ impl Turn {},),untrusted_input: self.untrusted_input,+ tools: self.tools.take(),};- let dispatch = dispatch(self.target, self.request, self.seed.take(), &usage, options);+ let dispatch = dispatch(self.target, self.request, self.seed.take(), usage, options);let reply = match (self.origin, self.progress) {(Some(origin), Some(sink)) => {@@ -612,17 +720,6 @@ impl Turn {log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");});- // Before the `?`. A turn that errored still spent what it spent, and- // this is the only place both the sink and a failing result are in- // hand -- `TurnOutcome` below is never built on that path.- if let Some(meter) = meter {- meter(- usage- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .clone(),- );- }let (reply, report) = reply?;let structured = if wants_json {serde_json::from_str(reply.trim()).ok()@@ -643,8 +740,9 @@ impl Turn {reply,session_id,usage: usage- .into_inner()- .unwrap_or_else(std::sync::PoisonError::into_inner),+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone(),structured,finish_reason: report.finish_reason,answered_model: report.answered_model,@@ -666,6 +764,12 @@ impl Turn {let host_only = match &self.target {TurnTarget::Agent(agent) => agent.host_only,TurnTarget::Runtime(_) => {+ if self.tools.is_some() {+ return refuse(+ "per-turn host tools need a runtime-owned Agent",+ "turn_tools_unsupported",+ );+ }if self.response_format.is_some() || self.max_tokens.is_some() {return refuse("response_format and max_tokens need a runtime-owned Agent",@@ -695,7 +799,7 @@ impl Turn {/// DomainSet gate itself before touching the core.use openhuman_core::agent::tinyagents::host::LastTurnUsage;-type UsageSink = std::sync::Mutex<Option<LastTurnUsage>>;+use crate::turn_meter::UsageSink;use openhuman_core::agent::tinyagents::response_shape::{FinalResponse, ResponseShapeScope};@@ -711,6 +815,7 @@ mod futures_box {/// What only an agent target can honour, already validated by/// [`Turn::validate_turn_options`].struct AgentTurnOptions {+ tools: Option<openhuman_core::agent::HostTools>,shape: std::sync::Arc<ResponseShapeScope>,untrusted_input: bool,}@@ -769,8 +874,9 @@ async fn dispatch(let route = openhuman_core::config::schema::EphemeralRoute::from_params(request.inference_url,request.api_key,- );- let host = inner.composed_host_tools();+ )+ .map(|route| route.with_headers(request.inference_headers));+ let host = options.tools.or_else(|| inner.composed_host_tools());let target = AgentChatTarget::Definition {definition: &inner.definition,host: host.as_ref(),diff --git a/crates/openhuman-embed/src/turn_meter.rs b/crates/openhuman-embed/src/turn_meter.rsnew file mode 100644index 0000000000..495ecf6788--- /dev/null+++ b/crates/openhuman-embed/src/turn_meter.rs@@ -0,0 +1,32 @@+//! A turn's usage callback survives dispatch errors, cancellation and dropping.++use openhuman_core::agent::tinyagents::host::LastTurnUsage;++pub(crate) type UsageSink = std::sync::Mutex<Option<LastTurnUsage>>;++pub(crate) struct TurnMeter {+ pub(crate) usage: UsageSink,+ callback: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,+}++impl TurnMeter {+ pub(crate) fn new(callback: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>) -> Self {+ Self {+ usage: std::sync::Mutex::new(None),+ callback,+ }+ }+}++impl Drop for TurnMeter {+ fn drop(&mut self) {+ if let Some(callback) = self.callback.take() {+ callback(+ self.usage+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone(),+ );+ }+ }+}diff --git a/crates/openhuman-embed/src/turn_tests.rs b/crates/openhuman-embed/src/turn_tests.rsindex 9f9edc49d6..7db25bcedb 100644--- a/crates/openhuman-embed/src/turn_tests.rs+++ b/crates/openhuman-embed/src/turn_tests.rs@@ -31,6 +31,7 @@ fn turn_request_field_names_match_the_controller() {cwd: Some("/tmp".into()),inference_url: Some("https://example.invalid/v1".into()),api_key: Some("k".into()),+ inference_headers: vec![("x-worker".into(), "a".into())],agent_id: Some("a".into()),};@@ -203,13 +204,14 @@ fn the_controller_declares_nowhere_for_a_seed_to_travel() {// `context` or `transcript` could carry history just as well, and a// heuristic that guesses at names would pass it silently. Anything new// fails here until someone decides whether a seed could ride it.- const KNOWN: [&str; 8] = [+ const KNOWN: [&str; 9] = ["message","model_override","temperature","thread_id","cwd","inference_url",+ "inference_headers","api_key","agent_id",];diff --git a/crates/openhuman-embed/tests/README.md b/crates/openhuman-embed/tests/README.mdindex 1c58a5bad6..2086d80218 100644--- a/crates/openhuman-embed/tests/README.md+++ b/crates/openhuman-embed/tests/README.md@@ -40,6 +40,14 @@ recorded on the wrong server.| [`turn_cancellation.rs`](turn_cancellation.rs) | Cancellation before send, during inference and during a builtin shell command; repeated requests and agent reuse. || [`process_cancellation.rs`](process_cancellation.rs) | On Linux, dropping a command future kills its shell descendants. |+| `inline_permissions.rs` | An inline UI decision precedes execution; concurrent agents and one-turn denials stay isolated. |+| `usage_hooks.rs` | Per-agent stop policy and per-turn cumulative usage observation, with provider charges and no extra calls after a stop. |+| [`turn_tools.rs`](turn_tools.rs) | One-turn belt replacement/revocation, resumed-session schemas and independent concurrent workers. |+| [`tool_environment.rs`](tool_environment.rs) | Overlapping child environments exclude inherited variables and stay within their own scopes. |+| [`scoped_hooks.rs`](scoped_hooks.rs) | Same-named runtime, agent and turn callbacks remain additive and isolated during concurrent turns, resumed sessions and reuse of a removed agent id. |+| [`route_headers.rs`](route_headers.rs) | Attribution headers and bearer follow only the per-turn route, without reaching other agents, later turns or backend calls. |+| [`tool_hook_context.rs`](tool_hook_context.rs) | Hook agent/session identities and cwd agree with builtin shell execution on an overridden and a default working root. |+## Running[`runtime_agents.rs`](runtime_agents.rs) gates its skills and MCP assertions on the `skills` anddiff --git a/crates/openhuman-embed/tests/inline_permissions.rs b/crates/openhuman-embed/tests/inline_permissions.rsnew file mode 100644index 0000000000..bcfcff253a--- /dev/null+++ b/crates/openhuman-embed/tests/inline_permissions.rs@@ -0,0 +1,168 @@+//! A host can await its own approval UI inline without polling the core.++mod common;++use common::{+ chat_completion, offline_config, route, runtime, scripted_provider, stub_backend,+ tool_call_completion,+};+use openhuman_embed::seams::{ToolHookContext, ToolHookDecision};+use openhuman_embed::{+ AgentDefinitionSpec, AgentSpec, HostTurnTools, Runtime, Tool, ToolScopeSpec, Workspace,+};+use serde_json::{json, Value};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++struct Probe(Arc<AtomicUsize>);+#[async_trait::async_trait]+impl Tool for Probe {+ fn name(&self) -> &str {+ "probe"+ }+ fn description(&self) -> &str {+ "Perform a host operation"+ }+ fn parameters_schema(&self) -> Value {+ json!({"type":"object","properties":{}})+ }+ async fn execute(&self, _: Value) -> anyhow::Result<openhuman_core::tools::ToolResult> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(openhuman_core::tools::ToolResult::success("ran"))+ }+}+#[test]+fn inline_approval_waits_for_the_host_and_isolated_turn_policies_can_only_narrow() {+ runtime().block_on(async { tokio::spawn(scenario()).await.unwrap() });+}+async fn scenario() {+ let backend = stub_backend().await;+ let provider = scripted_provider(+ vec![+ tool_call_completion("probe", "{}"),+ tool_call_completion("probe", "{}"),+ tool_call_completion("probe", "{}"),+ chat_completion("done"),+ tool_call_completion("probe", "{}"),+ tool_call_completion("probe", "{}"),+ ],+ "done",+ )+ .await;+ let other_provider =+ scripted_provider(vec![tool_call_completion("probe", "{}")], "other done").await;+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let calls = Arc::new(AtomicUsize::new(0));+ let other_calls = Arc::new(AtomicUsize::new(0));+ let spec = |id, provider: &wiremock::MockServer, calls: Arc<AtomicUsize>| {+ AgentSpec::new(id)+ .provider(route(provider, "fixture"))+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("Use probe then answer")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(move |_| HostTurnTools::advertised(vec![Box::new(Probe(calls.clone()))]))+ };+ let (requests, mut received) = tokio::sync::mpsc::unbounded_channel::<(+ ToolHookContext,+ tokio::sync::oneshot::Sender<ToolHookDecision>,+ )>();+ let agent = runtime+ .agent(+ spec("interactive", &provider, calls.clone()).can_use_tool(move |context| {+ let (answer, decision) = tokio::sync::oneshot::channel();+ requests.send((context.clone(), answer)).unwrap();+ Box::pin(async move {+ decision+ .await+ .unwrap_or_else(|_| ToolHookDecision::Deny("UI closed".into()))+ })+ }),+ )+ .unwrap();+ let other = runtime+ .agent(+ spec("other", &other_provider, other_calls.clone())+ .can_use_tool(|_| Box::pin(async { ToolHookDecision::Proceed })),+ )+ .unwrap();+ let first = tokio::spawn(agent.turn("needs approval").send());+ let (context, answer) =+ tokio::time::timeout(std::time::Duration::from_secs(5), received.recv())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(context.agent_id.as_deref(), Some("interactive"));+ assert_eq!(context.tool_name, "probe");+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 0,+ "tool ran before the UI answered"+ );+ other.run("independent worker").await.unwrap();+ assert_eq!(other_calls.load(Ordering::SeqCst), 1);+ answer+ .send(ToolHookDecision::Deny("human refused".into()))+ .unwrap();+ assert!(+ first.await.unwrap().is_err(),+ "denied call unexpectedly succeeded"+ );+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ let second = tokio::spawn(+ agent+ .turn("turn-specific refusal")+ .can_use_tool(|_| {+ Box::pin(async { ToolHookDecision::Deny("turn narrowed authority".into()) })+ })+ .send(),+ );+ let (_, answer) = received.recv().await.unwrap();+ answer.send(ToolHookDecision::Proceed).unwrap();+ assert!(+ second.await.unwrap().is_err(),+ "turn denial unexpectedly succeeded"+ );+ assert_eq!(calls.load(Ordering::SeqCst), 0, "turn policy was skipped");+ let third = tokio::spawn(agent.turn("next turn").send());+ let (_, answer) = received.recv().await.unwrap();+ answer.send(ToolHookDecision::Proceed).unwrap();+ third.await.unwrap().unwrap();+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 1,+ "previous turn's refusal leaked"+ );+ let mut pending = agent.turn("cancel while the UI waits");+ let cancellation = pending.cancellation_handle();+ let cancelled = tokio::spawn(pending.send());+ let (_, answer) = received.recv().await.unwrap();+ cancellation.cancel().await;+ assert!(matches!(+ cancelled.await.unwrap(),+ Err(openhuman_embed::CoreError::TurnCancelled { .. })+ ));+ assert!(+ answer.is_closed(),+ "cancelled turn left an approval receiver alive"+ );+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ let closed_ui = tokio::spawn(agent.turn("closed UI refuses").send());+ let (_, answer) = received.recv().await.unwrap();+ drop(answer);+ assert!(closed_ui.await.unwrap().is_err());+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 1,+ "closing the UI granted permission"+ );+}diff --git a/crates/openhuman-embed/tests/process_cancellation.rs b/crates/openhuman-embed/tests/process_cancellation.rsindex f353454cfa..1670bb9ec4 100644--- a/crates/openhuman-embed/tests/process_cancellation.rs+++ b/crates/openhuman-embed/tests/process_cancellation.rs@@ -121,3 +121,67 @@ async fn deadline_kills_and_reaps_a_command() {.await.unwrap();}++#[tokio::test]+async fn exited_group_leader_is_not_reaped_until_its_descendants_close_the_pipes() {+ let scratch = tempfile::tempdir().unwrap();+ let pidfile = scratch.path().join("exited.pid");+ let mut cmd = openhuman_core::agent::platform_shell::build_tokio_command(&format!(+ "sleep 30 & echo $$ $! > {}; exit 0",+ pidfile.display()+ ));+ let cleanup = ProcessCleanup::default();+ let mut run = Box::pin(cleanup.scope(output_unbounded(&mut cmd)));+ let pids = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ tokio::select! {+ result = &mut run => panic!("pipes closed early: {result:?}"),+ _ = tokio::time::sleep(Duration::from_millis(10)) => {}+ }+ if let Ok(text) = std::fs::read_to_string(&pidfile) {+ let pids: Vec<u32> = text+ .split_whitespace()+ .map(|p| p.parse().unwrap())+ .collect();+ break pids;+ }+ }+ })+ .await+ .unwrap();+ // Poll the output future while the waiter processes the shell's exit.+ tokio::select! {+ result = &mut run => panic!("pipes closed early: {result:?}"),+ _ = tokio::time::sleep(Duration::from_millis(100)) => {}+ }+ let leader_reserved = std::path::Path::new(&format!("/proc/{}", pids[0])).exists();+ drop(run);+ tokio::time::timeout(Duration::from_secs(2), cleanup.wait())+ .await+ .unwrap();+ assert!(+ leader_reserved,+ "reaped leader PID could be reused while cancellation still addresses its group"+ );+ assert!(!std::path::Path::new(&format!("/proc/{}", pids[0])).exists());+}++#[tokio::test]+async fn cancellable_turns_route_interpreters_away_from_unacknowledged_pools() {+ let mut config = openhuman_core::config::RuntimePoolConfig::default();+ config.python.enabled = Some(true);+ assert!(openhuman_core::runtime::pool::python::enabled(&config));+ assert!(openhuman_core::runtime::pool::node::enabled(&config));+ let cleanup = ProcessCleanup::default();+ cleanup+ .scope(async {+ tokio::task::yield_now().await;+ assert!(!openhuman_core::runtime::pool::python::enabled(&config));+ assert!(+ !openhuman_core::runtime::pool::node::enabled(&config),+ "cancellable node jobs must use an owned subprocess"+ );+ })+ .await;+ assert!(openhuman_core::runtime::pool::node::enabled(&config));+}diff --git a/crates/openhuman-embed/tests/route_headers.rs b/crates/openhuman-embed/tests/route_headers.rsnew file mode 100644index 0000000000..e341a27a65--- /dev/null+++ b/crates/openhuman-embed/tests/route_headers.rs@@ -0,0 +1,77 @@+//! Per-route attribution headers follow only the endpoint and turn named by the host.++mod common;++use common::{chat_requests, offline_config, provider, route, runtime, stub_backend};+use openhuman_embed::{AgentSpec, Provider, Route, Runtime, Workspace};++#[test]+fn attribution_headers_are_scoped_to_each_agent_and_turn_route() {+ runtime().block_on(async { tokio::spawn(scenario()).await.unwrap() });+}++async fn scenario() {+ let backend = stub_backend().await;+ let (a_provider, b_provider) = tokio::join!(provider("a"), provider("b"));+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let a_route = Route::openai_compatible(format!("{}/v1", a_provider.uri()), "a-key")+ .header("x-medulla-agent-id", "worker-a")+ .header("x-medulla-run-id", "a-run");+ assert!(+ !format!("{a_route:?}").contains("a-run"),+ "header values must stay out of Debug"+ );+ let a = runtime+ .agent(AgentSpec::new("worker-a").provider(route(&a_provider, "fixture")))+ .unwrap();+ let b = runtime+ .agent(+ AgentSpec::new("worker-b").provider(+ Provider::routed(+ Route::openai_compatible(format!("{}/v1", b_provider.uri()), "b-key")+ .header("x-medulla-agent-id", "worker-b"),+ )+ .model("fixture"),+ ),+ )+ .unwrap();+ let (a_result, b_result) = tokio::join!(a.turn("a").route(a_route).send(), b.run("b"));+ a_result.unwrap();+ b_result.unwrap();+ // The next turn inherits the agent provider, not the previous turn's headers.+ a.run("next a").await.unwrap();+ let a_requests = chat_requests(&a_provider).await;+ let b_requests = chat_requests(&b_provider).await;+ assert_eq!(a_requests.len(), 2);+ assert_eq!(b_requests.len(), 1);+ assert_eq!(+ a_requests[0].headers.get("x-medulla-agent-id").unwrap(),+ "worker-a"+ );+ assert_eq!(+ a_requests[0].headers.get("x-medulla-run-id").unwrap(),+ "a-run"+ );+ assert_eq!(+ a_requests[0].headers.get("authorization").unwrap(),+ "Bearer a-key"+ );+ assert!(a_requests[1].headers.get("x-medulla-run-id").is_none());+ assert_eq!(+ b_requests[0].headers.get("x-medulla-agent-id").unwrap(),+ "worker-b"+ );+ assert!(b_requests[0].headers.get("x-medulla-run-id").is_none());+ assert!(backend+ .received_requests()+ .await+ .unwrap()+ .iter()+ .all(|r| r.headers.get("x-medulla-run-id").is_none()));+}diff --git a/crates/openhuman-embed/tests/scoped_hooks.rs b/crates/openhuman-embed/tests/scoped_hooks.rsnew file mode 100644index 0000000000..3a7ae3ae96--- /dev/null+++ b/crates/openhuman-embed/tests/scoped_hooks.rs@@ -0,0 +1,256 @@+//! Agent and turn hooks stay isolated while concurrent workers share a runtime.++mod common;++use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};++use common::{+ chat_completion, eventually, offline_config, route, runtime, scripted_provider, stub_backend,+ tool_call_completion,+};+use openhuman_embed::seams::{PostTurnHook, ToolHook, ToolHookContext, TurnContext};+use openhuman_embed::{+ AgentDefinitionSpec, AgentSpec, HostTurnTools, Runtime, Tool, ToolScopeSpec, Workspace,+};+use serde_json::{json, Value};+use tokio::sync::Barrier;+use wiremock::MockServer;++type Events = Arc<Mutex<Vec<(String, String, String)>>>;++struct Observer {+ label: &'static str,+ events: Events,+ first: AtomicBool,+ overlap: Option<Arc<Barrier>>,+}++impl Observer {+ fn new(label: &'static str, events: &Events, overlap: Option<Arc<Barrier>>) -> Arc<Self> {+ Arc::new(Self {+ label,+ events: events.clone(),+ first: AtomicBool::new(true),+ overlap,+ })+ }+ fn record(&self, phase: &str, owner: &str) {+ self.events+ .lock()+ .unwrap()+ .push((self.label.into(), phase.into(), owner.into()));+ }+}++#[async_trait::async_trait]+impl ToolHook for Observer {+ fn name(&self) -> &str {+ "same-policy-name"+ }+ async fn before_tool(&self, ctx: &ToolHookContext) -> anyhow::Result<()> {+ self.record("before", ctx.arguments["owner"].as_str().unwrap());+ if self.first.swap(false, Ordering::SeqCst) {+ if let Some(barrier) = &self.overlap {+ tokio::time::timeout(std::time::Duration::from_secs(10), barrier.wait()).await?;+ }+ }+ Ok(())+ }+ async fn after_tool(&self, ctx: &ToolHookContext) -> anyhow::Result<()> {+ assert_eq!(ctx.success, Some(true));+ self.record("after", ctx.arguments["owner"].as_str().unwrap());+ Ok(())+ }+}++#[async_trait::async_trait]+impl PostTurnHook for Observer {+ fn name(&self) -> &str {+ "same-policy-name"+ }+ async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {+ assert!(ctx.session_id.is_some());+ assert!(ctx.agent_id.is_some());+ self.record("turn", ctx.user_message.lines().last().unwrap());+ Ok(())+ }+}++struct Probe;+#[async_trait::async_trait]+impl Tool for Probe {+ fn name(&self) -> &str {+ "probe"+ }+ fn description(&self) -> &str {+ "Report a worker's identity"+ }+ fn parameters_schema(&self) -> Value {+ json!({"type":"object","properties":{"owner":{"type":"string"}},"required":["owner"]})+ }+ async fn execute(&self, _: Value) -> anyhow::Result<openhuman_core::tools::ToolResult> {+ Ok(openhuman_core::tools::ToolResult::success("observed"))+ }+}++fn spec(id: &str, provider: &MockServer) -> AgentSpec {+ AgentSpec::new(id)+ .provider(route(provider, "fixture"))+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("Use probe once, then answer.")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(|_| HostTurnTools::advertised(vec![Box::new(Probe)]))+}++async fn worker_provider(owner: &str) -> MockServer {+ scripted_provider(+ (0..4)+ .flat_map(|_| {+ [+ tool_call_completion("probe", &json!({"owner":owner}).to_string()),+ chat_completion("done"),+ ]+ })+ .collect(),+ "done",+ )+ .await+}++#[test]+fn hooks_are_additive_and_isolated_across_agents_turns_and_reused_ids() {+ runtime().block_on(async { tokio::spawn(scenario()).await.expect("scenario") });+}++async fn scenario() {+ let backend = stub_backend().await;+ let (provider_a, provider_b) = tokio::join!(worker_provider("a"), worker_provider("b"));+ let events: Events = Default::default();+ let global = Observer::new("global", &events, None);+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .tool_hook(global.clone())+ .post_turn_hook(global)+ .build()+ .await+ .expect("runtime");+ let overlap = Arc::new(Barrier::new(2));+ let hook_a = Observer::new("agent-a", &events, Some(overlap.clone()));+ let hook_b = Observer::new("agent-b", &events, Some(overlap));+ let a = runtime+ .agent(+ spec("worker-a", &provider_a)+ .tool_hook(hook_a.clone())+ .post_turn_hook(hook_a),+ )+ .unwrap();+ let b = runtime+ .agent(+ spec("worker-b", &provider_b)+ .tool_hook(hook_b.clone())+ .post_turn_hook(hook_b),+ )+ .unwrap();+ let turn_hook = Observer::new("turn-a", &events, None);+ let scheduled = openhuman_core::agent::host_agents::resolve("worker-a").unwrap();+ scheduled+ .scope(async {+ assert_eq!(+ openhuman_core::agent::hooks::turn_tool_hooks().len(),+ 2,+ "scheduled turns lost the agent's tool hooks"+ );+ assert_eq!(+ openhuman_core::agent::hooks::turn_post_turn_hooks().len(),+ 2,+ "scheduled turns lost the agent's post-turn hooks"+ );+ })+ .await;+ let (first, second) = tokio::join!(+ a.turn("a-first")+ .tool_hook(turn_hook.clone())+ .post_turn_hook(turn_hook)+ .send(),+ b.turn("b-first").send(),+ );+ let first = first.expect("first a");+ second.expect("first b");+ a.turn("a-second")+ .session(first.session_id)+ .send()+ .await+ .expect("resumed a");+ let mut session = scheduled+ .session_host(&scheduled.config, Some("scheduled-a"))+ .unwrap();+ scheduled+ .scope(async { session.turn_with_origin("a-scheduled", None).await })+ .await+ .unwrap();+ runtime.remove_agent("worker-a").await.expect("remove a");+ let replacement = runtime+ .agent(spec("worker-a", &provider_a))+ .expect("reuse id");+ replacement+ .run("replacement")+ .await+ .expect("replacement turn");+ eventually("all background post-turn observers", || {+ let events = events.lock().unwrap();+ (events+ .iter()+ .filter(|(_, phase, _)| phase == "turn")+ .count()+ == 10)+ .then_some(())+ })+ .await;++ let events = events.lock().unwrap();+ let count = |label: &str, phase: &str, owner: &str| {+ events+ .iter()+ .filter(|(l, p, o)| l == label && p == phase && o == owner)+ .count()+ };+ for phase in ["before", "after"] {+ assert_eq!(count("global", phase, "a"), 4);+ assert_eq!(count("global", phase, "b"), 1);+ assert_eq!(count("agent-a", phase, "a"), 3);+ assert_eq!(count("agent-b", phase, "b"), 1);+ assert_eq!(count("turn-a", phase, "a"), 1);+ assert_eq!(count("agent-a", phase, "b"), 0);+ assert_eq!(count("agent-b", phase, "a"), 0);+ assert_eq!(count("turn-a", phase, "b"), 0);+ }+ for (label, message) in [+ ("global", "a-first"),+ ("global", "b-first"),+ ("global", "a-second"),+ ("global", "a-scheduled"),+ ("global", "replacement"),+ ("agent-a", "a-first"),+ ("agent-a", "a-second"),+ ("agent-a", "a-scheduled"),+ ("agent-b", "b-first"),+ ("turn-a", "a-first"),+ ] {+ assert_eq!(+ count(label, "turn", message),+ 1,+ "{label} / {message}: {events:?}"+ );+ }+ // Agent/turn callbacks never enter the runtime's process-global registry.+ assert_eq!(openhuman_core::agent::hooks::embedder_tool_hooks().len(), 1);+ assert_eq!(+ openhuman_core::agent::hooks::embedder_post_turn_hooks().len(),+ 1+ );+}diff --git a/crates/openhuman-embed/tests/tool_environment.rs b/crates/openhuman-embed/tests/tool_environment.rsnew file mode 100644index 0000000000..9ac96036f5--- /dev/null+++ b/crates/openhuman-embed/tests/tool_environment.rs@@ -0,0 +1,24 @@+//! Turn-owned child environments never mutate or inherit the daemon's env.++#![cfg(unix)]++use openhuman_core::tools::timeout::{output_unbounded, CommandEnvironment};++#[tokio::test]+async fn overlapping_command_environments_replace_inheritance_without_crossing_turns() {+ let run = |label: &'static str| async move {+ let environment = CommandEnvironment::new([(String::from("TURN_OWNER"), label.into())]);+ environment+ .scope(async {+ tokio::task::yield_now().await;+ let mut command = tokio::process::Command::new("/usr/bin/env");+ command.env("COMMAND_OWNED", "runtime-setting");+ String::from_utf8(output_unbounded(&mut command).await.unwrap().stdout).unwrap()+ })+ .await+ };+ let (a, b) = tokio::join!(run("a"), run("b"));+ assert_eq!(a.trim(), "COMMAND_OWNED=runtime-setting\nTURN_OWNER=a");+ assert_eq!(b.trim(), "COMMAND_OWNED=runtime-setting\nTURN_OWNER=b");+ assert!(!CommandEnvironment::is_active());+}diff --git a/crates/openhuman-embed/tests/tool_hook_context.rs b/crates/openhuman-embed/tests/tool_hook_context.rsnew file mode 100644index 0000000000..4b1ea6af21--- /dev/null+++ b/crates/openhuman-embed/tests/tool_hook_context.rs@@ -0,0 +1,109 @@+//! Hook attribution and cwd agree with the builtin tool's actual working directory.++mod common;++use common::{+ chat_completion, offline_config, route, runtime, scripted_provider, stub_backend,+ tool_call_completion,+};+use openhuman_embed::seams::{ToolHook, ToolHookContext};+use openhuman_embed::{Access, AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};+use serde_json::{json, Value};+use std::sync::{Arc, Mutex};++struct Capture(Arc<Mutex<Vec<Value>>>);+#[async_trait::async_trait]+impl ToolHook for Capture {+ fn name(&self) -> &str {+ "context-probe"+ }+ async fn before_tool(&self, ctx: &ToolHookContext) -> anyhow::Result<()> {+ self.0.lock().unwrap().push(serde_json::to_value(ctx)?);+ Ok(())+ }+ async fn after_tool(&self, ctx: &ToolHookContext) -> anyhow::Result<()> {+ self.0.lock().unwrap().push(serde_json::to_value(ctx)?);+ Ok(())+ }+}++#[test]+fn cwd_and_identity_follow_the_turn_and_then_return_to_the_agent_defaults() {+ runtime().block_on(async { tokio::spawn(scenario()).await.unwrap() });+}++async fn scenario() {+ let backend = stub_backend().await;+ let provider = scripted_provider(+ (0..2)+ .flat_map(|_| {+ [+ tool_call_completion("shell", &json!({"command":"pwd; printf '\\nowner=%s home=%s\\n' \"$TURN_OWNER\" \"$HOME\""}).to_string()),+ chat_completion("done"),+ ]+ })+ .collect(),+ "done",+ )+ .await;+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let default_dir = tempfile::tempdir().unwrap();+ let turn_dir = tempfile::tempdir().unwrap();+ let observed = Arc::new(Mutex::new(Vec::new()));+ let agent = runtime+ .agent(+ AgentSpec::new("cwd-worker")+ .provider(route(&provider, "fixture"))+ .access(Access::full())+ .action_dir(default_dir.path())+ .tool_hook(Arc::new(Capture(observed.clone())))+ .definition(+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),+ ),+ )+ .unwrap();+ agent+ .turn("run pwd")+ .session("override-session")+ .cwd(turn_dir.path())+ .tool_env([("TURN_OWNER".into(), "isolated".into())])+ .send()+ .await+ .unwrap();+ agent+ .turn("run pwd again")+ .session("default-session")+ .send()+ .await+ .unwrap();+ let observed = observed.lock().unwrap();+ assert_eq!(observed.len(), 4);+ assert!(observed[1]["output"]+ .as_str()+ .unwrap()+ .contains("owner=isolated home=\n"));+ for (pair, session, cwd) in [+ (&observed[..2], "override-session", turn_dir.path()),+ (&observed[2..], "default-session", default_dir.path()),+ ] {+ for context in pair {+ assert_eq!(context["agent_id"], "cwd-worker", "{context}");+ assert_eq!(context["session_id"], session, "{context}");+ assert_eq!(context["cwd"], cwd.to_string_lossy().as_ref(), "{context}");+ }+ assert!(+ pair[1]["output"]+ .as_str()+ .unwrap()+ .contains(cwd.to_string_lossy().as_ref()),+ "builtin shell disagrees with hook cwd: {}",+ pair[1]+ );+ }+}diff --git a/crates/openhuman-embed/tests/turn_cancellation.rs b/crates/openhuman-embed/tests/turn_cancellation.rsindex 0973411a3d..2512c8f96f 100644--- a/crates/openhuman-embed/tests/turn_cancellation.rs+++ b/crates/openhuman-embed/tests/turn_cancellation.rs@@ -31,7 +31,12 @@ async fn scenario() {.unwrap();// Cancellation before send never reaches inference and cannot hang.- let mut turn = agent.turn("cancel before sending");+ let metered = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let observed = metered.clone();+ let mut turn = agent.turn("cancel before sending").meter(move |usage| {+ assert!(usage.is_none());+ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ });let cancel = turn.cancellation_handle();tokio::time::timeout(Duration::from_secs(2), cancel.cancel()).await@@ -41,6 +46,11 @@ async fn scenario() {Err(CoreError::TurnCancelled { .. })));assert!(common::chat_requests(&provider).await.is_empty());+ assert_eq!(+ metered.load(std::sync::atomic::Ordering::SeqCst),+ 1,+ "cancelled turn is metered once"+ );// A later turn on the same agent remains usable.let mut turn = agent.turn("answer normally");@@ -66,7 +76,10 @@ async fn scenario() {let blocked = runtime.agent(AgentSpec::new("blocked").provider(route(&slow, "test-model"))).unwrap();- let mut turn = blocked.turn("wait for inference");+ let observed = metered.clone();+ let mut turn = blocked.turn("wait for inference").meter(move |_| {+ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ });let cancel = turn.cancellation_handle();let sent = tokio::spawn(turn.send());tokio::time::timeout(Duration::from_secs(5), async {@@ -86,10 +99,14 @@ async fn scenario() {sent.await.unwrap(),Err(CoreError::TurnCancelled { .. })));+ assert_eq!(metered.load(std::sync::atomic::Ordering::SeqCst), 2);assert_eq!(agent.run("still usable").await.unwrap().reply, "finished");// An externally dropped send future also acknowledges cancellation.- let mut turn = blocked.turn("drop this inference request");+ let observed = metered.clone();+ let mut turn = blocked.turn("drop this inference request").meter(move |_| {+ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ });let cancel = turn.cancellation_handle();let sent = tokio::spawn(turn.send());tokio::time::timeout(Duration::from_secs(5), async {@@ -105,6 +122,8 @@ async fn scenario() {.await.unwrap();+ assert_eq!(metered.load(std::sync::atomic::Ordering::SeqCst), 3);+let mut invalid = agent.turn("invalid route").route(openhuman_embed::Route::openai_compatible(diff --git a/crates/openhuman-embed/tests/turn_tools.rs b/crates/openhuman-embed/tests/turn_tools.rsnew file mode 100644index 0000000000..b1543f26e0--- /dev/null+++ b/crates/openhuman-embed/tests/turn_tools.rs@@ -0,0 +1,176 @@+//! A host can await its own approval UI inline without polling the core.++mod common;++use common::{+ chat_completion, offline_config, route, runtime, scripted_provider, stub_backend,+ tool_call_completion,+};+use openhuman_embed::{+ AgentDefinitionSpec, AgentSpec, HostTurnTools, Runtime, Tool, ToolScopeSpec, Workspace,+};+use serde_json::{json, Value};+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Arc,+};++struct Probe(Arc<AtomicUsize>);+#[async_trait::async_trait]+impl Tool for Probe {+ fn name(&self) -> &str {+ "probe"+ }+ fn description(&self) -> &str {+ "Perform a host operation"+ }+ fn parameters_schema(&self) -> Value {+ json!({"type":"object","properties":{}})+ }+ async fn execute(&self, _: Value) -> anyhow::Result<openhuman_core::tools::ToolResult> {+ self.0.fetch_add(1, Ordering::SeqCst);+ Ok(openhuman_core::tools::ToolResult::success("ran"))+ }+}+#[test]+fn turn_tool_belts_replace_agent_tools_without_leaking_into_resumed_or_concurrent_turns() {+ runtime().block_on(async { tokio::spawn(scenario()).await.unwrap() });+}+async fn scenario() {+ let backend = stub_backend().await;+ let provider = scripted_provider(+ (0..3)+ .flat_map(|_| [tool_call_completion("probe", "{}"), chat_completion("done")])+ .collect(),+ "done",+ )+ .await;+ let other_provider = scripted_provider(vec![tool_call_completion("probe", "{}")], "done").await;+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let calls = Arc::new(AtomicUsize::new(0));+ let replacement_calls = Arc::new(AtomicUsize::new(0));+ let other_calls = Arc::new(AtomicUsize::new(0));+ let spec = |id, provider: &wiremock::MockServer, calls: Arc<AtomicUsize>| {+ AgentSpec::new(id)+ .provider(route(provider, "fixture"))+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("Use probe then answer")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(move |_| HostTurnTools::advertised(vec![Box::new(Probe(calls.clone()))]))+ };+ let agent = runtime+ .agent(spec("replace", &provider, calls.clone()))+ .unwrap();+ let other = runtime+ .agent(spec("other", &other_provider, other_calls.clone()))+ .unwrap();+ let replacement = replacement_calls.clone();+ let (first, other_result) = tokio::join!(+ agent+ .turn("replacement")+ .session("same-thread")+ .tools(move |_| HostTurnTools::advertised(vec![Box::new(Probe(replacement.clone()))]))+ .send(),+ other.run("independent")+ );+ first.unwrap();+ other_result.unwrap();+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ assert_eq!(replacement_calls.load(Ordering::SeqCst), 1);+ assert_eq!(other_calls.load(Ordering::SeqCst), 1);+ agent+ .turn("revoked")+ .session("same-thread")+ .tools(|_| HostTurnTools::advertised(vec![]))+ .send()+ .await+ .unwrap();+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ assert_eq!(+ replacement_calls.load(Ordering::SeqCst),+ 1,+ "revoked tool was still executable"+ );+ agent+ .turn("restore")+ .session("same-thread")+ .send()+ .await+ .unwrap();+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ let requests = common::chat_requests(&provider).await;+ let revoked = requests+ .iter()+ .find(|r| {+ r.body_json::<Value>().unwrap()["messages"]+ .as_array()+ .unwrap()+ .iter()+ .any(|m| {+ m["content"]+ .as_str()+ .is_some_and(|s| s.ends_with("revoked"))+ })+ })+ .unwrap();+ assert!(!revoked.body_json::<Value>().unwrap()["tools"]+ .as_array()+ .is_some_and(|tools| tools.iter().any(|t| t["function"]["name"] == "probe")));+ // A mixed builtin/host definition must also discard historical declarations+ // on an explicit replacement. HostOnly's inherent strict snapshot is not+ // enough to exercise the replacement's dispatch scope.+ let mixed_provider = scripted_provider(+ vec![+ tool_call_completion("probe", "{}"),+ chat_completion("done"),+ chat_completion("no tools"),+ tool_call_completion("probe", "{}"),+ chat_completion("done"),+ ],+ "done",+ )+ .await;+ let mixed_calls = Arc::new(AtomicUsize::new(0));+ let mixed = runtime+ .agent(+ spec("mixed", &mixed_provider, mixed_calls.clone()).definition(+ AgentDefinitionSpec::new()+ .bare_prompt("Use the offered tools")+ .tools(ToolScopeSpec::Named(vec!["probe".into()])),+ ),+ )+ .unwrap();+ mixed+ .turn("initial belt")+ .session("mixed-thread")+ .send()+ .await+ .unwrap();+ mixed+ .turn("replace with empty belt")+ .session("mixed-thread")+ .tools(|_| HostTurnTools::advertised(vec![]))+ .send()+ .await+ .unwrap();+ assert_eq!(mixed_calls.load(Ordering::SeqCst), 1);+ let requests = common::chat_requests(&mixed_provider).await;+ assert!(!requests[2].body_json::<Value>().unwrap()["tools"]+ .as_array()+ .is_some_and(|tools| tools.iter().any(|t| t["function"]["name"] == "probe")));+ mixed+ .turn("restore belt")+ .session("mixed-thread")+ .send()+ .await+ .unwrap();+ assert_eq!(mixed_calls.load(Ordering::SeqCst), 2);+}diff --git a/crates/openhuman-embed/tests/usage_hooks.rs b/crates/openhuman-embed/tests/usage_hooks.rsnew file mode 100644index 0000000000..fadcffa411--- /dev/null+++ b/crates/openhuman-embed/tests/usage_hooks.rs@@ -0,0 +1,174 @@+//! Scoped usage observers and budget policies run between provider calls.++mod common;++use common::{+ chat_completion, chat_requests, offline_config, route, runtime, scripted_provider,+ stub_backend, tool_call_completion,+};+use openhuman_embed::seams::{StopDecision, StopHook, TurnState};+use openhuman_embed::{+ AgentDefinitionSpec, AgentSpec, HostTurnTools, Runtime, Tool, ToolScopeSpec, Workspace,+};+use serde_json::{json, Value};+use std::sync::{Arc, Mutex};++type Seen = Arc<Mutex<Vec<(String, u32, u64, Option<f64>)>>>;+struct Policy {+ label: &'static str,+ seen: Seen,+ stop: bool,+}+#[async_trait::async_trait]+impl StopHook for Policy {+ fn name(&self) -> &str {+ "usage-budget"+ }+ async fn check(&self, state: &TurnState<'_>) -> StopDecision {+ self.seen.lock().unwrap().push((+ self.label.into(),+ state.iteration,+ state.cost.input_tokens + state.cost.output_tokens,+ state.cost.total_usd(),+ ));+ if self.stop {+ StopDecision::Stop {+ reason: "worker budget exhausted".into(),+ }+ } else {+ StopDecision::Continue+ }+ }+}+struct Probe;+#[async_trait::async_trait]+impl Tool for Probe {+ fn name(&self) -> &str {+ "probe"+ }+ fn description(&self) -> &str {+ "Read a value"+ }+ fn parameters_schema(&self) -> Value {+ json!({"type":"object","properties":{}})+ }+ async fn execute(&self, _: Value) -> anyhow::Result<openhuman_core::tools::ToolResult> {+ Ok(openhuman_core::tools::ToolResult::success("value"))+ }+}+fn billed(mut response: Value) -> Value {+ response["usage"]["cost"] = json!(0.02);+ response+}+#[test]+fn per_agent_budget_stops_before_the_next_model_call_and_turn_observers_do_not_leak() {+ runtime().block_on(async { tokio::spawn(scenario()).await.unwrap() });+}+async fn scenario() {+ let backend = stub_backend().await;+ let a_provider = scripted_provider(+ vec![billed(tool_call_completion("probe", "{}"))],+ "extra call",+ )+ .await;+ let b_provider = scripted_provider(+ vec![+ billed(tool_call_completion("probe", "{}")),+ billed(chat_completion("done")),+ {+ let mut response = chat_completion("free");+ response["usage"]["cost"] = json!(0.0);+ response+ },+ ],+ "next turn",+ )+ .await;+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let seen: Seen = Default::default();+ let spec = |id, provider: &wiremock::MockServer| {+ AgentSpec::new(id)+ .provider(route(provider, "fixture"))+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("Use probe then answer")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(|_| HostTurnTools::advertised(vec![Box::new(Probe)]))+ };+ let a = runtime+ .agent(spec("budget-a", &a_provider).stop_hook(Arc::new(Policy {+ label: "a",+ seen: seen.clone(),+ stop: true,+ })))+ .unwrap();+ let b = runtime.agent(spec("budget-b", &b_provider)).unwrap();+ let (a_result, b_result) = tokio::join!(+ a.turn("work")+ .stop_hook(Arc::new(Policy {+ label: "a-turn",+ seen: seen.clone(),+ stop: false,+ }))+ .send(),+ b.turn("work")+ .stop_hook(Arc::new(Policy {+ label: "b-turn",+ seen: seen.clone(),+ stop: false+ }))+ .send()+ );+ assert_eq!(a_result.unwrap().usage.unwrap().cost_usd, Some(0.02));+ let b_result = b_result.unwrap();+ assert_eq!(+ chat_requests(&a_provider).await.len(),+ 1,+ "budget permitted another model call"+ );+ assert_eq!(chat_requests(&b_provider).await.len(), 2);+ assert_eq!(b_result.usage.unwrap().cost_usd, Some(0.04));+ assert_eq!(+ b.run("a later turn").await.unwrap().usage.unwrap().cost_usd,+ Some(0.0)+ );+ assert_eq!(+ b.run("an unpriced turn")+ .await+ .unwrap()+ .usage+ .unwrap()+ .cost_usd,+ None+ );+ let seen = seen.lock().unwrap();+ assert_eq!(+ seen.iter().filter(|(label, _, _, _)| label == "a").count(),+ 1+ );+ assert_eq!(+ seen.iter()+ .filter(|(label, _, _, _)| label == "a-turn")+ .count(),+ 1,+ "agent budget stop skipped the turn usage observer"+ );+ let b_seen: Vec<_> = seen+ .iter()+ .filter(|(label, _, _, _)| label == "b-turn")+ .collect();+ assert_eq!(b_seen.len(), 2, "turn observer leaked to a later turn");+ assert_eq!(b_seen[0].1, 1);+ assert_eq!(b_seen[0].2, 2);+ assert_eq!(b_seen[0].3, Some(0.02));+ assert_eq!(b_seen[1].1, 2);+ assert_eq!(b_seen[1].2, 4);+ assert_eq!(b_seen[1].3, Some(0.04));+}diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 912c2b7530..a8eb32207d 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -661,6 +661,14 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused || 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` || 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |+| 16.1.14 | Agent and turn hook isolation | RI | `crates/openhuman-embed/tests/scoped_hooks.rs` | ✅ | Additive same-named callbacks, overlapping worker turns, one-turn callback lifetime, resumed-session snapshots, core-scheduled turn callbacks and reuse of a removed agent id without registry leakage |+| 16.1.15 | Agent-turn route attribution headers | RU+RI | `crates/openhuman-embed/tests/route_headers.rs`, `crates/openhuman-embed/src/turn_tests.rs` | ✅ | Per-route headers reach only the named endpoint and turn, remain absent on other agents and backend requests, and are redacted in Debug; wire fields pinned against the registered controller schema |+| 16.1.16 | Tool-hook turn identity and cwd | RI | `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Before and after hooks report the worker/session and working root used by builtin shell; a later turn returns to its agent default |++| 16.1.17 | Inline agent/turn permission callback | RI | `crates/openhuman-embed/tests/inline_permissions.rs` | ✅ | UI decisions precede execution; denials narrow authority, concurrent agents remain independent, cancellation closes a pending receiver and a closed UI refuses execution |+| 16.1.18 | Per-turn host-tool replacement | RI | `crates/openhuman-embed/tests/turn_tools.rs` | ✅ | Replacement and empty-belt revocation apply to resumed HostOnly and mixed definitions, without restoring historical declarations or affecting other agents and later turns |+| 16.1.19 | Scoped usage observation and budget stop | RI | `crates/openhuman-embed/tests/usage_hooks.rs` | ✅ | Cumulative charged cost and tokens, known-zero versus unpriced calls, per-agent policy and per-turn observer isolation; no summary-repair model calls after a stop |+| 16.1.20 | Scoped builtin command environments | RI | `crates/openhuman-embed/tests/tool_environment.rs`, `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Overlapping subprocess maps exclude host inheritance on Unix; a real shell receives its turn's variables while excluding host HOME and preserving command-owned runtime/security additions |## Summarydiff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjsindex 72c437f51c..5fd1efbe3a 100644--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@ -39,7 +39,7 @@ const LEGACY_LIMIT_ENTRIES = [// under the general 750 limit, so it needs no exception at all.// The session-todo integration added transcript metadata construction to// this already-exempt composition seam. Keep its allowance exact.- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1406],+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1356],// Session-host factory still assembles the product's deliberately coupled// provider, security, memory, tool and prompt policy. Generic session// state moved to tinyagents-runtime; this remaining composition is split in