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
Merge remote-tracking branch 'upstream/main' into tinywallet-release-0192
Steven Enamakeleb420d1479f1
diff --cc crates/openhuman-core/src/agent/artifacts/files_tests.rsindex 37e11d8b7f,8c8f94f3bc..210ad49076--- a/crates/openhuman-core/src/agent/artifacts/files_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/files_tests.rs@@@ -15,11 -15,11 +15,18 @@@ async fn create_readytitle: &str,bytes: &[u8],) -> ArtifactMeta {- let (meta, path) = create_artifact(workspace, files_dir, ArtifactKind::Document, title, "txt")- let (meta, path) = create_artifact(workspace, files_dir, ArtifactKind::Document, title, "txt", None)-- .await-- .expect("create_artifact");++ let (meta, path) = create_artifact(++ workspace,++ files_dir,++ ArtifactKind::Document,++ title,++ "txt",++ None,++ )++ .await++ .expect("create_artifact");tokio::fs::write(&path, bytes).await.unwrap();- finalize_artifact(workspace, &meta.id, bytes.len() as u64)+ finalize_artifact(workspace, &meta.id, bytes.len() as u64, None).await.expect("finalize_artifact")}diff --cc crates/openhuman-core/src/agent/artifacts/ops_tests.rsindex 40a534a128,98d718df8b..fc06e97353--- a/crates/openhuman-core/src/agent/artifacts/ops_tests.rs+++ b/crates/openhuman-core/src/agent/artifacts/ops_tests.rs@@@ -368,7 -371,7 +371,9 @@@ async fn get_returns_the_files_folder_p.await.unwrap();std::fs::write(&path, b"plan").unwrap();- finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap();- finalize_artifact(tmp.path(), &meta.id, 4, None).await.unwrap();++ finalize_artifact(tmp.path(), &meta.id, 4, None)++ .await++ .unwrap();let value = ai_get_artifact(&config, &meta.id).await@@@ -399,7 -403,7 +405,9 @@@ async fn get_reports_a_ready_file_remov.await.unwrap();std::fs::write(&path, b"plan").unwrap();- finalize_artifact(tmp.path(), &meta.id, 4).await.unwrap();- finalize_artifact(tmp.path(), &meta.id, 4, None).await.unwrap();++ finalize_artifact(tmp.path(), &meta.id, 4, None)++ .await++ .unwrap();std::fs::remove_file(&path).unwrap();let err = ai_get_artifact(&config, &meta.id).await.unwrap_err();diff --cc crates/openhuman-core/src/agent/artifacts/store.rsindex 8d18b08158,b0d8373c87..b7a1918e9d--- a/crates/openhuman-core/src/agent/artifacts/store.rs+++ b/crates/openhuman-core/src/agent/artifacts/store.rs@@@ -568,23 -575,20 +575,22 @@@ pub async fn fail_artifactOk(meta)}- /// Read the active [`ApprovalChatContext`] task-local (set by- /// `web_chat` around each chat turn) and return its thread id, client- /// id, and the originating turn's `request_id`. Returns `(None, None,- /// None)` for non-chat callers (CLI, cron, sub-agent runners) so- /// artifact emit hooks degrade gracefully — the event is still- /// published but the web subscriber drops it for lack of a routing- /// target.- fn current_chat_context() -> (Option<String>, Option<String>, Option<String>) {- crate::security::approval::APPROVAL_CHAT_CONTEXT- .try_with(|ctx| {- (- Some(ctx.thread_id.clone()),- Some(ctx.client_id.clone()),- ctx.request_id.clone(),- )- })- .unwrap_or((None, None, None))+ /// The routing triple of the producing turn's [`ApprovalChatContext`]: its+ /// thread id, client id and originating `request_id`. `(None, None, None)` for+ /// non-chat callers (CLI, cron, sub-agent runners) so artifact emit hooks+ /// degrade gracefully: the event is still published but the web subscriber+ /// drops it for lack of a routing target.-fn chat_route(chat: Option<&ApprovalChatContext>) -> (Option<String>, Option<String>, Option<String>) {++fn chat_route(++ chat: Option<&ApprovalChatContext>,++) -> (Option<String>, Option<String>, Option<String>) {+ match chat {+ Some(ctx) => (+ Some(ctx.thread_id.clone()),+ Some(ctx.client_id.clone()),+ ctx.request_id.clone(),+ ),+ None => (None, None, None),+ }}#[cfg(test)]diff --cc crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rsindex 6dcba7b193,78f0d4f1fa..f0c4f187da--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs@@@ -12,13 -12,25 +12,25 @@@//! one wrapper whose result *is* the wrapped tool's result;//! * **the read limit**: the largest body `file_read` will open//! ([`FileReadTool::MAX_FILE_SIZE_BYTES`]);- //! * **where the files go**: `<workspace_dir>/artifacts/tool-results`- //! ([`crate::security::policy::tool_result_artifacts_dir`]), a detached store- //! outside the action directory, so a tool output is never written into the- //! project the agent is working in.+ //! * **where the bodies live**: on the acting tenant's scoped blob store+ //! ([`crate::agent::session_store::artifact_blobs_for`]), under the+ //! `tool-results/<session>/<tool>/<call>.txt` key the pointer quotes. Nothing+ //! is written into the project the agent is working in;+ //! * **how `file_read` opens one**: `file_read` reads the filesystem, so a read+ //! of a `tool-results/…` key is first *materialised* from the blob store into+ //! `<workspace_dir>/artifacts/tool-results`+ //! ([`crate::security::policy::tool_result_artifacts_dir`], a read-only trusted+ //! root) and the call is pointed at that file ([`HostArtifactStore::resolve_read`]).+ //! The blob lookup runs on every read, so a key another tenant wrote is absent+ //! from this tenant's store and is never served, and a session that reloads+ //! finds its artifacts again because the blobs outlive the process.++ use std::path::{Path, PathBuf};+ use std::sync::Arc;use serde_json::Value;-use tinystoragedrivers::BlobStore;use tinyagents_harness::artifacts::tool_results::{self, ArtifactRead, ToolResultArtifactStore};++use tinystoragedrivers::BlobStore;use crate::agent::harness::artifact_offload::{SanitizingRedactor, READ_TOOL};use tinytools_std::filesystem::FileReadTool;diff --cc crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rsindex f3a7ad058e,4828497bc5..17d69363ae--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs@@@ -36,22 -32,21 +32,27 @@@ async fn threshold_persists_to_blobs_an).await;- let expected = workspace.join("artifacts/tool-results/session_one/shell/call-1.txt");- let pointer = expected.to_string_lossy().into_owned();+ let key = "tool-results/session_one/shell/call-1.txt";assert!(outcome.persisted);+ assert!(out.contains(&format!("artifact_path: {key}\n")), "{out}");+ assert!(out.contains("[preview]"));+ assert!(!out.contains(secret));- assert!(!root.exists(), "nothing is on disk until a read asks for it");+ assert!(- out.contains(&format!("artifact_path: {pointer}\n")),- "{out}"++ !root.exists(),++ "nothing is on disk until a read asks for it"+ );- assert!(out.contains("original_bytes:"));- assert!(out.contains("[preview]"));- assert!(!out.contains("Bearer credential-marker-redact-me-123456"));- assert!(expected.is_file());+ assert_eq!(std::fs::read_dir(&project).unwrap().count(), 0);++ // The model's `file_read {"path": key}` is recognised and pointed at the+ // materialised copy of the blob.+ let mut args = json!({"path": key});+ let read = artifact_read_target(Some(&store), "file_read", &args).expect("artifact read");+ store.resolve_read(&mut args, &read).await;+ let pointer = args["path"].as_str().unwrap().to_string();- assert_eq!(std::path::Path::new(&pointer), root.join("session_one/shell/call-1.txt"));+ assert_eq!(- std::fs::read_dir(&project).unwrap().count(),- 0,- "nothing may be written into the project"++ std::path::Path::new(&pointer),++ root.join("session_one/shell/call-1.txt")+ );let cfg = crate::config::AutonomyConfig {enabled: true,diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 24ed24171b,42addc6da4..2681117a46--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@@ -402,9 -407,11 +407,11 @@@ pub(crate) struct HarnessHostPolicypub(crate) tool_call_cap: Option<usize>,}++#[cfg(test)]++pub(crate) use super::operation_context::tool_context_with_approval;pub(crate) use super::operation_context::{- parent_agent_id_for_tool, sandbox_mode_for_tool, HostOperationContext,+ approval_for_tool, parent_agent_id_for_tool, sandbox_mode_for_tool, HostOperationContext,};-#[cfg(test)]-pub(crate) use super::operation_context::tool_context_with_approval;/// OpenHuman product values that tools read from the run through/// `ToolExecutionContext::host::<OpenHumanRunExt>()`, installed bydiff --cc crates/openhuman-core/src/agent/tinyagents/middleware/approval.rsindex 34863c7422,a6e7f8a8e1..74d40c0f7a--- a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs@@@ -136,7 -136,7 +136,12 @@@ impl ApprovalResolver<crate::agent::tinlet summary = summarize_action(&call.name, &call.arguments);let redacted = redact_args(&call.arguments);let (outcome, request_id) = gate- .intercept_audited(approval_name.as_ref(), &summary, redacted)- .intercept_audited(&ctx.data.approval, approval_name.as_ref(), &summary, redacted)++ .intercept_audited(++ &ctx.data.approval,++ approval_name.as_ref(),++ &summary,++ redacted,++ ).await;match outcome {GateOutcome::Deny { reason } => {diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rsindex a6181150a9,1974cf7f12..024e4bd1cb--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs@@@ -20,9 -21,9 +21,7 @@@ use crate::agent::harness::tool_result_};use crate::agent::tinyagents::payload_summarizer::DynPayloadSummarizer;use crate::inference::tokenjuice::generate::GenerateTicket;--use tinyagents_harness::artifacts::tool_results::{- ArtifactRead, ToolResultArtifactOutcome, ToolResultArtifactStore,- ArtifactRead, ToolResultArtifactOutcome,--};++use tinyagents_harness::artifacts::tool_results::{ArtifactRead, ToolResultArtifactOutcome};use tinyagents_harness::middleware::library::{plan_output_stages, run_output_ladder, CompactedOutput, OutputCapPolicy, OutputLadderInput,OutputProcessor,@@@ -446,7 -447,11 +445,7 @@@ impl Middleware<(), crate::agent::tinya}}if let Some(read) =- artifact_read_target(self.artifact_store.as_ref(), &call.name, &call.arguments)- artifact_read_target(- self.artifact_store.as_deref(),- &call.name,- &call.arguments,- )++ artifact_read_target(self.artifact_store.as_deref(), &call.name, &call.arguments){tracing::debug!(tool = %call.name,diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rsindex 09fdba2c4b,afe12796b4..713a97aa83--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs@@@ -16,8 -16,8 +16,8 @@@ use tinyinference_llm::message::Messageuse tinyinference_llm::model::{ModelRequest, ModelResponse, ResolvedModelRoute};use tinytools::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};-use crate::agent::tinyagents::payload_summarizer::DynPayloadSummarizer;+ use crate::agent::harness::tool_result_artifacts::HostArtifactStore;+use crate::agent::tinyagents::payload_summarizer::DynPayloadSummarizer;- use tinyagents_harness::artifacts::tool_results::ToolResultArtifactStore;use tinyagents_harness::turn_outcome::ToolCallOutcome;use tinyjuice_bus::types::AgentTokenjuiceCompression;diff --cc crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsindex a96f64ebe9,16fe49d7cf..27d2b1da53--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@@ -439,29 -458,12 +458,11 @@@ pub(crate) async fn process_channel_runactive_turn_model_source,progress_tx,turn_origin,+ approval,)),};- // Sub-issue 2 of #3098: scope the agent turn in an `ApprovalChatContext`- // for every channel with the `chat_approvals` capability (served by- // `ChannelApprovalSurfaceSubscriber`). Without this scope the gate's- // "no chat context → allow straight through" branch- // (`approval/gate.rs:219-231`) silently bypasses every `Prompt`-class- // tool call, voiding the `supervised` autonomy tier on the channel.- let llm_result = tokio::time::timeout(Duration::from_secs(ctx.message_timeout_secs), async {- if channel_has_approval_surface(&msg.channel) {- let approval_ctx = crate::security::approval::ApprovalChatContext {- thread_id: history_key.clone(),- client_id: msg.channel.clone(),- request_id: Some(msg.id.clone()),- };- crate::security::approval::APPROVAL_CHAT_CONTEXT- .scope(approval_ctx, agent_call)- .await- } else {- agent_call.await- }- })- .await;+ let llm_result =- tokio::time::timeout(Duration::from_secs(ctx.message_timeout_secs), agent_call)- .await;++ tokio::time::timeout(Duration::from_secs(ctx.message_timeout_secs), agent_call).await;// Wait for draft updater to finishif let Some(handle) = draft_updater {diff --cc crates/openhuman-core/src/core/runtime/context.rsindex f7d269bd11,63eb9e7425..beef7d1a38--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@@ -524,8 -531,14 +531,16 @@@ impl CoreContext/// Run `fut` with `ctx` as the ambient [`CoreContext::current`]: dispatch wraps/// each handler in this, and multi-tenant hosts pass the tenant's context.+ ///+ /// A turn's origin survives a change of context: `ctx` without an origin of+ /// its own, scoped inside a turn that has one (an embedded agent's derived+ /// context replacing the caller's, say), keeps that turn's origin. Dropping+ /// it would turn a labelled turn into an unlabelled one the approval gate+ /// refuses.pub async fn scope<F: Future>(ctx: Arc<CoreContext>, fut: F) -> F::Output {- CURRENT_CONTEXT.scope(ctx, fut).await- CURRENT_CONTEXT.scope(Self::keeping_turn_origin(ctx), fut).await++ CURRENT_CONTEXT++ .scope(Self::keeping_turn_origin(ctx), fut)++ .await}/// [`scope`](Self::scope) for a synchronous closure.diff --cc crates/openhuman-core/src/core/runtime/context_test_support.rsindex 0000000000,e9d610fce7..741aca0b3amode 000000,100644..100644--- a/crates/openhuman-core/src/core/runtime/context_test_support.rs+++ b/crates/openhuman-core/src/core/runtime/context_test_support.rs@@@ -1,0 -1,78 +1,81 @@@+ //! Test-only constructors for [`CoreContext`]: a context with an explicit domain+ //! set, workspace or embedder config, without the full [`CoreContext::init`] boot.++ use super::*;++ impl CoreContext {+ /// Test-only constructor: build a context with an explicit+ /// [`DomainSet`](crate::core::runtime::DomainSet) and optional workspace, so+ /// cross-module tests (e.g. `core::all`'s registry filter) can exercise the+ /// ambient DomainSet gate without going through the full [`CoreContext::init`]+ /// boot sequence.+ pub(crate) fn for_test(+ domains: crate::core::runtime::DomainSet,+ workspace_dir: Option<std::path::PathBuf>,+ ) -> Arc<CoreContext> {+ Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {+ workspace_dir,+ }))),+ domains,+ tool_groups: Default::default(),+ components: Default::default(),+ embedder_config: None,+ user_skill_roots: true,+ backend_transport: None,+ turn_origin: None,+ channel_thread: None,+ session_agent: None,+ profile: None,+ agent: Default::default(),+ bare: false,+ })+ }++ /// Test-only: given `[components]` switches.+ pub(crate) fn for_test_with_components(c: crate::core::runtime::ComponentSet) -> Arc<Self> {- let mut ctx = Arc::try_unwrap(Self::for_test(crate::core::runtime::DomainSet::full(), None))- .ok()- .unwrap();++ let mut ctx = Arc::try_unwrap(Self::for_test(++ crate::core::runtime::DomainSet::full(),++ None,++ ))++ .ok()++ .unwrap();+ ctx.components = c;+ Arc::new(ctx)+ }++ /// Test-only constructor that carries an embedder-supplied config, so a+ /// cross-module test can exercise the `load_config_with_timeout()` read+ /// path (which prefers [`CoreContext::current_embedder_config`]) without a+ /// full boot or a racy on-disk `config.toml`.+ ///+ /// Distinct from [`CoreContext::for_test`] — which always sets+ /// `embedder_config: None` — so the ~30 existing `for_test` call sites are+ /// unaffected. The workspace binding is anchored to the config's+ /// `workspace_dir`, matching how [`CoreContext::init`] wires an+ /// embedder-supplied config.+ pub(crate) fn for_test_with_config(+ domains: crate::core::runtime::DomainSet,+ config: crate::config::Config,+ ) -> Arc<CoreContext> {+ Arc::new(CoreContext {+ host_kind: HostKind::Cli,+ workspace_binding: RwLock::new(Arc::new(RwLock::new(WorkspaceBinding {+ workspace_dir: Some(config.workspace_dir.clone()),+ }))),+ domains,+ tool_groups: Default::default(),+ components: Default::default(),+ embedder_config: Some(config),+ user_skill_roots: true,+ backend_transport: None,+ turn_origin: None,+ channel_thread: None,+ session_agent: None,+ profile: None,+ agent: Default::default(),+ bare: false,+ })+ }+ }diff --cc crates/openhuman-core/src/flows/tinyflows/caps/code.rsindex 4311aa2e02,2fc1a4bed0..63b9c37264--- a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs@@@ -67,8 -70,9 +70,14 @@@ impl CodeRunner for OpenHumanCodelet action = json!({ "language": format!("{language:?}"), "source": source });let summary = crate::security::approval::summarize_action("flows_code", &action);let redacted = crate::security::approval::redact_args(&action);-- let (gate_outcome, audit_id) =- gate_call_for_tier(tier_decision, "flows_code", &summary, redacted).await;- gate_call_for_tier(&self.approval, tier_decision, "flows_code", &summary, redacted)- .await;++ let (gate_outcome, audit_id) = gate_call_for_tier(++ &self.approval,++ tier_decision,++ "flows_code",++ &summary,++ redacted,++ )++ .await;if let crate::security::approval::GateOutcome::Deny { reason } = gate_outcome {return Err(EngineError::Capability(reason));}diff --cc crates/openhuman-core/src/flows/tinyflows/caps/http.rsindex d7ba629b68,70ab5bd416..04903a9549--- a/crates/openhuman-core/src/flows/tinyflows/caps/http.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/http.rs@@@ -181,7 -184,8 +184,7 @@@ impl HttpClient for OpenHumanHttplet summary = crate::security::approval::summarize_action(TOOL_NAME, &request);let redacted = crate::security::approval::redact_args(&request);let (outcome, audit_id) =- gate_call_for_tier(tier_decision, TOOL_NAME, &summary, redacted).await;- gate_call_for_tier(&self.approval, tier_decision, TOOL_NAME, &summary, redacted)- .await;++ gate_call_for_tier(&self.approval, tier_decision, TOOL_NAME, &summary, redacted).await;if let crate::security::approval::GateOutcome::Deny { reason } = outcome {return Err(EngineError::Capability(reason));}diff --cc crates/openhuman-core/src/flows/tinyflows/caps/tools/composio.rsindex b84254a681,53b09cfadf..027147e7a7--- a/crates/openhuman-core/src/flows/tinyflows/caps/tools/composio.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tools/composio.rs@@@ -172,7 -172,7 +172,8 @@@ impl ToolBackend for ComposioToolBackenlet (outcome, audit_id) = if tier_decision == GateDecision::Allow {(crate::security::approval::GateOutcome::Allow, None)} else {- super::super::gate_call_for_tier(tier_decision, slug, &summary, redacted).await- super::super::gate_call_for_tier(ctx.approval, tier_decision, slug, &summary, redacted).await++ super::super::gate_call_for_tier(ctx.approval, tier_decision, slug, &summary, redacted)++ .await};if let crate::security::approval::GateOutcome::Deny { reason } = outcome {tracing::warn!(diff --cc crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rsindex 26c8a60918,06cb06d465..e7ca8050ed--- a/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs@@@ -48,8 -48,9 +48,14 @@@ impl ToolBackend for NativeToolBackendlet tier_decision = super::super::enforce_node_tier_gate(ctx.security, class, "tool_call")?;let summary = crate::security::approval::summarize_action(tool_name, &args);let redacted = crate::security::approval::redact_args(&args);-- let (outcome, audit_id) =- super::super::gate_call_for_tier(tier_decision, tool_name, &summary, redacted).await;- super::super::gate_call_for_tier(ctx.approval, tier_decision, tool_name, &summary, redacted)- .await;++ let (outcome, audit_id) = super::super::gate_call_for_tier(++ ctx.approval,++ tier_decision,++ tool_name,++ &summary,++ redacted,++ )++ .await;if let crate::security::approval::GateOutcome::Deny { reason } = outcome {return Err(EngineError::Capability(reason));}diff --cc crates/openhuman-core/src/flows/tinyflows/memory_adapter.rsindex 42a01b97a8,5d1db2d475..e82623af8e--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs@@@ -142,8 -144,9 +144,14 @@@ impl OpenHumanMemorylet tier_decision = enforce_node_tier_gate(&self.security, CommandClass::Write, op)?;let summary = summarize_action(&tool_name, action);let redacted = redact_args(action);-- let (outcome, audit_id) =- gate_call_for_tier(tier_decision, &tool_name, &summary, redacted).await;- gate_call_for_tier(&self.approval, tier_decision, &tool_name, &summary, redacted)- .await;++ let (outcome, audit_id) = gate_call_for_tier(++ &self.approval,++ tier_decision,++ &tool_name,++ &summary,++ redacted,++ )++ .await;if let GateOutcome::Deny { reason } = outcome {tracing::warn!(target: "flows", op, "{LOG_PREFIX} write: approval gate denied");return Err(EngineError::Capability(reason));diff --cc crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rsindex 2c79ced231,95909f9a84..eb058a1499--- a/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs+++ b/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs@@@ -697,9 -697,7 +697,10 @@@ async fn managed_construction_ledger_cobuild(&EgressLedger::none());let sentinel = "egress-ledger-factory-sentinel";- crate::security::egress::emit_external_transfer(None, crate::security::egress::EgressDescriptor::network_fetch(sentinel));+ crate::security::egress::emit_external_transfer(++ None,+ crate::security::egress::EgressDescriptor::network_fetch(sentinel),+ );let mut disclosures = 0;loop {match rx.recv().await {diff --cc crates/openhuman-core/src/integrations/client_api_key_tests.rsindex a42b722cd6,733517af99..1106a5392b--- a/crates/openhuman-core/src/integrations/client_api_key_tests.rs+++ b/crates/openhuman-core/src/integrations/client_api_key_tests.rs@@@ -44,7 -44,7 +44,10 @@@ async fn json_requests_send_the_api_keylet client = api_key_client(start_mock_backend(app).await);assert!(client.uses_api_key());client- .get::<serde_json::Value>("/agent-integrations/composio/connections")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/connections")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/connections",++ ).await.expect("an API-key client reaches composio");@@@ -69,7 -69,7 +72,10 @@@ async fn binary_download_sends_the_api_);let client = api_key_client(start_mock_backend(app).await);let (bytes, _, _) = client- .get_bytes("/agent-integrations/file-storage/files/f1/download")- .get_bytes(&Default::default(), "/agent-integrations/file-storage/files/f1/download")++ .get_bytes(++ &Default::default(),++ "/agent-integrations/file-storage/files/f1/download",++ ).await.expect("download with an API key");assert_eq!(&bytes[..], b"bytes");@@@ -108,7 -108,7 +114,10 @@@ async fn presigned_download_redirect_do);let client = api_key_client(start_mock_backend(backend).await);let (bytes, _, _) = client- .get_bytes("/agent-integrations/file-storage/files/f1/download")- .get_bytes(&Default::default(), "/agent-integrations/file-storage/files/f1/download")++ .get_bytes(++ &Default::default(),++ "/agent-integrations/file-storage/files/f1/download",++ ).await.unwrap();assert_eq!(&bytes[..], b"stored bytes");diff --cc crates/openhuman-core/src/integrations/client_error_propagation_tests.rsindex d557e35c85,e3d6615bc2..e394972079--- a/crates/openhuman-core/src/integrations/client_error_propagation_tests.rs+++ b/crates/openhuman-core/src/integrations/client_error_propagation_tests.rs@@@ -182,14 -182,14 +182,22 @@@ async fn verb_methods_block_user_data_eassert_blocked("upload_multipart",client- .upload_multipart::<serde_json::Value>(path, reqwest::multipart::Form::new())- .upload_multipart::<serde_json::Value>(&Default::default(), path, reqwest::multipart::Form::new())++ .upload_multipart::<serde_json::Value>(++ &Default::default(),++ path,++ reqwest::multipart::Form::new(),++ ).await.unwrap_err().to_string(),);assert_blocked("get_bytes",- client.get_bytes(path).await.unwrap_err().to_string(),- client.get_bytes(&Default::default(), path).await.unwrap_err().to_string(),++ client++ .get_bytes(&Default::default(), path)++ .await++ .unwrap_err()++ .to_string(),);}@@@ -249,7 -250,7 +258,10 @@@ async fn verb_methods_never_expose_admi);assert_blocked("get_bytes",- client.get_bytes("/webhooks/core").await.unwrap_err(),- client.get_bytes(&Default::default(), "/webhooks/core").await.unwrap_err(),++ client++ .get_bytes(&Default::default(), "/webhooks/core")++ .await++ .unwrap_err(),);}@@@ -391,7 -394,7 +405,10 @@@ async fn local_only_rejects_user_data_v// gate and DOES reach transport (surfaces the mock's 403) — proving the// gate is selective, not a blanket network kill.let err = client- .get::<serde_json::Value>("/agent-integrations/composio/connections")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/connections")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/connections",++ ).await.expect_err("control-plane reaches transport and surfaces the mock 403");let msg = format!("{err:#}");@@@ -416,7 -419,7 +433,10 @@@ async fn get_403_propagates_backend_errlet base = start_mock_backend(app).await;let client = client_for(base);let err = client- .get::<serde_json::Value>("/agent-integrations/composio/connections")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/connections")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/connections",++ ).await.expect_err("403 must surface as Err");let msg = format!("{err:#}");diff --cc crates/openhuman-core/src/integrations/client_session_expiry_tests.rsindex be8f82b893,dbca617357..4c580411a9--- a/crates/openhuman-core/src/integrations/client_session_expiry_tests.rs+++ b/crates/openhuman-core/src/integrations/client_session_expiry_tests.rs@@@ -94,7 -95,7 +95,10 @@@ async fn get_401_session_jwt_classifieslet base = start_mock_backend(app).await;let client = client_for(base);let err = client- .get::<serde_json::Value>("/agent-integrations/composio/connections")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/connections")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/connections",++ ).await.expect_err("401 must surface as Err");let msg = format!("{err:#}");@@@ -136,7 -137,7 +140,10 @@@ async fn non_401_4xx_does_not_classify_let base = start_mock_backend(app).await;let client = client_for(base);let err = client- .get::<serde_json::Value>("/agent-integrations/composio/connections")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/connections")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/connections",++ ).await.expect_err("403 must surface as Err");let msg = format!("{err:#}");@@@ -246,7 -247,7 +253,10 @@@ async fn get_401_composio_triggers_keeplet base = start_mock_backend(app).await;let client = client_for(base);let err = client- .get::<serde_json::Value>("/agent-integrations/composio/triggers/available?toolkit=gmail")- .get::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/triggers/available?toolkit=gmail")++ .get::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/triggers/available?toolkit=gmail",++ ).await.expect_err("401 must surface as Err");let msg = format!("{err:#}");diff --cc crates/openhuman-core/src/integrations/client_tests.rsindex 331de08777,25e1e7f87e..19623e2618--- a/crates/openhuman-core/src/integrations/client_tests.rs+++ b/crates/openhuman-core/src/integrations/client_tests.rs@@@ -86,10 -86,10 +86,17 @@@ async fn product_identity_seen_by_backelet client = client_for(base);let sdk_result = client- .post::<serde_json::Value>("/agent-integrations/composio/execute", &json!({}))- .post::<serde_json::Value>(&Default::default(), "/agent-integrations/composio/execute", &json!({}))++ .post::<serde_json::Value>(++ &Default::default(),++ "/agent-integrations/composio/execute",++ &json!({}),++ ).await;let download_result = client- .get_bytes("/agent-integrations/file-storage/files/f1/download")- .get_bytes(&Default::default(), "/agent-integrations/file-storage/files/f1/download")++ .get_bytes(++ &Default::default(),++ "/agent-integrations/file-storage/files/f1/download",++ ).await;sdk_result.expect("mock backend returns a success envelope");diff --cc crates/openhuman-core/src/integrations/composio/tools/execute.rsindex 98e141a562,8259a27fc8..e8f8d5edfe--- a/crates/openhuman-core/src/integrations/composio/tools/execute.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/execute.rs@@@ -110,11 -110,14 +110,16 @@@ impl Tool for ComposioExecuteTool_options: ToolCallOptions,context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {-- let (config, outcome) = Box::pin(self.execute_unredacted(-- args,-- sandbox_mode_for_tool(context),-- task_recency_window_for_tool(context),- crate::agent::tinyagents::host::run_context::approval_for_tool(context)- .chat- .as_ref(),-- ))++ let (config, outcome) = Box::pin(++ self.execute_unredacted(++ args,++ sandbox_mode_for_tool(context),++ task_recency_window_for_tool(context),++ crate::agent::tinyagents::host::run_context::approval_for_tool(context)++ .chat++ .as_ref(),++ ),++ ).await;redact_composio_outcome(&config, outcome)}diff --cc crates/openhuman-core/src/integrations/composio/tools_metadata_and_sandbox_tests.rsindex c2fd7ef3da,49d066ce54..4c3fbc01e4--- a/crates/openhuman-core/src/integrations/composio/tools_metadata_and_sandbox_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/tools_metadata_and_sandbox_tests.rs@@@ -188,11 -198,7 +198,12 @@@ async fn connect_tool_validates_before_client_id: "c-test".into(),request_id: None,};- let result = APPROVAL_CHAT_CONTEXT- .scope(- ctx,- tool.execute(serde_json::json!({ "toolkit": "google_drive" })),- let result = tool.execute_with_context(serde_json::json!({ "toolkit": "google_drive" }), tinytools::ToolCallOptions::default(), Some(&chat_tool_context(ctx)))++ let result = tool++ .execute_with_context(++ serde_json::json!({ "toolkit": "google_drive" }),++ tinytools::ToolCallOptions::default(),++ Some(&chat_tool_context(ctx)),+ ).await.unwrap();assert!(result.is_error);diff --cc crates/openhuman-core/src/integrations/file_storage/tools/list.rsindex 1dad2285a4,ea731dfe8b..9e0b46161b--- a/crates/openhuman-core/src/integrations/file_storage/tools/list.rs+++ b/crates/openhuman-core/src/integrations/file_storage/tools/list.rs@@@ -41,8 -41,29 +41,33 @@@ impl Tool for StorageListFilesTool}async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {+ self.run(_args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ _args: Value,+ _options: tinytools::ToolCallOptions,+ context: Option<&dyn tinytools::ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);+ self.run(_args, &approval).await+ }+ }++ impl StorageListFilesTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ _args: Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {tracing::debug!("[file_storage] listing files");- match self.client.get::<ListFilesResponse>(FILES_PATH).await {- match self.client.get::<ListFilesResponse>(approval, FILES_PATH).await {++ match self++ .client++ .get::<ListFilesResponse>(approval, FILES_PATH)++ .await++ {Ok(resp) => {let mut lines = vec![format!("{} file(s), using {} of {} bytes:",diff --cc crates/openhuman-core/src/integrations/file_storage/tools/visibility.rsindex c157e99f70,49b02a00c6..8e83b47b19--- a/crates/openhuman-core/src/integrations/file_storage/tools/visibility.rs+++ b/crates/openhuman-core/src/integrations/file_storage/tools/visibility.rs@@@ -84,7 -105,7 +105,8 @@@ impl StorageSetVisibilityTooltracing::debug!("[file_storage] setting visibility={visibility} for file_id={file_id}");match self.client- .patch::<FileMeta>(approval,+ .patch::<FileMeta>(++ approval,&file_path(&file_id, ""),&json!({ "visibility": visibility }),)diff --cc crates/openhuman-core/src/integrations/tools/stock_prices.rsindex a0ea510f51,220db092d3..6aea5592e3--- a/crates/openhuman-core/src/integrations/tools/stock_prices.rs+++ b/crates/openhuman-core/src/integrations/tools/stock_prices.rs@@@ -188,7 -209,7 +209,11 @@@ impl StockQuoteTooltracing::info!("[stock_quote] symbol={}", symbol);let body = json!({ "symbol": symbol });- match self.client.post::<QuoteResponse>(PATH_QUOTE, &body).await {- match self.client.post::<QuoteResponse>(approval, PATH_QUOTE, &body).await {++ match self++ .client++ .post::<QuoteResponse>(approval, PATH_QUOTE, &body)++ .await++ {Ok(resp) => {let q = &resp.quote;let mut out = format!(diff --cc crates/openhuman-core/src/media/generation/artifact_tool.rsindex af81d1ce5f,a85e2ccc06..55011d7ab0--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs@@@ -65,7 -63,9 +66,8 @@@ pub struct MediaArtifactTool<T: Tool>per_call: Option<PerCallInner<T>>,}- type PerCallInner<T> = std::sync::Arc<dyn Fn(ProgressFn) -> T + Send + Sync>;-type PerCallInner<T> = std::sync::Arc<- dyn Fn(ProgressFn, Option<&ApprovalChatContext>) -> T + Send + Sync,->;++type PerCallInner<T> =++ std::sync::Arc<dyn Fn(ProgressFn, Option<&ApprovalChatContext>) -> T + Send + Sync>;impl<T: Tool> MediaArtifactTool<T> {/// `kind` is the artifact category to file every generated output@@@ -88,17 -87,9 +90,18 @@@}}+ /// Reads generated outputs addressed by blob key from the media tool's+ /// backing store. This keeps TinyAgents' blob-backed output contract+ /// separate from the host's visible Files-folder artifact store.+ #[must_use]+ pub fn with_blobs(mut self, blobs: Arc<dyn tinystoragedrivers::BlobStore>) -> Self {+ self.blobs = Some(blobs);+ self+ }+/// Run each call on a tool built by `build` around that call's poll- /// observer, so a long job's polled state reaches that call's heartbeat.+ /// observer and chat routing, so a long job's polled state reaches that+ /// call's heartbeat and its egress disclosures reach that call's chat.#[must_use]pub fn with_per_call_inner(mut self,@@@ -154,8 -146,8 +158,16 @@@else {continue;};- self.file_one(entry, &src_path, args, index, total, call_id.as_deref())- self.file_one(entry, &src_path, args, index, total, call_id.as_deref(), chat)-- .await;++ self.file_one(++ entry,++ &src_path,++ args,++ index,++ total,++ call_id.as_deref(),++ chat,++ )++ .await;}result}@@@ -196,28 -190,23 +210,35 @@@return;}};- match move_or_copy(src, &dest).await {+ let stored = if src.is_absolute() {+ move_or_copy(src, &dest).await+ } else {+ self.file_blob(src, &dest).await+ };+ match stored {Ok(size_bytes) => {- match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {+ match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await {Ok(updated) => {if let Some(obj) = entry.as_object_mut() {obj.insert("artifact_id".into(), json!(updated.id));}}Err(err) => {- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err)- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err, chat)-- .await;++ let _ = fail_artifact(++ &self.workspace_dir,++ &self.files_dir,++ &meta.id,++ &err,++ chat,++ )++ .await;set_artifact_error(entry, &err);}}}Err(err) => {- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err).await;- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err, chat).await;++ let _ =++ fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err, chat).await;tracing::warn!(target: "media_generation",err = %err,diff --cc crates/openhuman-core/src/media/generation/provider.rsindex 9a09259749,b5bb1f4df6..719412a1a6--- a/crates/openhuman-core/src/media/generation/provider.rs+++ b/crates/openhuman-core/src/media/generation/provider.rs@@@ -37,6 -38,10 +38,13 @@@ use crate::security::credentials::sessi/// Backend route prefix that proxies OpenRouter's media API.pub const OPENROUTER_PROXY_PATH: &str = "/agent-integrations/openrouter";+ /// Rebuilds the generators so their egress disclosures reach `chat`.-type GeneratorRouter =- Arc<dyn Fn(Option<ApprovalChatContext>) -> (Arc<dyn ImageGenerator>, Arc<dyn VideoGenerator>) + Send + Sync>;++type GeneratorRouter = Arc<++ dyn Fn(Option<ApprovalChatContext>) -> (Arc<dyn ImageGenerator>, Arc<dyn VideoGenerator>)++ + Send++ + Sync,++>;+/// The image and video generators for this process.pub struct MediaGenerators {/// Image generation.diff --cc crates/openhuman-core/src/media/generation/provider_tests.rsindex 0000000000,318a6f4fd8..60343427b4mode 000000,100644..100644--- a/crates/openhuman-core/src/media/generation/provider_tests.rs+++ b/crates/openhuman-core/src/media/generation/provider_tests.rs@@@ -1,0 -1,83 +1,82 @@@+ use super::*;+ use crate::core::events::DomainEvent;++ fn guard(chat: Option<ApprovalChatContext>) -> Guard {+ Guard {+ config: Arc::new(Config::default()),+ chat,+ }+ }++ async fn disclosed_routing(+ rx: &mut tinybus::events::EventReceiver<DomainEvent>,+ service: &str,+ ) -> (Option<String>, Option<String>) {+ loop {+ match rx.recv().await {+ Some(DomainEvent::ExternalTransferPending {+ descriptor,+ thread_id,+ client_id,+ ..+ }) if descriptor.service == service => return (thread_id, client_id),+ Some(_) => continue,+ None => panic!("the bus closed before the disclosure arrived"),+ }+ }+ }++ /// A media request discloses its egress to the chat the call was built for, and+ /// two guards built for different chats do not share a destination.+ #[tokio::test]+ async fn a_guard_discloses_to_the_chat_it_was_built_for() {+ crate::core::bus::init().await.expect("bus init");+ let mut rx = crate::core::bus::BUS.get().unwrap().receiver();++ let chat_a = ApprovalChatContext {+ thread_id: "thread-media-a".into(),+ client_id: "client-media-a".into(),+ request_id: None,+ };+ let chat_b = ApprovalChatContext {+ thread_id: "thread-media-b".into(),+ client_id: "client-media-b".into(),+ request_id: None,+ };+ let (a, b, none) = (guard(Some(chat_a)), guard(Some(chat_b)), guard(None));+ a.admit("videos/probe-a").unwrap();+ tokio::task::yield_now().await;+ b.admit("videos/probe-b").unwrap();+ none.admit("videos/probe-none").unwrap();++ let service = |route: &str| format!("{OPENROUTER_PROXY_PATH}/{route}");+ assert_eq!(+ disclosed_routing(&mut rx, &service("videos/probe-a")).await,+ (Some("thread-media-a".into()), Some("client-media-a".into()))+ );+ assert_eq!(+ disclosed_routing(&mut rx, &service("videos/probe-b")).await,+ (Some("thread-media-b".into()), Some("client-media-b".into()))+ );+ assert_eq!(+ disclosed_routing(&mut rx, &service("videos/probe-none")).await,+ (None, None)+ );+ }++ #[test]+ fn generators_without_a_router_are_returned_as_they_are() {+ use tinyagents_harness::tinyinference_image::MockImageGenerator;+ use tinyagents_harness::tinyinference_video::{MockVideoGenerator, MockVideoScript};+ let generators = MediaGenerators::new(+ Arc::new(MockImageGenerator::new()),+ Arc::new(MockVideoGenerator::new(MockVideoScript::delivers())),+ );+ let routed = generators.routed(Some(&ApprovalChatContext {+ thread_id: "t".into(),+ client_id: "c".into(),+ request_id: None,+ }));+ assert!(Arc::ptr_eq(&generators.image, &routed.image));+ assert!(Arc::ptr_eq(&generators.video, &routed.video));+ }-diff --cc crates/openhuman-core/src/media/generation/tools.rsindex 7e51eaf0db,e19036deb7..9a9bc3ffa2--- a/crates/openhuman-core/src/media/generation/tools.rs+++ b/crates/openhuman-core/src/media/generation/tools.rs@@@ -73,10 -73,16 +73,17 @@@ pub fn media_tools_fromvideo_wait: WaitPolicy,) -> Vec<Box<dyn Tool>> {let files = files_dir.into();- let MediaGenerators { image, video } = generators;+ let generators = Arc::new(generators);let output = MediaOutput::new(action_dir).with_reference_policy(reference_policy(action_dir, workspace_dir));+ let output_blobs = Arc::clone(&output.blobs);+ let image_tool = |image: &Arc<dyn ImageGenerator>| {+ GenerateImageTool::new(Arc::clone(image), output.clone())+ .with_name(IMAGE_TOOL_NAME)+ .with_description(IMAGE_DESCRIPTION)+ .with_permission_level(PermissionLevel::Execute)+ .with_category(ToolCategory::Workflow)+ };let tools: Vec<Box<dyn Tool>> = vec![Box::new(MediaArtifactTool::new(@@@ -89,7 -91,20 +92,21 @@@workspace_dir.to_path_buf(),files.clone(),)- .with_blobs(Arc::clone(&output_blobs)),++ .with_blobs(Arc::clone(&output_blobs))+ // A tool per call, around generators that disclose to that call's+ // chat.+ .with_per_call_inner({+ let generators = Arc::clone(&generators);+ let output = output.clone();+ move |_observer, chat| {+ let routed = generators.routed(chat);+ GenerateImageTool::new(routed.image, output.clone())+ .with_name(IMAGE_TOOL_NAME)+ .with_description(IMAGE_DESCRIPTION)+ .with_permission_level(PermissionLevel::Execute)+ .with_category(ToolCategory::Workflow)+ }+ }),),Box::new(MediaArtifactTool::new(@@@ -98,12 -113,16 +115,17 @@@workspace_dir.to_path_buf(),files,)+ .with_blobs(output_blobs).with_per_call_inner({- let video = Arc::clone(&video);+ let generators = Arc::clone(&generators);let output = output.clone();- move |observer| {- video_tool(&video, &output, video_wait.clone().with_progress(observer))+ move |observer, chat| {+ let routed = generators.routed(chat);+ video_tool(+ &routed.video,+ &output,+ video_wait.clone().with_progress(observer),+ )}}),),diff --cc crates/openhuman-core/src/modules/wallet_host.rsindex ee92731562,9a5312b474..fc665e5575--- a/crates/openhuman-core/src/modules/wallet_host.rs+++ b/crates/openhuman-core/src/modules/wallet_host.rs@@@ -677,9 -692,10 +692,8 @@@ impl WalletHost&self,request: AuthorizeX402PaymentRequest,) -> tinybus::Result<HostResponse> {- let owner_matches = crate::security::approval::APPROVAL_CHAT_CONTEXT- .try_with(|context| x402_request_owner_matches(&request, context))- .unwrap_or(false);- let owner_matches = x402_request_owner_matches(- &request,- crate::agent::turn_origin::current().as_ref(),- );++ let owner_matches =++ x402_request_owner_matches(&request, crate::agent::turn_origin::current().as_ref());let approved = if owner_matches {if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {matches!(diff --cc crates/openhuman-core/src/sandbox/shell_exec.rsindex e2d27c37c4,f83b792ff8..6d14d2ec17--- a/crates/openhuman-core/src/sandbox/shell_exec.rs+++ b/crates/openhuman-core/src/sandbox/shell_exec.rs@@@ -94,7 -97,7 +97,10 @@@ pub(crate) static USE_FIXTURE: std::syn/// Run `run` through the module and collect its output.////// A worker owns cancellation and resource cleanup if the caller drops its wait.- pub(crate) async fn run(config: &Config, run: NativeShellRun) -> anyhow::Result<SandboxExecResult> {-pub(crate) async fn run(config: &Config, mut run: NativeShellRun) -> anyhow::Result<SandboxExecResult> {++pub(crate) async fn run(++ config: &Config,++ mut run: NativeShellRun,++) -> anyhow::Result<SandboxExecResult> {#[cfg(test)]if !run.is_jailed() && USE_FIXTURE.load(std::sync::atomic::Ordering::SeqCst) {let _ = config;diff --cc crates/openhuman-core/src/security/approval/gate_tests.rsindex e57b71a540,46c73f565a..e8eb394d6d--- a/crates/openhuman-core/src/security/approval/gate_tests.rs+++ b/crates/openhuman-core/src/security/approval/gate_tests.rs@@@ -212,5 -212,7 +212,7 @@@ mod subagent_testsmod tenant_tests;#[path = "gate_triage_tests.rs"]mod triage_tests;-#[path = "gate_turn_context_tests.rs"]-mod turn_context_tests;#[path = "gate_ttl_and_triage_tests.rs"]mod ttl_and_triage_tests;++#[path = "gate_turn_context_tests.rs"]++mod turn_context_tests;diff --cc crates/openhuman-core/src/security/egress/emit_tests.rsindex 849b7a249e,abcd36e9d9..7fffe44e59--- a/crates/openhuman-core/src/security/egress/emit_tests.rs+++ b/crates/openhuman-core/src/security/egress/emit_tests.rs@@@ -58,8 -58,8 +58,11 @@@ async fn local_transfer_does_not_publis// A local (non-external) transfer must NOT emit; a following external one// must. If we reach the sentinel without having seen the local marker, the// local transfer was correctly suppressed.- emit_external_transfer(EgressDescriptor::inference("ollama", local_marker, false));- emit_external_transfer(EgressDescriptor::network_fetch(sentinel_marker));- emit_external_transfer(None, EgressDescriptor::inference("ollama", local_marker, false));++ emit_external_transfer(++ None,++ EgressDescriptor::inference("ollama", local_marker, false),++ );+ emit_external_transfer(None, EgressDescriptor::network_fetch(sentinel_marker));loop {match rx.recv().await {diff --cc crates/openhuman-core/src/tools/impl/document/mod.rsindex 3fddd85825,ed3b09ceb3..58b8e9025a--- a/crates/openhuman-core/src/tools/impl/document/mod.rs+++ b/crates/openhuman-core/src/tools/impl/document/mod.rs@@@ -267,7 -291,7 +291,14 @@@ impl DocumentTool.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let reason = format!("failed to write generated document ({filename}): {err}");- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason, chat).await;++ let _ = fail_artifact(++ &self.workspace_dir,++ &self.files_dir,++ &meta.id,++ &reason,++ chat,++ )++ .await;tracing::warn!(target: "document",err = %err,@@@ -279,7 -303,7 +310,8 @@@}let size_bytes = bytes.len() as u64;- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await {++ let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await++ {Ok(updated) => updated,Err(err) => {let reason = format!("failed to finalize artifact: {err}");@@@ -288,8 -312,8 +320,14 @@@// stuck `Pending` spinner. Fail-artifact errors are// swallowed — they can only recur if the same ledger backend// is unavailable.-- let _ =- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason, chat).await;++ let _ = fail_artifact(++ &self.workspace_dir,++ &self.files_dir,++ &meta.id,++ &reason,++ chat,++ )++ .await;tracing::warn!(target: "document",err = %err,diff --cc crates/openhuman-core/src/tools/impl/network/host.rsindex 21c5bb3b59,fc752f12d2..fb782d6def--- a/crates/openhuman-core/src/tools/impl/network/host.rs+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@@ -55,6 -63,23 +63,17 @@@ pub fn http_request_toolallowed_domains: Vec<String>,max_response_size: usize,timeout_secs: u64,+ ) -> HttpRequestTool {- http_request_tool_for(- gate,- None,- allowed_domains,- max_response_size,- timeout_secs,- )++ http_request_tool_for(gate, None, allowed_domains, max_response_size, timeout_secs)+ }++ /// [`http_request_tool`] whose x402 quotes are owned by `chat`.+ fn http_request_tool_for(+ gate: Arc<dyn NetGate>,+ chat: Option<&ApprovalChatContext>,+ allowed_domains: Vec<String>,+ max_response_size: usize,+ timeout_secs: u64,) -> HttpRequestTool {let tool = HttpRequestTool::new(gate,diff --cc crates/openhuman-core/src/tools/impl/presentation/mod.rsindex 2c87d642c9,64b2767337..3ddc69e7da--- a/crates/openhuman-core/src/tools/impl/presentation/mod.rs+++ b/crates/openhuman-core/src/tools/impl/presentation/mod.rs@@@ -383,7 -407,8 +407,14 @@@ impl PresentationTool.map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();let reason = format!("failed to write generated deck ({filename}): {err}");- let _ = fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason).await;- let _ =- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &reason, chat).await;++ let _ = fail_artifact(++ &self.workspace_dir,++ &self.files_dir,++ &meta.id,++ &reason,++ chat,++ )++ .await;tracing::warn!(target: "presentation",err = %err,@@@ -395,7 -420,7 +426,8 @@@}let size_bytes = bytes.len() as u64;- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {- let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await {++ let updated = match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await++ {Ok(updated) => updated,Err(err) => {let reason = format!("failed to finalize artifact: {err}");diff --cc crates/openhuman-core/src/tools/impl/system/install_tool_tests.rsindex fe76ff0cc1,d64089813c..2f72f6bbf6--- a/crates/openhuman-core/src/tools/impl/system/install_tool_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/install_tool_tests.rs@@@ -24,8 -34,7 +34,12 @@@ fn chat_tool_context#[tokio::test]async fn blocked_when_install_disabled() {let tool = InstallToolTool::new(policy(false, AutonomyLevel::Full));- let result = APPROVAL_CHAT_CONTEXT- .scope(chat_ctx(), tool.execute(json!({ "package": "jq" })))- let result = tool.execute_with_context(json!({ "package": "jq" }), tinytools::ToolCallOptions::default(), Some(&chat_tool_context(chat_ctx())))++ let result = tool++ .execute_with_context(++ json!({ "package": "jq" }),++ tinytools::ToolCallOptions::default(),++ Some(&chat_tool_context(chat_ctx())),++ ).await.unwrap();assert!(result.is_error);@@@ -35,8 -44,7 +49,12 @@@#[tokio::test]async fn blocked_when_readonly() {let tool = InstallToolTool::new(policy(true, AutonomyLevel::ReadOnly));- let result = APPROVAL_CHAT_CONTEXT- .scope(chat_ctx(), tool.execute(json!({ "package": "jq" })))- let result = tool.execute_with_context(json!({ "package": "jq" }), tinytools::ToolCallOptions::default(), Some(&chat_tool_context(chat_ctx())))++ let result = tool++ .execute_with_context(++ json!({ "package": "jq" }),++ tinytools::ToolCallOptions::default(),++ Some(&chat_tool_context(chat_ctx())),++ ).await.unwrap();assert!(result.is_error);@@@ -46,11 -54,7 +64,12 @@@#[tokio::test]async fn rejects_injection_in_package_name() {let tool = InstallToolTool::new(policy(true, AutonomyLevel::Full));- let result = APPROVAL_CHAT_CONTEXT- .scope(- chat_ctx(),- tool.execute(json!({ "package": "jq; rm -rf /" })),- let result = tool.execute_with_context(json!({ "package": "jq; rm -rf /" }), tinytools::ToolCallOptions::default(), Some(&chat_tool_context(chat_ctx())))++ let result = tool++ .execute_with_context(++ json!({ "package": "jq; rm -rf /" }),++ tinytools::ToolCallOptions::default(),++ Some(&chat_tool_context(chat_ctx())),+ ).await.unwrap();assert!(result.is_error);diff --cc crates/openhuman-core/src/tools/mod.rsindex 967fed8308,bca567cd96..0fbbdb0191--- a/crates/openhuman-core/src/tools/mod.rs+++ b/crates/openhuman-core/src/tools/mod.rs@@@ -3,6 -3,7 +3,7 @@@ pub(crate) mod native_opsmod native_ops_types;pub mod ops;pub mod orchestrator_tools;++pub(crate) mod per_call;pub(crate) mod policy_session;pub mod registry;pub mod rules;diff --cc crates/openhuman-core/src/web3/bridge/schemas.rsindex a6ee060c2b,836714f164..8700d0ff31--- a/crates/openhuman-core/src/web3/bridge/schemas.rs+++ b/crates/openhuman-core/src/web3/bridge/schemas.rs@@@ -94,9 -94,9 +94,14 @@@ pub fn schema(function: &str) -> Controfn handle_quote(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;- let quote = web3_service::quote(&config, methods::WEB3_BRIDGE_QUOTE, Value::Object(params))- let quote = web3_service::quote(&config, None, methods::WEB3_BRIDGE_QUOTE, Value::Object(params))-- .await-- .map_err(|error| error.to_string())?;++ let quote = web3_service::quote(++ &config,++ None,++ methods::WEB3_BRIDGE_QUOTE,++ Value::Object(params),++ )++ .await++ .map_err(|error| error.to_string())?;Outcome::new(quote, vec!["web3 bridge prepared".to_string()]).into_cli_compatible_json()})}diff --cc crates/openhuman-core/src/web3/dapp/schemas.rsindex dffb156e59,0ab785872e..f887631c45--- a/crates/openhuman-core/src/web3/dapp/schemas.rs+++ b/crates/openhuman-core/src/web3/dapp/schemas.rs@@@ -77,9 -77,9 +77,14 @@@ pub fn schema(function: &str) -> Controfn handle_call(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;- let quote = web3_service::quote(&config, methods::WEB3_DAPP_QUOTE, Value::Object(params))- let quote = web3_service::quote(&config, None, methods::WEB3_DAPP_QUOTE, Value::Object(params))-- .await-- .map_err(|error| error.to_string())?;++ let quote = web3_service::quote(++ &config,++ None,++ methods::WEB3_DAPP_QUOTE,++ Value::Object(params),++ )++ .await++ .map_err(|error| error.to_string())?;Outcome::new(quote, vec!["web3 dapp call prepared".to_string()]).into_cli_compatible_json()})}diff --cc crates/openhuman-core/src/web3/swap/schemas.rsindex 49884540db,da1ed011b4..b961f449c6--- a/crates/openhuman-core/src/web3/swap/schemas.rs+++ b/crates/openhuman-core/src/web3/swap/schemas.rs@@@ -105,9 -105,9 +105,14 @@@ fn unknown_schema() -> ControllerSchemfn handle_quote(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let config = config_rpc::load_config_with_timeout().await?;- let quote = web3_service::quote(&config, methods::WEB3_SWAP_QUOTE, Value::Object(params))- let quote = web3_service::quote(&config, None, methods::WEB3_SWAP_QUOTE, Value::Object(params))-- .await-- .map_err(|error| error.to_string())?;++ let quote = web3_service::quote(++ &config,++ None,++ methods::WEB3_SWAP_QUOTE,++ Value::Object(params),++ )++ .await++ .map_err(|error| error.to_string())?;Outcome::new(quote, vec!["web3 swap prepared".to_string()]).into_cli_compatible_json()})}diff --cc crates/openhuman-core/src/web3/wallet/schemas.rsindex 54df8c6ddb,7f428836a1..e50af0a1d9--- a/crates/openhuman-core/src/web3/wallet/schemas.rs+++ b/crates/openhuman-core/src/web3/wallet/schemas.rs@@@ -484,7 -484,7 +484,9 @@@ fn handle_prepare_transfer(params: Map<Box::pin(async move {let parsed: PrepareTransferParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- prepare_transfer(parsed).await?.into_cli_compatible_json()- prepare_transfer(parsed, None).await?.into_cli_compatible_json()++ prepare_transfer(parsed, None)++ .await?++ .into_cli_compatible_json()})}@@@ -492,7 -492,7 +494,9 @@@ fn handle_execute_prepared(params: Map<Box::pin(async move {let parsed: ExecutePreparedParams = serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))?;- execute_prepared(parsed).await?.into_cli_compatible_json()- execute_prepared(parsed, None).await?.into_cli_compatible_json()++ execute_prepared(parsed, None)++ .await?++ .into_cli_compatible_json()})}diff --cc crates/openhuman-core/src/web3/wallet/stub_tests.rsindex 8e85b30453,8e85b30453..9d888d4587--- a/crates/openhuman-core/src/web3/wallet/stub_tests.rs+++ b/crates/openhuman-core/src/web3/wallet/stub_tests.rs@@@ -21,13 -21,13 +21,16 @@@ async fn secret_material_is_disabled_er#[tokio::test]async fn prepare_transfer_is_disabled_error() {-- let err = prepare_transfer(PrepareTransferParams {-- chain: WalletChain::Solana,-- to_address: "recipient".to_string(),-- amount_raw: "1".to_string(),-- asset_symbol: None,-- evm_network: None,-- })++ let err = prepare_transfer(++ PrepareTransferParams {++ chain: WalletChain::Solana,++ to_address: "recipient".to_string(),++ amount_raw: "1".to_string(),++ asset_symbol: None,++ evm_network: None,++ },++ None,++ ).await.expect_err("no transfer can be prepared when the wallet is compiled out");assert_eq!(err, DISABLED_MSG);@@@ -35,10 -35,10 +38,13 @@@#[tokio::test]async fn execute_prepared_is_disabled_error() {-- let err = execute_prepared(ExecutePreparedParams {-- quote_id: "quote".to_string(),-- confirmed: true,-- })++ let err = execute_prepared(++ ExecutePreparedParams {++ quote_id: "quote".to_string(),++ confirmed: true,++ },++ None,++ ).await.expect_err("no prepared transfer can execute when the wallet is compiled out");assert_eq!(err, DISABLED_MSG);