The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(integrations): split client and file storage modules into submodules
Steven Enamakel87465d10b3b5
diff --git a/crates/openhuman-tinyhumans/src/integrations/client.rs b/crates/openhuman-tinyhumans/src/integrations/client.rsnew file mode 100644index 0000000000..5c54eaecf9--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client.rs@@ -0,0 +1,29 @@+//! Shared HTTP client for all integration tools.++pub mod budget_gate;+mod construct;+mod download;+mod errors;+mod pricing;+mod requests;++pub use construct::IntegrationClient;+pub use pricing::{build_client, pricing_for_config};++#[cfg(test)]+pub(crate) use errors::extract_error_detail;++// Brought into scope here (rather than only inside each submodule) purely so+// `#[cfg(test)] mod tests` below — and the `super::*` glob each test file+// does — can see them, mirroring what direct declaration in this file used+// to provide before the `include!` split was replaced with real submodules.+#[cfg(test)]+use construct::sanitize_backend_url;+#[cfg(test)]+use errors::is_composio_soft_auth_path;+#[cfg(test)]+use requests::{backend_egress_descriptor, enforce_backend_egress, managed_budget_applies_to_path};++#[cfg(test)]+#[path = "client_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/client/budget_gate.rs b/crates/openhuman-tinyhumans/src/integrations/client/budget_gate.rsnew file mode 100644index 0000000000..f4d00f2b5e--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/budget_gate.rs@@ -0,0 +1,307 @@+//! Managed-tool budget gate: refuses `/agent-integrations/*` calls once the+//! account's AI credits are exhausted, so a tool call never burns a backend+//! round-trip that the backend would reject anyway.+//!+//! Lives with the integrations client because that is its one consumer+//! (`requests.rs::ensure_budget_available`). The `team_get_usage` RPC lives in+//! `openhuman-tinyhumans` (`hosted::team::get_usage`, on the TinyHumans SDK)+//! and shares this module's failure backoff through+//! [`usage_with_failure_backoff`], so a persistent backend fault collapses to+//! about one probe a minute across both surfaces.+//!+//! The pre-call probe reads `GET /teams/me/usage` through+//! [`BackendClient`], so it rides the backend transport port. It resolves+//! the credential first and defers to the backend (allows the call) without+//! any request when there is no usable TinyHumans credential — the offline+//! local session, an API-less core, or a signed-out user.++use std::sync::RwLock;+use std::time::{Duration, Instant};++use serde_json::Value;++use crate::backend::BackendClient;+use crate::config::Config;+use crate::core::Outcome;+use crate::security::credentials::session_support::BackendCredential;++/// Fetch `GET /teams/me/usage` for the pre-call probe with an+/// already-resolved credential. `flatten_authed_error` keeps the typed 401 on+/// the `SESSION_EXPIRED` sentinel so a lapse never anchors the backoff.+async fn fetch_usage(config: &Config, credential: BackendCredential) -> Result<Value, String> {+ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let client = BackendClient::new(&api_url).map_err(|e| format!("{e:#}"))?;+ client+ .authed_json(&credential, reqwest::Method::GET, "/teams/me/usage", None)+ .await+ .map_err(crate::backend::flatten_authed_error)+}++/// How long a *failed* usage fetch is short-circuited before the backend is+/// probed again. `get_usage` is hammered from two surfaces — the frontend usage+/// poll (the `team_get_usage` RPC) and the pre-call budget gate+/// (`managed_tool_budget_exhausted`) — so a *persistent* non-2xx (a misrouted+/// `BACKEND_URL`, a backend outage) otherwise re-fires on every poll and every+/// managed tool call, re-reporting to Sentry each time. That is the+/// `/teams/me/usage` flood in GH #4153 (TAURI-RUST-BSF/-8C/-HDS/-HW1/-JJ5).+///+/// This window collapses a persistent fault to ~one backend probe (and so+/// ~one Sentry event) per minute per process while staying responsive: the+/// FIRST failure of a streak still hits the backend and still reports (real+/// signal preserved — backpressure, not silent drop), and any success clears+/// the window immediately. This is defense-in-depth flood control; the actual+/// misroute fix lives in `effective_backend_api_url` (see GH #4153).+const USAGE_FAILURE_BACKOFF: Duration = Duration::from_secs(60);++/// Process-global anchor of the most recent *reportable* `get_usage` failure.+/// Session-expiry (401) failures are intentionally NOT recorded here — they are+/// handled by their own RPC arm and must keep driving auth recovery.+struct UsageFailureCache {+ /// Backend identity + `Instant` of the last reported failure for that+ /// backend, if a streak is active. Keying on the backend URL means a+ /// changed `config.api_url` (e.g. after the user fixes a misrouted+ /// `BACKEND_URL`, or auth/session context that re-points the backend) no+ /// longer matches the stored key, so the next probe hits the new backend+ /// immediately instead of inheriting the old backend's backoff (GH #4153).+ inner: RwLock<Option<(String, Instant)>>,+}++impl UsageFailureCache {+ const fn new() -> Self {+ Self {+ inner: RwLock::new(None),+ }+ }++ /// True when a failure for `key` was recorded within `ttl` of `now`. A+ /// failure anchored under a different backend key never counts as fresh.+ fn is_fresh(&self, key: &str, now: Instant, ttl: Duration) -> bool {+ let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());+ guard+ .as_ref()+ .is_some_and(|(k, at)| k == key && now.duration_since(*at) < ttl)+ }++ /// Anchor a fresh failure for `key` (start / keep a streak).+ fn record(&self, key: &str, now: Instant) {+ let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());+ *guard = Some((key.to_string(), now));+ }++ /// Clear the streak — the endpoint recovered.+ fn clear(&self) {+ let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());+ *guard = None;+ }+}++static USAGE_FAILURE_CACHE: UsageFailureCache = UsageFailureCache::new();++/// Run a `/teams/me/usage` fetch behind the process-wide failure backoff.+///+/// `backend_key` identifies the backend (the effective API URL) so a failure+/// on one backend never suppresses a probe after the backend is re-pointed+/// (#4153). Shared by the pre-call probe here and the hosted `team_get_usage`+/// RPC, which supplies an SDK-backed `fetch`. Callers resolve the credential+/// *before* calling this, so a missing credential never opens a streak.+pub async fn usage_with_failure_backoff<F, Fut>(+ backend_key: &str,+ fetch: F,+) -> Result<Outcome<Value>, String>+where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<Output = Result<Value, String>>,+{+ get_usage_with_cache(+ &USAGE_FAILURE_CACHE,+ backend_key,+ USAGE_FAILURE_BACKOFF,+ Instant::now(),+ fetch,+ )+ .await+}++/// The pre-call usage probe: `None` (allow, defer to the backend) when there is+/// no usable credential — no request, no backoff streak — else the usage+/// document behind the shared failure backoff.+async fn probe_usage(config: &Config) -> Result<Value, String> {+ let credential =+ crate::security::credentials::session_support::resolve_backend_credential(config)?;+ let backend_key = crate::backend::require_base_url(&config.api_url)?;+ usage_with_failure_backoff(&backend_key, || fetch_usage(config, credential))+ .await+ .map(|outcome| outcome.value)+}++/// Cache-aware usage fetch. Mirrors the backoff/backpressure shape of+/// [`budget_exhausted_with_cache`] but for *failures*:+///+/// - Within `ttl` of a recorded failure → short-circuit WITHOUT calling+/// `fetch` (network backpressure) and return the+/// [`crate::core::observability::USAGE_PROBE_BACKOFF_PREFIX`] sentinel, which+/// the JSON-RPC boundary demotes (no re-report).+/// - Otherwise call `fetch`: `Ok` clears the streak; a non-session-expiry `Err`+/// anchors a fresh streak and propagates verbatim (first-of-streak reports);+/// a session-expiry `Err` propagates verbatim WITHOUT anchoring (its own RPC+/// arm handles it / drives auth recovery).+async fn get_usage_with_cache<F, Fut>(+ cache: &UsageFailureCache,+ key: &str,+ ttl: Duration,+ now: Instant,+ fetch: F,+) -> Result<Outcome<Value>, String>+where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<Output = Result<Value, String>>,+{+ if cache.is_fresh(key, now, ttl) {+ tracing::debug!(+ "[team] usage probe in failure-backoff window — skipping backend call (suppressing repeat report)"+ );+ return Err(format!(+ "{} recent /teams/me/usage failure suppressed (backoff)",+ crate::core::observability::USAGE_PROBE_BACKOFF_PREFIX+ ));+ }++ match fetch().await {+ Ok(data) => {+ cache.clear();+ Ok(Outcome::single_log(data, "team usage fetched from backend"))+ }+ Err(err) => {+ if crate::core::observability::is_session_expired_message(&err) {+ // Session lapse — handled by the session-expired RPC arm and+ // drives local session cleanup. Never enter the failure window.+ tracing::debug!(+ "[team] usage probe failed with session-expiry — not anchoring backoff"+ );+ } else {+ cache.record(key, now);+ }+ Err(err)+ }+ }+}++fn usage_number(data: &Value, key: &str) -> f64 {+ data.get(key).and_then(Value::as_f64).unwrap_or(0.0)+}++/// Returns true when backend usage says OpenHuman-managed spend should stop.+///+/// A brand-new free account can legitimately have `remainingUsd == 0` and no+/// recurring budget; that should not disable managed tools on its own. We only+/// gate once there is an actual cycle budget/spend signal, matching the+/// frontend's exhausted-budget semantics while covering spend-only payloads.+pub fn usage_budget_exhausted(data: &Value) -> bool {+ let remaining = usage_number(data, "remainingUsd");+ let cycle_budget = usage_number(data, "cycleBudgetUsd");+ let cycle_spent = usage_number(data, "cycleSpentUsd");+ let cycle_limit_7day = usage_number(data, "cycleLimit7day");+ let bypass = data+ .get("bypassCycleLimit")+ .and_then(Value::as_bool)+ .unwrap_or(false);++ !bypass+ && remaining <= 0.01+ && (cycle_budget > 0.01 || cycle_spent > 0.01 || cycle_limit_7day > 0.01)+}++/// How long a managed-tool budget probe result is reused before re-fetching.+///+/// `ensure_budget_available` runs before **every** managed `post`/`get`, so a+/// burst of managed tool calls in one agent turn would otherwise fire one+/// `GET /teams/me/usage` round-trip *per call* — doubling the network cost of+/// each managed integration request and re-fetching identical usage data. A+/// short TTL collapses that burst to one probe while keeping the gate+/// responsive: the backend remains the authoritative gate (it rejects spend+/// once credits run out), so the worst case of a stale cache is a handful of+/// extra calls within the window that the backend itself still blocks.+const BUDGET_PROBE_TTL: Duration = Duration::from_secs(30);++/// Process-global cache for the managed-tool budget probe.+struct BudgetProbeCache {+ /// `(fetched_at, exhausted)` of the last successful probe, if any.+ inner: RwLock<Option<(Instant, bool)>>,+}++impl BudgetProbeCache {+ const fn new() -> Self {+ Self {+ inner: RwLock::new(None),+ }+ }++ /// Cached `exhausted` flag if the last probe is still within `ttl`.+ fn get(&self, now: Instant, ttl: Duration) -> Option<bool> {+ let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());+ guard.and_then(|(fetched_at, exhausted)| {+ (now.duration_since(fetched_at) < ttl).then_some(exhausted)+ })+ }++ /// Record a fresh probe result.+ fn put(&self, now: Instant, exhausted: bool) {+ let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());+ *guard = Some((now, exhausted));+ }+}++static BUDGET_PROBE_CACHE: BudgetProbeCache = BudgetProbeCache::new();++pub async fn managed_tool_budget_exhausted(config: &Config) -> bool {+ budget_exhausted_with_cache(&BUDGET_PROBE_CACHE, BUDGET_PROBE_TTL, || async {+ match probe_usage(config).await {+ Ok(usage) => Some(usage_budget_exhausted(&usage)),+ Err(err) => {+ tracing::debug!(+ error = %err,+ "[budget-gate] usage probe failed; allowing managed tool to defer to backend"+ );+ None+ }+ }+ })+ .await+}++/// Cache-aware budget gate. Returns the cached `exhausted` flag when fresh;+/// otherwise calls `fetch` and caches a successful result. A failed probe+/// (`fetch` returns `None`) is **not** cached and reports "not exhausted" so+/// the call defers to the backend gate — identical to the pre-cache behaviour.+async fn budget_exhausted_with_cache<F, Fut>(+ cache: &BudgetProbeCache,+ ttl: Duration,+ fetch: F,+) -> bool+where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<Output = Option<bool>>,+{+ if let Some(hit) = cache.get(Instant::now(), ttl) {+ tracing::debug!(exhausted = hit, "[team] budget probe cache hit");+ return hit;+ }+ match fetch().await {+ Some(exhausted) => {+ tracing::debug!(+ exhausted,+ "[team] budget probe cache miss; caching fresh probe"+ );+ cache.put(Instant::now(), exhausted);+ exhausted+ }+ None => {+ tracing::debug!("[team] budget probe failed; deferring to backend gate (not cached)");+ false+ }+ }+}++#[cfg(test)]+#[path = "budget_gate_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/client/budget_gate_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client/budget_gate_tests.rsnew file mode 100644index 0000000000..2d33a5c2bc--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/budget_gate_tests.rs@@ -0,0 +1,326 @@+use super::*;+use serde_json::json;+use std::sync::atomic::{AtomicUsize, Ordering};++#[test]+fn budget_cache_get_returns_none_when_empty() {+ let cache = BudgetProbeCache::new();+ assert_eq!(cache.get(Instant::now(), Duration::from_secs(30)), None);+}++// ── GH #4153: `/teams/me/usage` failure backoff ──────────────────────────++use crate::core::observability::is_suppressed_usage_probe_backoff;++const TTL: Duration = Duration::from_secs(60);+const FAIL_KEY: &str = "backend-under-test";++#[test]+fn usage_failure_cache_freshness_window() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ assert!(+ !cache.is_fresh(FAIL_KEY, base, TTL),+ "empty cache is never fresh"+ );+ cache.record(FAIL_KEY, base);+ assert!(cache.is_fresh(FAIL_KEY, base + Duration::from_secs(5), TTL));+ assert!(!cache.is_fresh(FAIL_KEY, base + Duration::from_secs(61), TTL));+ cache.clear();+ assert!(+ !cache.is_fresh(FAIL_KEY, base, TTL),+ "cleared cache is never fresh"+ );+}++// GH #4153: a failure anchored under one backend key must NOT suppress a+// probe for a different backend (e.g. after the user fixes BACKEND_URL or+// the session re-points the backend) — otherwise the new route never gets+// tested for up to the backoff window.+#[test]+fn failure_backoff_is_keyed_per_backend() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ cache.record("https://old.example/api/v1", base);+ assert!(cache.is_fresh("https://old.example/api/v1", base, TTL));+ assert!(+ !cache.is_fresh("https://new.example/api/v1", base, TTL),+ "a different backend key must not inherit the old backend's backoff"+ );+}++// T1 — first failure of a streak hits the backend, reports verbatim, anchors.+#[tokio::test]+async fn first_failure_reports_and_anchors() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ let calls = AtomicUsize::new(0);+ let err = get_usage_with_cache(&cache, FAIL_KEY, TTL, base, || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Err("GET /teams/me/usage failed (500 Internal Server Error): ".to_string()) }+ })+ .await+ .unwrap_err();+ assert_eq!(calls.load(Ordering::SeqCst), 1, "backend probed once");+ assert!(+ !is_suppressed_usage_probe_backoff(&err),+ "first failure must NOT be the backoff sentinel (it reports): {err}"+ );+ assert!(cache.is_fresh(FAIL_KEY, base, TTL), "streak anchored");+}++// T2 — a repeat inside the window short-circuits WITHOUT touching the+// backend and returns the demote sentinel.+#[tokio::test]+async fn repeat_within_window_suppressed_and_skips_backend() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ cache.record(FAIL_KEY, base);+ let calls = AtomicUsize::new(0);+ let err = get_usage_with_cache(&cache, FAIL_KEY, TTL, base + Duration::from_secs(5), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { panic!("fetch must not run inside the backoff window") }+ })+ .await+ .unwrap_err();+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 0,+ "backend NOT probed (backpressure)"+ );+ assert!(+ is_suppressed_usage_probe_backoff(&err),+ "repeat must carry the backoff sentinel: {err}"+ );+}++// T3 — once the window expires the backend is probed again (≤1 report/min).+#[tokio::test]+async fn window_expiry_reprobes_and_reports() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ cache.record(FAIL_KEY, base);+ let later = base + Duration::from_secs(61);+ let calls = AtomicUsize::new(0);+ let err = get_usage_with_cache(&cache, FAIL_KEY, TTL, later, || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Err("GET /teams/me/usage failed (500 Internal Server Error): ".to_string()) }+ })+ .await+ .unwrap_err();+ assert_eq!(calls.load(Ordering::SeqCst), 1, "stale window re-probes");+ assert!(+ !is_suppressed_usage_probe_backoff(&err),+ "re-probe failure reports"+ );+ assert!(+ cache.is_fresh(FAIL_KEY, later, TTL),+ "streak re-anchored at the new probe"+ );+}++// T4 — a success clears the streak so the next failure reports immediately.+#[tokio::test]+async fn success_clears_streak() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ cache.record(FAIL_KEY, base);+ let later = base + Duration::from_secs(61); // stale → fetch runs+ let outcome = get_usage_with_cache(&cache, FAIL_KEY, TTL, later, || async {+ Ok(serde_json::json!({"remainingUsd": 5.0}))+ })+ .await+ .expect("success");+ assert_eq!(outcome.value["remainingUsd"], 5.0);+ assert!(+ !cache.is_fresh(FAIL_KEY, later, TTL),+ "success cleared the streak"+ );+}++// T5 — session-expiry must flow verbatim and must NOT anchor the window+// (its own RPC arm drives auth recovery).+#[tokio::test]+async fn session_expiry_bypasses_backoff() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ let err = get_usage_with_cache(&cache, FAIL_KEY, TTL, base, || async {+ Err("SESSION_EXPIRED: backend rejected session token on GET /teams/me/usage".to_string())+ })+ .await+ .unwrap_err();+ assert!(+ err.contains("SESSION_EXPIRED"),+ "propagated verbatim: {err}"+ );+ assert!(!is_suppressed_usage_probe_backoff(&err));+ assert!(+ !cache.is_fresh(FAIL_KEY, base, TTL),+ "session-expiry must not start a backoff streak"+ );+}++// T6 — the producer's sentinel and the classifier are coupled (no drift).+#[tokio::test]+async fn produced_sentinel_is_classified() {+ let cache = UsageFailureCache::new();+ let base = Instant::now();+ cache.record(FAIL_KEY, base);+ let err = get_usage_with_cache(&cache, FAIL_KEY, TTL, base, || async {+ unreachable!("fresh window short-circuits")+ })+ .await+ .unwrap_err();+ assert!(+ err.starts_with(crate::core::observability::USAGE_PROBE_BACKOFF_PREFIX),+ "sentinel built from the shared prefix constant: {err}"+ );+ assert!(is_suppressed_usage_probe_backoff(&err));+}++#[test]+fn budget_cache_returns_value_within_ttl_and_expires_after() {+ let cache = BudgetProbeCache::new();+ let base = Instant::now();+ cache.put(base, true);+ // Within TTL → cached value.+ assert_eq!(+ cache.get(base + Duration::from_secs(5), Duration::from_secs(30)),+ Some(true)+ );+ // Past TTL → miss (caller must re-probe).+ assert_eq!(+ cache.get(base + Duration::from_secs(31), Duration::from_secs(30)),+ None+ );+}++#[tokio::test]+async fn cache_hit_skips_fetch() {+ let cache = BudgetProbeCache::new();+ cache.put(Instant::now(), true);+ let calls = AtomicUsize::new(0);+ let result = budget_exhausted_with_cache(&cache, Duration::from_secs(30), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Some(false) }+ })+ .await;+ assert!(result, "fresh cache value should be returned");+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 0,+ "fetch must be skipped on cache hit"+ );+}++#[tokio::test]+async fn cache_miss_fetches_and_caches() {+ let cache = BudgetProbeCache::new();+ let calls = AtomicUsize::new(0);+ // First call: empty cache → fetch runs and result is cached.+ let first = budget_exhausted_with_cache(&cache, Duration::from_secs(30), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Some(true) }+ })+ .await;+ assert!(first);+ // Second call: cache is now warm → fetch is skipped.+ let second = budget_exhausted_with_cache(&cache, Duration::from_secs(30), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Some(false) }+ })+ .await;+ assert!(+ second,+ "second call should return the cached true, not the fresh false"+ );+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 1,+ "only the first call should fetch"+ );+}++#[tokio::test]+async fn failed_probe_is_not_cached_and_defers_to_backend() {+ let cache = BudgetProbeCache::new();+ let calls = AtomicUsize::new(0);+ // Probe failure (None) → returns false (defer to backend) and does not cache.+ let first = budget_exhausted_with_cache(&cache, Duration::from_secs(30), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { None }+ })+ .await;+ assert!(!first, "failed probe defers to backend (not exhausted)");+ // Next call must re-probe because the failure wasn't cached.+ let second = budget_exhausted_with_cache(&cache, Duration::from_secs(30), || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Some(true) }+ })+ .await;+ assert!(second);+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 2,+ "failed probe is re-fetched next time"+ );+}++#[test]+fn usage_budget_exhausted_requires_real_cycle_signal() {+ assert!(!usage_budget_exhausted(&json!({+ "remainingUsd": 0,+ "cycleBudgetUsd": 0,+ "cycleSpentUsd": 0,+ })));+ assert!(usage_budget_exhausted(&json!({+ "remainingUsd": 0,+ "cycleBudgetUsd": 10,+ "cycleSpentUsd": 10,+ })));+ assert!(usage_budget_exhausted(&json!({+ "remainingUsd": 0,+ "cycleBudgetUsd": 0,+ "cycleSpentUsd": 2,+ })));+}++#[test]+fn usage_budget_exhausted_honors_remaining_and_bypass() {+ assert!(!usage_budget_exhausted(&json!({+ "remainingUsd": 0.25,+ "cycleBudgetUsd": 10,+ })));+ assert!(!usage_budget_exhausted(&json!({+ "remainingUsd": 0,+ "cycleBudgetUsd": 10,+ "bypassCycleLimit": true,+ })));+}++// ── Sentry 36649: no credential → no request, no streak ─────────────────++#[tokio::test]+async fn probe_without_a_credential_fails_before_the_backoff_and_any_request() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = Config {+ workspace_dir: tmp.path().join("workspace"),+ action_dir: tmp.path().join("workspace"),+ config_path: tmp.path().join("config.toml"),+ api_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let err = probe_usage(&config).await.unwrap_err();+ assert!(+ err.contains("no backend session token"),+ "the credential error is returned as-is, not a network failure: {err}"+ );+ assert!(+ !USAGE_FAILURE_CACHE.is_fresh(+ &crate::backend::base_url(&config.api_url).unwrap(),+ Instant::now(),+ USAGE_FAILURE_BACKOFF+ ),+ "a missing credential must not open a failure-backoff streak"+ );+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client/construct.rs b/crates/openhuman-tinyhumans/src/integrations/client/construct.rsnew file mode 100644index 0000000000..a5ce4166e6--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/construct.rs@@ -0,0 +1,178 @@+//! `IntegrationClient` type definition, backend-URL sanitisation, and the+//! constructors that wire up its HTTP transports.++use std::sync::Arc;+use std::time::Duration;++use crate::integrations::types::IntegrationPricing;++/// Strip any inference-style path that snuck into a backend URL before+/// it becomes the [`IntegrationClient::backend_url`] field. Idempotent —+/// returns the input unchanged when already clean.+///+/// See issue #2075 / Sentry `OPENHUMAN-TAURI-H6`, `-HN`: a misconfigured+/// `BACKEND_URL` env (e.g. `https://api.tinyhumans.ai/openai/v1/chat/completions`)+/// baked into a build silently produced 404 URLs like+/// `…/openai/v1/chat/completions/agent-integrations/composio/connections`+/// because every `IntegrationClient` method joins paths onto this field+/// via [`crate::util::url::join_url`].+pub(super) fn sanitize_backend_url(backend_url: &str) -> String {+ let cleaned = crate::util::url::normalize_backend_api_base_url(backend_url);+ let trimmed = backend_url.trim().trim_end_matches('/');+ if !cleaned.is_empty() && cleaned != trimmed {+ // Redact userinfo (username/password) before logging — a+ // misconfigured URL could carry credentials in the authority+ // segment. The helper preserves host/path for diagnosability+ // while scrubbing secrets.+ tracing::warn!(+ input = %crate::util::redact_url_for_log(trimmed),+ cleaned = %crate::util::redact_url_for_log(&cleaned),+ "[integrations] backend_url carried an inference / non-root path; \+ stripping before use (issue #2075)"+ );+ }+ if cleaned.is_empty() {+ backend_url.to_string()+ } else {+ cleaned+ }+}++/// Shared client for all integration tools. Holds backend URL, auth token,+/// the download `reqwest::Client`, and a lazily-fetched pricing cache. JSON+/// traffic rides the process [`BackendTransport`](crate::backend::transport::BackendTransport).+pub struct IntegrationClient {+ pub backend_url: String,+ pub auth_token: String,+ /// `auth_token` in the shape the transport takes: a session JWT rides+ /// `Authorization: Bearer`, a TinyHumans API key rides `x-api-key` (see+ /// `api::transport::credential_headers`). The 401 handling in `errors.rs`+ /// branches on which one it is.+ pub(super) credential: crate::security::credentials::session_support::BackendCredential,+ pub(super) budget_config: Option<Arc<crate::config::Config>>,+ // The binary download path never rode the SDK: file storage also consumes+ // Content-Type and Content-Disposition, and the presigned-redirect hop+ // must not carry attribution headers (see `new_inner`).+ pub(super) download_client: reqwest::Client,+ /// Follows storage redirects without inheriting any backend credential.+ pub(super) presigned_client: reqwest::Client,+ pub(super) pricing: tokio::sync::OnceCell<IntegrationPricing>,+}++impl IntegrationClient {+ /// A client authenticating with a session JWT.+ pub fn new(backend_url: String, auth_token: String) -> Self {+ Self::new_inner(+ backend_url,+ crate::security::credentials::session_support::BackendCredential::Session(auth_token),+ None,+ )+ }++ /// A client authenticating with whichever credential+ /// [`resolve_backend_credential`](crate::security::credentials::session_support::resolve_backend_credential)+ /// chose: the TinyHumans API key or the session JWT.+ pub fn new_with_credential(+ backend_url: String,+ credential: crate::security::credentials::session_support::BackendCredential,+ ) -> Self {+ Self::new_inner(backend_url, credential, None)+ }++ /// Credential-aware variant of [`Self::new_with_budget_config`].+ pub fn new_with_credential_and_budget_config(+ backend_url: String,+ credential: crate::security::credentials::session_support::BackendCredential,+ config: Arc<crate::config::Config>,+ ) -> Self {+ Self::new_inner(backend_url, credential, Some(config))+ }++ /// Whether this client authenticates with a TinyHumans API key rather+ /// than a session JWT.+ pub fn uses_api_key(&self) -> bool {+ self.credential.is_api_key()+ }++ /// The auth headers for a request built outside the backend transport+ /// (binary download, raw DELETE): `Authorization: Bearer` for a session,+ /// `x-api-key` for an API key.+ pub(crate) fn auth_headers(&self) -> anyhow::Result<reqwest::header::HeaderMap> {+ self.validate_credential_endpoint()?;+ crate::backend::transport::credential_headers(&self.credential)+ .map_err(|e| anyhow::anyhow!("invalid backend credential header: {e}"))+ }++ pub(super) fn validate_credential_endpoint(&self) -> anyhow::Result<()> {+ let endpoint = &self.backend_url;+ if self.uses_api_key()+ && !crate::inference::provider::openhuman_backend_model::is_managed_endpoint_for_api_key(+ endpoint,+ )+ {+ anyhow::bail!("TinyHumans API key requires the managed backend or a loopback endpoint");+ }+ if !crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(+ endpoint,+ ) {+ anyhow::bail!("backend credential requires HTTPS or a loopback HTTP endpoint");+ }+ Ok(())+ }++ fn new_inner(+ backend_url: String,+ credential: crate::security::credentials::session_support::BackendCredential,+ budget_config: Option<Arc<crate::config::Config>>,+ ) -> Self {+ // Defense-in-depth (issue #2075 / Sentry OPENHUMAN-TAURI-H6, -HN):+ // every prod call site routes `backend_url` through+ // `effective_backend_api_url` which strips inference-style paths,+ // but any future caller that forgets that step would silently+ // produce 404 URLs like+ // https://api.tinyhumans.ai/openai/v1/chat/completions/agent-integrations/composio/connections+ // (the inference path concatenated with every domain path). We+ // re-strip here so the field invariant — "backend_url has no+ // inference path" — holds locally, and `warn!` once when we have+ // to fix up the input so the regression is observable in logs.+ let backend_url = sanitize_backend_url(&backend_url);++ // JSON traffic goes through the process backend transport+ // (`TransportProfile::Integrations`: platform TLS, 60 s timeout,+ // product identity — see `openhuman_tinyhumans::backend::headers`).+ // Only the binary download+ // client is built here.+ //+ // `download_client` deliberately does NOT carry the product identity.+ // Its one caller (`get_bytes`) fetches a route that can redirect to+ // presigned storage. The first client stops at the redirect; the second+ // follows it without x-api-key or any other backend header.+ //+ // These raw clients do not add product attribution to storage requests.+ let download_client = crate::util::tls::tls_client_builder()+ .http1_only()+ .redirect(reqwest::redirect::Policy::none())+ .timeout(Duration::from_secs(15 * 60))+ .connect_timeout(Duration::from_secs(15))+ .build()+ .expect("failed to build integration download HTTP client");+ let presigned_client = crate::util::tls::tls_client_builder()+ .http1_only()+ .redirect(reqwest::redirect::Policy::none())+ .timeout(Duration::from_secs(15 * 60))+ .connect_timeout(Duration::from_secs(15))+ .build()+ .expect("failed to build presigned download HTTP client");++ let auth_token = credential.secret().to_owned();+ Self {+ backend_url,+ auth_token,+ credential,+ budget_config,+ download_client,+ presigned_client,+ pricing: tokio::sync::OnceCell::new(),+ }+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client/download.rs b/crates/openhuman-tinyhumans/src/integrations/client/download.rsnew file mode 100644index 0000000000..b567e7527e--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/download.rs@@ -0,0 +1,141 @@+//! Raw-bytes download support for [`IntegrationClient`]: the file-storage+//! download route bypasses the JSON envelope and needs `Content-Type` /+//! `Content-Disposition` metadata the SDK's binary primitive doesn't expose.++use crate::backend::transport::BackendTransportError;++use super::construct::IntegrationClient;+use super::requests::{emit_backend_egress, enforce_backend_egress};++/// Extract the `filename` (or RFC 5987 `filename*`) parameter from a+/// `Content-Disposition` header value, e.g.+/// `attachment; filename="report.pdf"` → `Some("report.pdf")`.+/// Best-effort: unparseable values yield `None` and callers fall back to+/// their own naming scheme.+fn parse_content_disposition_filename(value: &str) -> Option<String> {+ for part in value.split(';') {+ let part = part.trim();+ let lower = part.to_ascii_lowercase();+ if let Some(rest) = lower+ .starts_with("filename*=")+ .then(|| &part["filename*=".len()..])+ {+ // RFC 5987: filename*=UTF-8''percent-encoded — keep the tail+ // after the last `'` and leave percent-decoding to callers who+ // care (the raw form is still a usable, safe name).+ let tail = rest.rsplit('\'').next().unwrap_or(rest);+ let trimmed = tail.trim_matches('"').trim();+ if !trimmed.is_empty() {+ return Some(trimmed.to_string());+ }+ } else if let Some(rest) = lower+ .starts_with("filename=")+ .then(|| &part["filename=".len()..])+ {+ let trimmed = rest.trim().trim_matches('"').trim();+ if !trimmed.is_empty() {+ return Some(trimmed.to_string());+ }+ }+ }+ None+}++impl IntegrationClient {+ /// Authenticated GET returning the raw response body plus content-type and+ /// any `Content-Disposition` filename. Used for backend download routes+ /// that redirect to a presigned S3 URL. The storage hop uses a separate+ /// client with no backend credential headers.+ pub async fn get_bytes(+ &self,+ approval: &crate::security::approval::ApprovalTurnContext,+ path: &str,+ ) -> anyhow::Result<(bytes::Bytes, Option<String>, Option<String>)> {+ self.validate_credential_endpoint()?;+ enforce_backend_egress(path)?;+ emit_backend_egress(approval, path);+ self.ensure_budget_available(path).await?;+ let route = path.split('?').next().unwrap_or(path);+ let segments = route.trim_matches('/').split('/').collect::<Vec<_>>();+ let is_file_download = matches!(+ segments.as_slice(),+ ["agent-integrations", "file-storage", "files", _, "download"]+ );+ if !is_file_download {+ anyhow::bail!("route is intentionally not exposed by the SDK: GET {route}");+ }+ let url = crate::util::url::join_url(&self.backend_url, path);+ tracing::debug!("[integrations] GET(bytes) {}", url);++ let mut resp = self+ .download_client+ .get(&url)+ .headers(self.auth_headers()?)+ .send()+ .await+ .map_err(|error| Self::report_transport_error(error, "get_bytes", path, &url))?;+ // Follow redirects manually so every hop is checked. The authenticated+ // first request is separate from the credential-free storage client.+ for _ in 0..10 {+ if !resp.status().is_redirection() {+ break;+ }+ let location = resp+ .headers()+ .get(reqwest::header::LOCATION)+ .ok_or_else(|| anyhow::anyhow!("download redirect missing Location"))?+ .to_str()?;+ let redirect_url = resp.url().join(location)?;+ anyhow::ensure!(+ crate::inference::provider::openhuman_backend_model::is_safe_endpoint_for_managed_bearer(redirect_url.as_str()),+ "download redirect requires HTTPS or a loopback HTTP endpoint"+ );+ // Redirect hops never carry backend headers, including x-api-key.+ resp = self+ .presigned_client+ .get(redirect_url)+ .send()+ .await+ .map_err(|error| Self::report_transport_error(error, "get_bytes", path, &url))?;+ }+ anyhow::ensure!(+ !resp.status().is_redirection(),+ "download exceeded the maximum number of redirects"+ );+ let status = resp.status();+ if !status.is_success() {+ let body_text = resp.text().await.unwrap_or_default();+ let body =+ serde_json::from_str(&body_text).unwrap_or(serde_json::Value::String(body_text));+ return Err(self.map_transport_error(+ BackendTransportError::Status {+ status: status.as_u16(),+ body,+ },+ "get_bytes",+ path,+ &url,+ ));+ }+ let content_type = resp+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned);+ let filename = resp+ .headers()+ .get(reqwest::header::CONTENT_DISPOSITION)+ .and_then(|value| value.to_str().ok())+ .and_then(parse_content_disposition_filename);+ let body = resp.bytes().await.map_err(|error| {+ anyhow::anyhow!("failed to read response body for GET {url}: {error}")+ })?;+ tracing::debug!(+ "[integrations] GET(bytes) {} → {} bytes (content_type={:?})",+ url,+ body.len(),+ content_type+ );+ Ok((body, content_type, filename))+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client/errors.rs b/crates/openhuman-tinyhumans/src/integrations/client/errors.rsnew file mode 100644index 0000000000..8bf76477bc--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/errors.rs@@ -0,0 +1,336 @@+//! Backend error classification for [`IntegrationClient`]: extracting a+//! readable detail from an error body, mapping transport errors to `anyhow`, and+//! handling the session-JWT 401 → session-expiry recovery path (and the+//! API-key 401, which must never trigger it).++use std::error::Error as _;++use crate::backend::transport::BackendTransportError;++use crate::integrations::types::BackendResponse;++use super::construct::IntegrationClient;++/// Maximum length (in bytes) of backend error body included in propagated+/// errors. Keep this bounded — error messages flow through tracing/Sentry and+/// are surfaced in user-facing toasts, neither of which want a 100KB blob.+pub(crate) const MAX_ERROR_BODY_LEN: usize = 500;++/// Extract a human-readable failure detail from a backend error response body.+///+/// The backend wraps every error response in+/// `{ "success": false, "error": "<msg>" }` (see+/// `backend-openhuman/src/middlewares/errorHandler.ts`). When the body parses+/// as that envelope, return the inner `error` string verbatim — it is the+/// authoritative failure message (e.g. `"Insufficient balance"`,+/// `"Toolkit \"X\" is not enabled"`).+///+/// Otherwise (non-JSON body, missing `error` field) fall back to the raw+/// text truncated to `max_bytes` at a UTF-8 char boundary so callers always+/// get *something* to grep for, without unbounded memory in error paths.+pub(crate) fn extract_error_detail(body: &str, max_bytes: usize) -> String {+ if body.is_empty() {+ return "<empty body>".to_string();+ }+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {+ if let Some(msg) = v.get("error").and_then(|e| e.as_str()) {+ let trimmed = msg.trim();+ if !trimmed.is_empty() {+ return crate::util::truncate_at_byte_boundary(trimmed, max_bytes);+ }+ }+ }+ crate::util::truncate_at_byte_boundary(body, max_bytes)+}++/// Handle a `401 Unauthorized` from the OpenHuman backend's+/// `/agent-integrations/*` routes.+///+/// **Why this 401 is unambiguously a session-JWT rejection.** Only reached+/// when the client authenticates with the *app-session JWT* (an API-key client+/// takes [`handle_api_key_unauthorized`] instead); that JWT rides+/// `Authorization: Bearer`, resolved by+/// `session_support::resolve_backend_credential`, the same resolver billing /+/// team / webhooks / memory all use. The backend's auth middleware+/// (`backend-openhuman`) is what answers `401 {"error":"Invalid token"}` when+/// that JWT is expired / revoked / rotated server-side — see the identical+/// envelope pinned in `inference/provider/config_rejection.rs` and the socket+/// reconnect loop's `"Invalid token"` handling in+/// `openhuman::platform::socket::ws_loop`. A *third-party* integration's auth failure+/// never reaches this arm:+///+/// - **Composio backend mode** (the default that routes through this client):+/// provider-side failures come back as `2xx` envelope `success:false`+/// (`"Toolkit X is not enabled"`, `"Missing required fields: …"`) or a+/// descriptive non-401 4xx/5xx — handled by+/// [`crate::core::observability::is_provider_user_state_message`] /+/// [`crate::core::observability::is_backend_user_error_message`], NOT a bare+/// 401. The backend's auth wall is the only thing that returns 401 here.+/// - **Composio direct mode**: bypasses this client entirely (it talks to+/// `backend.composio.dev` with `x-api-key` via `ComposioTool`), so a+/// direct-mode key 401 carries the distinct `"[composio-direct] … HTTP 401:+/// Invalid API key"` shape and never lands here.+///+/// So narrowing to `status == 401` (and *only* 401 — 403 stays generic, it can+/// be an authz/scope rejection on a backend-mediated resource rather than a+/// dead session) targets exactly the session-JWT rejection with zero risk of+/// logging the user out for an unrelated integration problem.+///+/// What this does, mirroring `api/rest.rs::flatten_authed_error` (typed-401 →+/// `SESSION_EXPIRED:` sentinel) and+/// `inference/provider/ops/http_error.rs::publish_backend_session_expired`+/// (direct publish for paths whose error is consumed inline / swallowed):+///+/// 1. Build a `SESSION_EXPIRED:`-prefixed message so it (a) classifies as+/// [`crate::core::observability::ExpectedErrorKind::SessionExpired`] and+/// stays demoted from Sentry, and (b) is recognised by+/// `core::session_expiry::is_session_expired_error` *if* it ever propagates up to+/// the RPC boundary.+/// 2. **Publish `DomainEvent::SessionExpired` directly.** The autonomous agent+/// tool path converts tool errors into a `role:tool` result string fed back+/// to the model — the `Err` never+/// reaches `jsonrpc::invoke_method`, so relying on propagation alone would+/// leave re-login un-triggered (this is the root-cause gap behind+/// TAURI-RUST-84E: the prior fix demoted the noise but never drove+/// recovery). Publishing here makes the credentials subscriber clear the+/// session and the UI prompt re-sign-in regardless of which call site+/// surfaced the 401.+fn handle_session_jwt_unauthorized(method: &str, path: &str, url: &str, detail: &str) -> String {+ let message = format!(+ "SESSION_EXPIRED: backend rejected session token on {method} {path} \+ (401 for {url}: {detail}) — sign in again to resume"+ );++ let soft = is_composio_soft_auth_path(method, path);++ tracing::warn!(+ path = %path,+ method = %method,+ soft_auth = soft,+ "[integrations] backend rejected session JWT (401)"+ );++ // Demote from Sentry (SESSION_EXPIRED classifies as expected) — keeps the+ // noise suppression the prior fix established. Applies to both paths.+ crate::core::observability::report_error_or_expected(+ message.as_str(),+ "integrations",+ "session_expired",+ &[+ ("path", path),+ ("status", "401"),+ ("failure", "session_jwt"),+ ],+ );++ // Soft path: surface the sentinel to the caller (→ in-place CTA) WITHOUT+ // the global sign-out. See `is_composio_soft_auth_path`.+ if soft {+ tracing::debug!(+ path = %path,+ "[integrations] soft composio auth path — returning SESSION_EXPIRED to the panel without publishing global SessionExpired (#4281)"+ );+ return message;+ }++ // Drive recovery: publish SessionExpired so the credentials subscriber+ // clears the stale token and the UI prompts re-sign-in. The reason string+ // is already free of secrets (it names the path + sanitized backend+ // `error` detail), but re-scrub for defense-in-depth before it reaches the+ // subscriber's logs.+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {+ source: format!("integrations.{method}:{path}"),+ reason: tinyinference_core::sanitize::sanitize_api_error(&message),+ });++ message+}++/// Handle a `401` on a request authenticated with a TinyHumans API key.+///+/// There is no session to expire: the key is revoked, mistyped or blocked by+/// its IP allowlist. So this never publishes `DomainEvent::SessionExpired`+/// (that would sign a desktop user out of a session the request never used)+/// and uses the same `API_KEY_REJECTED:` sentinel as+/// `api::rest::flatten_authed_error`. A key that lacks a scope answers `403`,+/// which stays on the generic non-2xx path.+fn handle_api_key_unauthorized(method: &str, path: &str, url: &str, detail: &str) -> String {+ let message = format!(+ "API_KEY_REJECTED: backend rejected api key on {method} {path} \+ (401 for {url}: {detail}) — check the configured TinyHumans API key"+ );+ tracing::warn!(+ path = %path,+ method = %method,+ "[integrations] backend rejected api key (401)"+ );+ crate::core::observability::report_error_or_expected(+ message.as_str(),+ "integrations",+ "api_key_rejected",+ &[("path", path), ("status", "401"), ("failure", "api_key")],+ );+ message+}++/// Composio **trigger-catalog reads** (`GET /agent-integrations/composio/triggers…`)+/// where a 401 is a single recoverable read failure rather than whole-session+/// death. The connection itself is still active — `list_connections` uses the+/// *same* session JWT and succeeds, so signing the user out on a triggers-only+/// 401 over-reacts and (per #2286) must not happen.+///+/// For these reads [`handle_session_jwt_unauthorized`] still builds the+/// `SESSION_EXPIRED:` sentinel (so the trigger panel can classify the error and+/// render an in-place "Sign in again" CTA) and still demotes from Sentry, but+/// it does **not** publish [`DomainEvent::SessionExpired`] — that global+/// teardown would unmount the panel before the CTA is usable (#4281). A+/// genuinely dead session is still caught by the authoritative paths+/// (app-state snapshot, connections poll), which keep driving re-login.+///+/// Scoped to `GET` deliberately: trigger **writes** (`POST` enable / disable /+/// create) keep the standard global-sign-out on a 401 — they are not the+/// "catalog won't load" surface this issue addresses, and a write that 401s on+/// a dead session has no in-place CTA to fall back to (its error renders as a+/// per-row toggle failure, not the panel banner).+pub(super) fn is_composio_soft_auth_path(method: &str, path: &str) -> bool {+ // Match on a real path boundary, not a bare prefix: `…/triggers` exact,+ // `…/triggers/…` (the `available` catalog), or `…/triggers?…` (the active+ // list with a `toolkit` query). A bare `starts_with` would also match an+ // unrelated `…/triggersXYZ` route and wrongly suppress the global sign-out.+ const BASE: &str = "/agent-integrations/composio/triggers";+ method.eq_ignore_ascii_case("GET")+ && path+ .strip_prefix(BASE)+ .is_some_and(|rest| rest.is_empty() || rest.starts_with('/') || rest.starts_with('?'))+}++impl IntegrationClient {+ /// Render a reqwest transport error with its full source chain (mirrors+ /// the inline closures in [`Self::post`] / [`Self::get`]) and route it+ /// through the observability classifier so network-environment failures+ /// skip Sentry.+ pub(super) fn report_transport_error(+ e: reqwest::Error,+ method: &str,+ path: &str,+ url: &str,+ ) -> anyhow::Error {+ let mut chain = format!("{e}");+ let mut src: Option<&(dyn std::error::Error + 'static)> = e.source();+ while let Some(s) = src {+ chain.push_str(" → ");+ chain.push_str(&s.to_string());+ src = s.source();+ }+ crate::core::observability::report_error_or_expected(+ chain.as_str(),+ "integrations",+ method,+ &[("path", path), ("failure", "transport")],+ );+ anyhow::anyhow!("{} {} failed: {}", method.to_uppercase(), url, chain)+ }++ pub(super) fn map_transport_error(+ &self,+ error: BackendTransportError,+ method: &str,+ path: &str,+ url: &str,+ ) -> anyhow::Error {+ let method_upper = method.to_uppercase();+ match error {+ // A core with no backend transport installed (built without+ // `openhuman-tinyhumans`): expected build state, not a defect.+ // `report_error_or_expected` keys off the `BACKEND_UNAVAILABLE:`+ // prefix to keep it out of Sentry.+ BackendTransportError::Unavailable => {+ let msg = format!(+ "{}{method_upper} {url}: managed backend is not available in this build",+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX+ );+ crate::core::observability::report_error_or_expected(+ msg.as_str(),+ "integrations",+ method,+ &[("path", path), ("failure", "backend_unavailable")],+ );+ anyhow::anyhow!(msg)+ }+ BackendTransportError::Http(error) => {+ Self::report_transport_error(error, method, path, url)+ }+ BackendTransportError::Status { status, body } => {+ let body_text = match body {+ serde_json::Value::String(text) => text,+ value => value.to_string(),+ };+ let detail = extract_error_detail(&body_text, MAX_ERROR_BODY_LEN);+ if status == reqwest::StatusCode::UNAUTHORIZED.as_u16()+ && self.credential.is_api_key()+ {+ return anyhow::anyhow!(handle_api_key_unauthorized(+ &method_upper,+ path,+ url,+ &detail+ ));+ }+ if status == reqwest::StatusCode::UNAUTHORIZED.as_u16() {+ return anyhow::anyhow!(handle_session_jwt_unauthorized(+ &method_upper,+ path,+ url,+ &detail+ ));+ }+ let status_text = reqwest::StatusCode::from_u16(status)+ .map(|status| status.to_string())+ .unwrap_or_else(|_| status.to_string());+ let status_code = status.to_string();+ crate::core::observability::report_error_or_expected(+ format!("Backend returned {status_text} for {method_upper} {url}: {detail}")+ .as_str(),+ "integrations",+ method,+ &[+ ("path", path),+ ("status", status_code.as_str()),+ ("failure", "non_2xx"),+ ],+ );+ anyhow::anyhow!("Backend returned {status_text} for {method_upper} {url}: {detail}")+ }+ other => anyhow::anyhow!("{method_upper} {url} failed: {other}"),+ }+ }++ pub(super) fn parse_envelope<T: serde::de::DeserializeOwned>(+ method: &str,+ path: &str,+ url: &str,+ value: serde_json::Value,+ ) -> anyhow::Result<T> {+ let method_upper = method.to_uppercase();+ let envelope: BackendResponse<T> = serde_json::from_value(value)?;+ if !envelope.success {+ let msg = envelope+ .error+ .unwrap_or_else(|| "unknown backend error".into());+ crate::core::observability::report_error_or_expected(+ msg.as_str(),+ "integrations",+ method,+ &[("path", path), ("failure", "envelope_error")],+ );+ anyhow::bail!("Backend error for {} {}: {}", method_upper, url, msg);+ }+ envelope.data.ok_or_else(|| {+ anyhow::anyhow!(+ "Backend returned success but no data for {} {}",+ method_upper,+ url+ )+ })+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client/pricing.rs b/crates/openhuman-tinyhumans/src/integrations/client/pricing.rsnew file mode 100644index 0000000000..a36cc76b25--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/pricing.rs@@ -0,0 +1,177 @@+//! Pricing cache and the top-level `build_client` / `pricing_for_config`+//! helpers used to construct an [`IntegrationClient`] from app config.++use std::sync::Arc;++use crate::integrations::types::IntegrationPricing;++use super::construct::IntegrationClient;++impl IntegrationClient {+ /// Fetch and cache pricing info from the backend. Returns a default+ /// (empty) pricing struct on network errors so tool registration never fails.+ pub async fn pricing(&self) -> &IntegrationPricing {+ self.pricing+ .get_or_init(|| async {+ match self+ .get::<IntegrationPricing>(+ &crate::security::approval::ApprovalTurnContext::default(),+ "/agent-integrations/pricing",+ )+ .await+ {+ Ok(p) => {+ tracing::debug!("[integrations] pricing fetched successfully");+ p+ }+ Err(e) => {+ tracing::warn!("[integrations] failed to fetch pricing: {e}");+ IntegrationPricing::default()+ }+ }+ })+ .await+ }+}++/// Fetch pricing for the integrations module, honouring the+/// Composio routing mode.+///+/// When `config.composio.mode == "direct"`, the user is running with+/// their own Composio API key and there is **no backend session** that+/// could serve `/agent-integrations/pricing` — the backend route is+/// what mediates the margin between Composio's raw price and what the+/// hosted product charges. In direct mode, margins do not apply+/// (the user pays Composio directly) and the backend may not even be+/// reachable (sovereign / offline-friendly deployments). We+/// short-circuit to the default empty pricing struct and emit a+/// `[composio-direct]` log line so this branch is easy to grep.+///+/// In backend mode we fall through to the live cache on+/// [`IntegrationClient::pricing`], preserving the existing behavior+/// for every caller. The empty default struct is identical to what+/// [`IntegrationClient::pricing`] returns on a network error, so+/// downstream consumers don't need a separate code path.+pub async fn pricing_for_config(+ client: &IntegrationClient,+ config: &crate::config::Config,+) -> IntegrationPricing {+ use crate::config::schema::COMPOSIO_MODE_DIRECT;++ if config.composio.mode.trim() == COMPOSIO_MODE_DIRECT {+ tracing::debug!(+ "[composio-direct] pricing short-circuit: backend `/agent-integrations/pricing` \+ is unreachable in direct mode — returning default (empty) pricing"+ );+ return IntegrationPricing::default();+ }+ client.pricing().await.clone()+}++/// Helper: build an `Arc<IntegrationClient>` from the root config, or+/// `None` if there is no backend credential. A local offline credential keeps+/// the core signed in but cannot authenticate hosted integration routes.+///+/// Both the backend URL and the credential come from **core defaults**:+///+/// - backend URL → [`crate::backend::base_url`]+/// applied to `config.api_url`. Unlike the plain+/// [`crate::backend::inference_base_url`] resolver (which honours a+/// user-set local-AI endpoint so chat completions still work), the+/// backend resolver detects local-AI URLs and falls back to the+/// `BACKEND_URL` / `VITE_BACKEND_URL` env vars (and finally the hosted+/// default) so backend paths don't get concatenated onto a local+/// Ollama/vLLM endpoint and 404.+/// - credential → [`resolve_backend_credential`], the same resolver every+/// other backend caller uses: the stored TinyHumans API key when there is+/// one (sent as `x-api-key`), else the live app-session JWT (sent as+/// `Authorization: Bearer`). The local offline token and an expired session+/// both resolve to an error, so no client is built for them.+///+/// There are no per-feature toggles for the shared client itself —+/// callers that need a kill switch (e.g. google_places, parallel,+/// stock_prices) gate tool registration at their own level.+///+/// [`resolve_backend_credential`]: crate::security::credentials::session_support::resolve_backend_credential+pub fn build_client(config: &crate::config::Config) -> Option<Arc<IntegrationClient>> {+ // Use the integrations-specific resolver: when `config.api_url` is set+ // to a local-AI endpoint (Ollama, vLLM, …), it would still be perfect+ // for `/v1/chat/completions`, but reusing it as the base for backend+ // integration paths produces URLs like+ // http://127.0.0.1:11434/v1/agent-integrations/composio/toolkits+ // which 404 against the local LLM and flooded Sentry+ // (OPENHUMAN-TAURI-51 / -80 / -7Z). The helper falls through to env /+ // default backend in that case so integrations actually work.+ let backend_url = match crate::backend::base_url(&config.api_url) {+ Ok(url) => url,+ Err(_) => {+ tracing::debug!(+ "[integrations] no backend transport — integrations client unavailable"+ );+ return None;+ }+ };++ let credential =+ match crate::security::credentials::session_support::resolve_backend_credential(config) {+ Ok(credential) => Some(credential),+ Err(e) => {+ tracing::debug!("[integrations] no backend credential: {e}");+ None+ }+ };++ build_client_with_credential(config, backend_url, credential)+}++/// The credential decision is separate from profile-store lookup so callers+/// can test the backend boundary without process-wide auth-store state.+fn build_client_with_credential(+ config: &crate::config::Config,+ backend_url: String,+ credential: Option<crate::security::credentials::session_support::BackendCredential>,+) -> Option<Arc<IntegrationClient>> {+ use crate::security::credentials::session_support::BackendCredential;++ let credential = match credential {+ Some(BackendCredential::Session(token))+ if crate::security::credentials::session_support::is_local_session_token(+ token.trim(),+ ) =>+ {+ // Offline identity is valid for the local core, but the hosted+ // integrations API cannot authenticate it. Never send it as a+ // backend JWT: a predictable 401 would publish a global+ // SessionExpired event into an otherwise healthy local chat.+ tracing::debug!(+ "[integrations] local offline credential has no hosted integrations client"+ );+ return None;+ }+ Some(BackendCredential::Session(token)) => {+ BackendCredential::Session(token.trim().to_owned())+ }+ Some(BackendCredential::ApiKey(key)) => BackendCredential::ApiKey(key.trim().to_owned()),+ None => return None,+ };+ if credential.secret().is_empty() {+ tracing::warn!("[integrations] no auth token available — not signed in and no API key set");+ return None;+ }+ tracing::debug!(+ backend_url = %backend_url,+ api_key = credential.is_api_key(),+ "[integrations] client built (backend credential resolved)"+ );+ Some(Arc::new(+ IntegrationClient::new_with_credential_and_budget_config(+ backend_url,+ credential,+ Arc::new(config.clone()),+ ),+ ))+}++#[cfg(test)]+#[path = "pricing_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/client/pricing_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client/pricing_tests.rsnew file mode 100644index 0000000000..20f6d160b2--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/pricing_tests.rs@@ -0,0 +1,61 @@+use super::*;+use crate::security::credentials::session_support::BackendCredential;++#[test]+fn local_offline_token_never_constructs_a_hosted_integration_client() {+ let config = crate::config::Config::default();+ let backend_url = "https://api.example.test".to_owned();+ assert!(build_client_with_credential(+ &config,+ backend_url.clone(),+ Some(BackendCredential::Session("header.payload.local".into())),+ )+ .is_none());+ assert!(build_client_with_credential(+ &config,+ backend_url,+ Some(BackendCredential::Session("header.payload.jwt".into())),+ )+ .is_some());+}++#[test]+fn api_key_constructs_a_client_that_authenticates_with_the_key() {+ let config = crate::config::Config::default();+ let client = build_client_with_credential(+ &config,+ "https://api.tinyhumans.ai".to_owned(),+ Some(BackendCredential::ApiKey(" tiny_test_abc ".into())),+ )+ .expect("an API key alone must build the integrations client");+ assert!(client.uses_api_key());+ assert_eq!(client.auth_token, "tiny_test_abc");+ let headers = client.auth_headers().unwrap();+ assert_eq!(headers.get("x-api-key").unwrap(), "tiny_test_abc");+ assert!(headers.get(reqwest::header::AUTHORIZATION).is_none());+}++#[test]+fn api_key_rejects_foreign_or_plaintext_integration_endpoints() {+ for endpoint in ["https://example.com", "http://example.com"] {+ let client = IntegrationClient::new_with_credential(+ endpoint.to_owned(),+ BackendCredential::ApiKey("tiny_test_abc".into()),+ );+ assert!(client.validate_credential_endpoint().is_err());+ assert!(client.auth_headers().is_err());+ }+}++#[test]+fn missing_or_blank_credential_builds_no_client() {+ let config = crate::config::Config::default();+ let url = "https://api.example.test".to_owned();+ assert!(build_client_with_credential(&config, url.clone(), None).is_none());+ assert!(build_client_with_credential(+ &config,+ url,+ Some(BackendCredential::ApiKey(" ".into()))+ )+ .is_none());+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client/requests.rs b/crates/openhuman-tinyhumans/src/integrations/client/requests.rsnew file mode 100644index 0000000000..23f1640e13--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client/requests.rs@@ -0,0 +1,207 @@+//! Outbound request plumbing for [`IntegrationClient`]: route guards, egress+//! disclosure/enforcement, budget gating, and the JSON verb methods+//! (`post`/`get`/`patch`/`delete`/`upload_multipart`).++use super::construct::IntegrationClient;+use crate::security::approval::ApprovalTurnContext;++pub(super) fn managed_budget_applies_to_path(path: &str) -> bool {+ path != "/agent-integrations/pricing" && path.starts_with("/agent-integrations/")+}++fn reject_privileged_backend_path(method: &str, path: &str) -> anyhow::Result<()> {+ let route = path.split('?').next().unwrap_or(path);+ if route.split('/').any(|segment| {+ segment.eq_ignore_ascii_case("webhooks") || segment.eq_ignore_ascii_case("admin")+ }) {+ anyhow::bail!(+ "route is intentionally not exposed by the SDK: {} {}",+ method,+ route+ );+ }+ Ok(())+}++/// Build the egress descriptor for a managed-backend round-trip. The query+/// string is stripped so only the endpoint (the "to where") is described, never+/// any data carried in the query.+pub(super) fn backend_egress_descriptor(path: &str) -> crate::security::egress::EgressDescriptor {+ let endpoint = path.split('?').next().unwrap_or(path);+ crate::security::egress::EgressDescriptor::integration(endpoint)+}++/// Egress spine (privacy epic S2, #4436): disclose an OpenHuman managed-backend+/// round-trip before it leaves the device. Fire-and-forget — never fails the+/// caller.+pub(super) fn emit_backend_egress(approval: &ApprovalTurnContext, path: &str) {+ crate::security::egress::emit_external_transfer(+ approval.chat.as_ref(),+ backend_egress_descriptor(path),+ );+}++/// Local-only enforcement (privacy epic S7, #4441): refuse a managed-backend+/// round-trip that ships user data when the live policy is `LocalOnly`. Returns+/// `Ok(())` for control-plane paths (session / team / billing / integration+/// connection-management + catalog) even under `LocalOnly` — blocking those+/// would break sign-in and the Connections UI for no privacy benefit. See+/// [`is_control_plane`](crate::security::egress). Call before+/// [`emit_backend_egress`] so a blocked call is neither disclosed nor sent.+pub(super) fn enforce_backend_egress(path: &str) -> anyhow::Result<()> {+ crate::security::egress::enforce_egress(&backend_egress_descriptor(path))+}++impl IntegrationClient {+ /// The process backend transport, or the typed "backend unavailable"+ /// error already classified for this call.+ pub(super) fn transport(+ &self,+ method: &str,+ path: &str,+ url: &str,+ ) -> anyhow::Result<std::sync::Arc<dyn crate::backend::transport::BackendTransport>> {+ crate::backend::transport::resolve_backend_transport()+ .map_err(|error| self.map_transport_error(error, method, path, url))+ }++ /// Describe one `/agent-integrations/*` round-trip for the transport: the+ /// client's credential (session JWT as bearer, API key as `x-api-key`), no envelope unwrapping (this client parses+ /// the `{success,data}` envelope itself so its error classification sees+ /// the raw shape).+ pub(super) fn backend_request<'a>(+ &'a self,+ method: reqwest::Method,+ path: &'a str,+ body: Option<&'a serde_json::Value>,+ ) -> crate::backend::transport::BackendRequest<'a> {+ crate::backend::transport::BackendRequest {+ profile: crate::backend::transport::TransportProfile::Integrations,+ base_url: &self.backend_url,+ method,+ path,+ query: &[],+ body,+ credential: Some(&self.credential),+ unwrap_envelope: false,+ }+ }++ pub(super) async fn ensure_budget_available(&self, path: &str) -> anyhow::Result<()> {+ if !managed_budget_applies_to_path(path) {+ return Ok(());+ }+ if let Some(config) = &self.budget_config {+ if super::budget_gate::managed_tool_budget_exhausted(config).await {+ anyhow::bail!(+ "Managed cloud tools are disabled because your OpenHuman AI credits are exhausted. Add credits or route the task to user-supplied providers."+ );+ }+ }+ Ok(())+ }++ /// POST JSON to a backend endpoint and parse the response `data` field.+ pub async fn post<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ path: &str,+ body: &serde_json::Value,+ ) -> anyhow::Result<T> {+ self.request_json(approval, reqwest::Method::POST, path, Some(body))+ .await+ }++ /// GET from a backend endpoint and parse the response `data` field.+ pub async fn get<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ path: &str,+ ) -> anyhow::Result<T> {+ self.request_json(approval, reqwest::Method::GET, path, None)+ .await+ }++ pub(super) async fn request_json<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ method: reqwest::Method,+ path: &str,+ body: Option<&serde_json::Value>,+ ) -> anyhow::Result<T> {+ self.validate_credential_endpoint()?;+ reject_privileged_backend_path(method.as_str(), path)?;+ enforce_backend_egress(path)?;+ emit_backend_egress(approval, path);+ self.ensure_budget_available(path).await?;+ let url = crate::util::url::join_url(&self.backend_url, path);+ let method_name = method.as_str().to_ascii_lowercase();+ tracing::debug!("[integrations] {} {}", method.as_str(), url);+ let value = self+ .transport(&method_name, path, &url)?+ .send_json(self.backend_request(method, path, body))+ .await+ .map_err(|error| self.map_transport_error(error, &method_name, path, &url))?;+ Self::parse_envelope(&method_name, path, &url, value)+ }++ /// PATCH JSON to a backend endpoint and parse the response `data` field.+ /// Mirrors [`Self::post`] (auth header, 401 → session-expiry, error+ /// classification).+ pub async fn patch<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ path: &str,+ body: &serde_json::Value,+ ) -> anyhow::Result<T> {+ self.request_json(approval, reqwest::Method::PATCH, path, Some(body))+ .await+ }++ /// DELETE a backend resource and parse the response `data` field.+ /// Mirrors [`Self::post`] (auth header, 401 → session-expiry, error+ /// classification).+ pub async fn delete<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ path: &str,+ ) -> anyhow::Result<T> {+ self.request_json(approval, reqwest::Method::DELETE, path, None)+ .await+ }++ /// POST a `multipart/form-data` body to a backend endpoint and parse the+ /// response `data` field. Mirrors [`Self::post`] URL building, Bearer+ /// auth, 401 → session-expiry handling and error classification; the+ /// content type is set by reqwest from the form boundary.+ pub async fn upload_multipart<T: serde::de::DeserializeOwned>(+ &self,+ approval: &ApprovalTurnContext,+ path: &str,+ form: reqwest::multipart::Form,+ ) -> anyhow::Result<T> {+ self.validate_credential_endpoint()?;+ reject_privileged_backend_path("POST", path)?;+ enforce_backend_egress(path)?;+ emit_backend_egress(approval, path);+ self.ensure_budget_available(path).await?;+ let url = crate::util::url::join_url(&self.backend_url, path);+ tracing::debug!("[integrations] POST(multipart) {}", url);++ let value = self+ .transport("post_multipart", path, &url)?+ .send_multipart(+ self.backend_request(reqwest::Method::POST, path, None),+ form,+ )+ .await+ .map_err(|error| self.map_transport_error(error, "post_multipart", path, &url))?;+ // The transport unwraps successful `{success,data}` responses. Preserve+ // compatibility with endpoints that return their payload directly,+ // while still recognizing a `success:false` envelope.+ if value.get("success") == Some(&serde_json::Value::Bool(false)) {+ return Self::parse_envelope("post_multipart", path, &url, value);+ }+ Ok(serde_json::from_value(value)?)+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client_api_key_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client_api_key_tests.rsnew file mode 100644index 0000000000..1106a5392b--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client_api_key_tests.rs@@ -0,0 +1,159 @@+//! `IntegrationClient` authenticated with a TinyHumans API key instead of a+//! session JWT: the key rides `x-api-key` on every route (JSON, download,+//! raw DELETE), and a 401 is an API-key rejection, never a session expiry.++use super::*;+use axum::http::HeaderMap;+use parking_lot::Mutex;++use crate::security::credentials::session_support::BackendCredential;++const KEY: &str = "tiny_test_integrations_key";++fn api_key_client(base: String) -> IntegrationClient {+ IntegrationClient::new_with_credential(base, BackendCredential::ApiKey(KEY.into()))+}++/// `(x-api-key, authorization)` seen by the mock for one request.+type Seen = Arc<Mutex<Vec<(Option<String>, Option<String>)>>>;++fn record(seen: &Seen, headers: &HeaderMap) {+ let header = |name: &str| {+ headers+ .get(name)+ .and_then(|value| value.to_str().ok())+ .map(str::to_owned)+ };+ seen.lock()+ .push((header("x-api-key"), header("authorization")));+}++#[tokio::test]+async fn json_requests_send_the_api_key_as_x_api_key_and_no_bearer() {+ let seen: Seen = Arc::default();+ let app = Router::new().route(+ "/agent-integrations/composio/connections",+ get({+ let seen = Arc::clone(&seen);+ move |headers: HeaderMap| async move {+ record(&seen, &headers);+ Json(json!({ "success": true, "data": { "connections": [] } }))+ }+ }),+ );+ let client = api_key_client(start_mock_backend(app).await);+ assert!(client.uses_api_key());+ client+ .get::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/connections",+ )+ .await+ .expect("an API-key client reaches composio");++ let seen = seen.lock();+ assert_eq!(seen.len(), 1);+ assert_eq!(seen[0].0.as_deref(), Some(KEY));+ assert_eq!(seen[0].1, None, "an API key must never ride Authorization");+}++#[tokio::test]+async fn binary_download_sends_the_api_key_as_x_api_key() {+ let seen: Seen = Arc::default();+ let app = Router::new().route(+ "/agent-integrations/file-storage/files/f1/download",+ get({+ let seen = Arc::clone(&seen);+ move |headers: HeaderMap| async move {+ record(&seen, &headers);+ "bytes"+ }+ }),+ );+ let client = api_key_client(start_mock_backend(app).await);+ let (bytes, _, _) = client+ .get_bytes(+ &Default::default(),+ "/agent-integrations/file-storage/files/f1/download",+ )+ .await+ .expect("download with an API key");+ assert_eq!(&bytes[..], b"bytes");++ let seen = seen.lock();+ assert_eq!(seen[0].0.as_deref(), Some(KEY));+ assert_eq!(seen[0].1, None);+}++#[tokio::test]+async fn presigned_download_redirect_does_not_forward_api_key() {+ let seen: Seen = Arc::default();+ let storage = Router::new().route(+ "/blob",+ get({+ let seen = Arc::clone(&seen);+ move |headers: HeaderMap| async move {+ record(&seen, &headers);+ "stored bytes"+ }+ }),+ );+ let storage_url = start_mock_backend(storage).await;+ let location = format!("{storage_url}/blob");+ let backend = Router::new().route(+ "/agent-integrations/file-storage/files/f1/download",+ get(move || {+ let location = location.clone();+ async move {+ (+ StatusCode::FOUND,+ [(axum::http::header::LOCATION, location)],+ )+ }+ }),+ );+ let client = api_key_client(start_mock_backend(backend).await);+ let (bytes, _, _) = client+ .get_bytes(+ &Default::default(),+ "/agent-integrations/file-storage/files/f1/download",+ )+ .await+ .unwrap();+ assert_eq!(&bytes[..], b"stored bytes");+ let seen = seen.lock();+ assert_eq!(seen.len(), 1);+ assert_eq!(seen[0], (None, None));+}++#[tokio::test]+async fn api_key_401_is_api_key_rejected_not_session_expired() {+ use crate::core::observability::is_session_expired_message;++ let app = Router::new().route(+ "/agent-integrations/parallel/search",+ post(|| async {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "Invalid API key" })),+ )+ .into_response()+ }),+ );+ let client = api_key_client(start_mock_backend(app).await);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/parallel/search",+ &json!({ "objective": "x" }),+ )+ .await+ .expect_err("401 must surface as Err");+ let msg = format!("{err:#}");+ assert!(msg.contains("API_KEY_REJECTED"), "{msg}");+ assert!(!msg.contains("SESSION_EXPIRED"), "{msg}");+ assert!(+ !is_session_expired_message(&msg),+ "a rejected API key must not drive the session re-login flow: {msg}"+ );+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client_error_propagation_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client_error_propagation_tests.rsnew file mode 100644index 0000000000..e394972079--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client_error_propagation_tests.rs@@ -0,0 +1,643 @@+use super::*;++// ── Unit: `extract_error_detail` ──────────────────────────────────++#[test]+fn extract_error_detail_envelope_returns_inner_message() {+ let body = r#"{"success":false,"error":"Insufficient balance"}"#;+ assert_eq!(extract_error_detail(body, 500), "Insufficient balance");+}++#[test]+fn extract_error_detail_envelope_trims_whitespace() {+ let body = r#"{"success":false,"error":" Toolkit \"foo\" is not enabled "}"#;+ assert_eq!(+ extract_error_detail(body, 500),+ "Toolkit \"foo\" is not enabled"+ );+}++#[test]+fn extract_error_detail_falls_back_for_non_json_body() {+ let body = "<html>500 internal error</html>";+ assert_eq!(extract_error_detail(body, 500), body);+}++#[test]+fn extract_error_detail_handles_empty_body() {+ assert_eq!(extract_error_detail("", 500), "<empty body>");+}++#[test]+fn extract_error_detail_truncates_long_non_json_bodies_at_char_boundary() {+ // Multi-byte UTF-8 (€ = 3 bytes). Building a string longer than `max`+ // ensures truncate_at_char_boundary backs off until it lands on a+ // valid char boundary instead of slicing inside a code point.+ let body = "€".repeat(200); // 600 bytes+ let out = extract_error_detail(&body, 50);+ assert!(out.ends_with('…'), "expected ellipsis, got: {out}");+ // Hard cap check: the returned string MUST NOT exceed `max` bytes+ // including the ellipsis. Earlier the helper appended `…` after+ // slicing to `max`, which leaked 3 bytes past the advertised cap;+ // CR flagged this. Now the cap is strict.+ assert!(+ out.len() <= 50,+ "output ({} bytes) exceeded advertised cap of 50",+ out.len()+ );+}++#[test]+fn extract_error_detail_with_max_below_ellipsis_returns_empty() {+ // Edge case: when `max` is smaller than the ellipsis byte length+ // (3 bytes), there's no room for any content + ellipsis, so the+ // helper must return an empty string rather than panic or emit a+ // partial codepoint.+ let body = "€".repeat(10);+ assert_eq!(extract_error_detail(&body, 2), "");+}++#[test]+fn extract_error_detail_envelope_missing_error_field_falls_back() {+ let body = r#"{"success":false}"#;+ // No `error` key — fall back to truncated raw body so the caller+ // still has *something* to grep for.+ assert_eq!(extract_error_detail(body, 500), body);+}++#[test]+fn extract_error_detail_envelope_blank_error_falls_back() {+ let body = r#"{"success":false,"error":" "}"#;+ assert_eq!(extract_error_detail(body, 500), body);+}++#[test]+fn managed_budget_gate_applies_to_agent_integration_paths() {+ assert!(managed_budget_applies_to_path(+ "/agent-integrations/composio/execute"+ ));+ assert!(managed_budget_applies_to_path(+ "/agent-integrations/parallel/search"+ ));+ assert!(!managed_budget_applies_to_path(+ "/agent-integrations/pricing"+ ));+ assert!(!managed_budget_applies_to_path("/teams/me/usage"));+}++// ── Unit: local-only egress enforcement (privacy epic S7, #4441) ──++#[test]+fn backend_egress_descriptor_strips_query_and_targets_backend() {+ let desc = backend_egress_descriptor("/agent-integrations/composio/execute?foo=bar");+ assert_eq!(desc.reason, crate::security::EgressReason::Integration);+ assert_eq!(desc.provider_slug, "openhuman_backend");+ // Query stripped — only the endpoint is disclosed, never carried data.+ assert_eq!(desc.service, "/agent-integrations/composio/execute");+ assert!(desc.is_external);+}++#[test]+fn enforce_backend_egress_blocks_user_data_but_allows_control_plane() {+ use crate::config::PrivacyMode;+ use crate::security::live_policy::test_privacy_scope;+ {+ // Thread-scoped LocalOnly — no process-global mutation, no cross-test race.+ let _mode = test_privacy_scope(PrivacyMode::LocalOnly);+ // User-data tool path → refused.+ let blocked = enforce_backend_egress("/agent-integrations/composio/execute");+ assert!(blocked.is_err());+ assert!(blocked+ .unwrap_err()+ .to_string()+ .contains("Local-only privacy mode is active"));+ // Control-plane (connection-management + pricing) → allowed even under LocalOnly.+ enforce_backend_egress("/agent-integrations/composio/connections")+ .expect("connections is control-plane");+ enforce_backend_egress("/agent-integrations/pricing").expect("pricing is control-plane");+ }++ // Standard mode → everything allowed.+ let _mode = test_privacy_scope(PrivacyMode::Standard);+ enforce_backend_egress("/agent-integrations/composio/execute").expect("Standard allows");+}++/// Privacy epic S7 (#4441): the LocalOnly gate must fire through the PUBLIC verb+/// methods, not only via the `enforce_backend_egress` helper. Each of the six+/// verbs (`post`/`get`/`patch`/`delete`/`upload_multipart`/`get_bytes`) runs the+/// gate synchronously on first poll — before any `.await` — so a user-data path+/// is refused before the request leaves the device. The client points at an+/// unreachable address, so a leaked call would surface a transport error, not+/// the local-only message; asserting the policy string therefore proves the+/// short-circuit fired end-to-end through the verb, not just the helper.+#[tokio::test]+async fn verb_methods_block_user_data_egress_under_local_only() {+ use crate::config::PrivacyMode;+ use crate::security::live_policy::test_privacy_scope;++ let _mode = test_privacy_scope(PrivacyMode::LocalOnly);+ let client = client_for("http://127.0.0.1:0".into());+ let path = "/agent-integrations/composio/execute"; // user-data egress (blocked)+ let body = json!({ "arguments": { "secret": "leak-me" } });++ let assert_blocked = |verb: &str, msg: String| {+ assert!(+ msg.contains("Local-only privacy mode is active"),+ "{verb}: expected a local-only block before network, got: {msg}"+ );+ };++ assert_blocked(+ "post",+ client+ .post::<serde_json::Value>(&Default::default(), path, &body)+ .await+ .unwrap_err()+ .to_string(),+ );+ assert_blocked(+ "get",+ client+ .get::<serde_json::Value>(&Default::default(), path)+ .await+ .unwrap_err()+ .to_string(),+ );+ assert_blocked(+ "patch",+ client+ .patch::<serde_json::Value>(&Default::default(), path, &body)+ .await+ .unwrap_err()+ .to_string(),+ );+ assert_blocked(+ "delete",+ client+ .delete::<serde_json::Value>(&Default::default(), path)+ .await+ .unwrap_err()+ .to_string(),+ );+ assert_blocked(+ "upload_multipart",+ client+ .upload_multipart::<serde_json::Value>(+ &Default::default(),+ path,+ reqwest::multipart::Form::new(),+ )+ .await+ .unwrap_err()+ .to_string(),+ );+ assert_blocked(+ "get_bytes",+ client+ .get_bytes(&Default::default(), path)+ .await+ .unwrap_err()+ .to_string(),+ );+}++/// The OpenHuman compatibility wrapper must retain the SDK's privileged-route+/// denylist on every public verb, including the temporary reqwest download+/// exception. An unreachable base URL makes a transport error the failure+/// mode if any request gets past the local gate.+#[tokio::test]+async fn verb_methods_never_expose_admin_or_webhook_routes() {+ let client = client_for("http://127.0.0.1:0".into());+ let body = json!({});+ let assert_blocked = |verb: &str, error: anyhow::Error| {+ let message = error.to_string();+ assert!(+ message.contains("route is intentionally not exposed by the SDK"),+ "{verb}: expected SDK route denylist, got: {message}"+ );+ };++ assert_blocked(+ "get",+ client+ .get::<serde_json::Value>(&Default::default(), "/coupons/admin")+ .await+ .unwrap_err(),+ );+ assert_blocked(+ "post",+ client+ .post::<serde_json::Value>(&Default::default(), "/admin/announcements", &body)+ .await+ .unwrap_err(),+ );+ assert_blocked(+ "patch",+ client+ .patch::<serde_json::Value>(&Default::default(), "/webhooks/core/hook-1", &body)+ .await+ .unwrap_err(),+ );+ assert_blocked(+ "delete",+ client+ .delete::<serde_json::Value>(&Default::default(), "/webhooks/core/hook-1")+ .await+ .unwrap_err(),+ );+ assert_blocked(+ "upload_multipart",+ client+ .upload_multipart::<serde_json::Value>(+ &Default::default(),+ "/webhooks/composio",+ reqwest::multipart::Form::new(),+ )+ .await+ .unwrap_err(),+ );+ assert_blocked(+ "get_bytes",+ client+ .get_bytes(&Default::default(), "/webhooks/core")+ .await+ .unwrap_err(),+ );+}++#[tokio::test]+async fn integration_requests_carry_the_host_attribution() {+ // The installed transport (here the `cfg(test)` plain one) stamps the+ // host's product identity; which identity it is belongs to the host.+ let seen = product_identity_seen_by_backend().await;+ assert_eq!(+ seen.sdk.as_deref(),+ Some(crate::backend::transport::plain::TEST_PRODUCT_IDENTITY),+ "agent-integration traffic must be attributed like every other backend call"+ );+ assert_eq!(+ seen.download.as_deref(),+ None,+ "the download transport must stay untagged — it follows a 302 to presigned \+ storage and reqwest keeps non-sensitive headers across the cross-host hop"+ );+}++#[tokio::test]+async fn post_400_propagates_backend_error_envelope_message() {+ // Mirror the real backend BadRequestError shape from+ // `backend-openhuman/src/middlewares/errorHandler.ts` — the 400+ // body is JSON `{ success:false, error:"<msg>" }`.+ let app = Router::new().route(+ "/agent-integrations/composio/execute",+ post(|| async {+ (+ StatusCode::BAD_REQUEST,+ Json(json!({ "success": false, "error": "Insufficient balance" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/execute",+ &json!({ "tool": "GMAIL_FETCH_EMAILS" }),+ )+ .await+ .expect_err("400 must surface as Err");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("Insufficient balance"),+ "expected backend error in propagated message, got: {msg}"+ );+ assert!(msg.contains("400"), "expected status code, got: {msg}");+}++#[tokio::test]+async fn post_500_propagates_html_body_truncated() {+ let app = Router::new().route(+ "/foo",+ post(|| async {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "<html>upstream blew up</html>",+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(&Default::default(), "/foo", &json!({}))+ .await+ .expect_err("500 must surface as Err");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("upstream blew up"),+ "expected raw body in propagated message, got: {msg}"+ );+}++#[tokio::test]+async fn local_only_rejects_user_data_verb_before_transport() {+ // End-to-end proof (privacy epic S7, #4441) that a PUBLIC verb+ // (`post`/`get`) — not just the private `enforce_backend_egress` helper —+ // honours LocalOnly and refuses a user-data backend call BEFORE it hits+ // transport. The mock 403s on every route it actually receives, so if the+ // gate short-circuits first the error is the policy message, never the+ // mock body.+ use crate::config::PrivacyMode;+ use crate::security::live_policy::test_privacy_scope;++ let app = Router::new()+ .route(+ "/agent-integrations/composio/execute",+ post(|| async {+ (+ StatusCode::FORBIDDEN,+ Json(json!({ "success": false, "error": "mock must not be reached" })),+ )+ .into_response()+ }),+ )+ .route(+ "/agent-integrations/composio/connections",+ get(|| async {+ (+ StatusCode::FORBIDDEN,+ Json(json!({ "success": false, "error": "control-plane reached transport" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);++ // `#[tokio::test]` runs on a current-thread runtime, so the gate's inline+ // `current_privacy_mode()` read observes this override on the same thread+ // (see `TEST_PRIVACY_MODE`).+ let _mode = test_privacy_scope(PrivacyMode::LocalOnly);++ // (1) User-data verb call is refused by the gate BEFORE transport — the+ // error carries the policy message and NOT the mock's 403 body.+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/execute",+ &json!({ "tool": "GMAIL_FETCH_EMAILS" }),+ )+ .await+ .expect_err("LocalOnly must block the user-data POST before transport");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("Local-only privacy mode is active"),+ "expected policy block, got: {msg}"+ );+ assert!(+ !msg.contains("mock must not be reached"),+ "gate must short-circuit before the request reaches the mock: {msg}"+ );++ // (2) A control-plane verb call under the SAME LocalOnly scope passes the+ // 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>(+ &Default::default(),+ "/agent-integrations/composio/connections",+ )+ .await+ .expect_err("control-plane reaches transport and surfaces the mock 403");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("control-plane reached transport"),+ "control-plane must reach transport under LocalOnly, got: {msg}"+ );+}++#[tokio::test]+async fn get_403_propagates_backend_error_envelope_message() {+ let app = Router::new().route(+ "/agent-integrations/composio/connections",+ get(|| async {+ (+ StatusCode::FORBIDDEN,+ Json(json!({ "success": false, "error": "Toolkit \"x\" is not enabled" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .get::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/connections",+ )+ .await+ .expect_err("403 must surface as Err");+ let msg = format!("{err:#}");+ assert!(+ msg.contains("Toolkit \"x\" is not enabled"),+ "expected backend error in propagated message, got: {msg}"+ );+ assert!(msg.contains("403"), "expected status code, got: {msg}");+}++// ── OPENHUMAN-TAURI-BC regression: wire format pins to classifier ─++/// Regression guard for OPENHUMAN-TAURI-BC: the exact bail message+/// `IntegrationClient::post` builds for a 4xx user-input failure must+/// classify as `BackendUserError` so the observability layer routes+/// the report through a warn breadcrumb instead of a Sentry event.+///+/// If the format string in `client.rs` drifts away from the prefix+/// `is_backend_user_error_message` matches on, every Composio /+/// integrations 4xx will start spamming Sentry again — exactly the+/// regression this guards.+#[tokio::test]+async fn post_400_user_input_failure_classifies_as_backend_user_error() {+ use crate::core::observability::{expected_error_kind, ExpectedErrorKind};++ let app = Router::new().route(+ "/agent-integrations/composio/authorize",+ post(|| async {+ (+ StatusCode::BAD_REQUEST,+ Json(json!({+ "success": false,+ "error": "Composio authorization failed: 400 {\"error\":{\"message\":\"Missing required fields: Tenant Name\",\"slug\":\"ConnectedAccount_MissingRequiredFields\",\"status\":400}}"+ })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/authorize",+ &json!({ "toolkit": "sharepoint" }),+ )+ .await+ .expect_err("400 must surface as Err");+ let msg = format!("{err:#}");++ // The propagated message must still match the classifier — both the+ // `IntegrationClient::post` bail string and the+ // `observability::report_error_or_expected` argument share the same+ // shape, so this is a tight pin against drift on either side.+ //+ // After #1472 wave E added `ProviderUserState` (which matches+ // `"missing required fields"` regardless of HTTP status), the+ // SharePoint shape now lands in the more specific bucket. Either+ // expected-kind silences Sentry; assert the new tighter bucket so+ // a regression in the precedence ordering surfaces here.+ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::ProviderUserState),+ "OPENHUMAN-TAURI-BC: propagated 400 must classify as ProviderUserState (more \+ specific than BackendUserError, takes precedence per #1472 wave E); got: {msg}"+ );+}++/// Counterpart: a 5xx must remain actionable. If the classifier ever+/// over-reaches and silences 5xx, this test catches it before users do.+#[tokio::test]+async fn post_500_remains_actionable() {+ use crate::core::observability::expected_error_kind;++ let app = Router::new().route(+ "/foo",+ post(|| async {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "<html>upstream blew up</html>",+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(&Default::default(), "/foo", &json!({}))+ .await+ .expect_err("500 must surface as Err");+ let msg = format!("{err:#}");+ assert_eq!(+ expected_error_kind(&msg),+ None,+ "5xx must remain actionable, not classified as expected; got: {msg}"+ );+}++// ── Jira subdomain / ConnectedAccount_MissingRequiredFields (issue#1702) ─++/// The Jira authorization flow requires an Atlassian subdomain ("Tenant+/// Name"). When the user submits the form without it, Composio returns a+/// `ConnectedAccount_MissingRequiredFields` error. The error must:+/// 1. Propagate through `IntegrationClient::post` so the RPC layer can+/// surface it to the UI (not silently swallowed).+/// 2. Classify as `BackendUserError` so the observability layer demotes+/// it from a Sentry event to a warn breadcrumb — this is an expected+/// user-input failure, not a product bug.+///+/// The first assertion locks in the error string; the second pins the+/// classifier to `BackendUserError` so future changes to either side+/// (format string in `client.rs` or classifier in `observability.rs`)+/// are caught at review rather than in production.+#[tokio::test]+async fn jira_missing_subdomain_error_propagates_and_classifies_as_user_error() {+ use crate::core::observability::{expected_error_kind, ExpectedErrorKind};++ let app = Router::new().route(+ "/agent-integrations/composio/authorize",+ post(|| async {+ (+ StatusCode::BAD_REQUEST,+ Json(json!({+ "success": false,+ "error": "Composio authorization failed: 400 {\"error\":{\"message\":\"Missing required fields: Tenant Name\",\"slug\":\"ConnectedAccount_MissingRequiredFields\",\"status\":400}}"+ })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/authorize",+ &json!({ "toolkit": "jira" }),+ )+ .await+ .expect_err("Jira missing-subdomain must surface as Err");+ let msg = format!("{err:#}");++ // 1. The error string from the Composio payload must propagate so the+ // UI can show "Missing required fields: Tenant Name" in the connect+ // form and prompt for the Atlassian subdomain.+ assert!(+ msg.contains("Tenant Name") || msg.contains("ConnectedAccount_MissingRequiredFields"),+ "Jira missing-subdomain error must propagate; got: {msg}"+ );++ // 2. The classifier must route this as an expected user-input failure —+ // not a Sentry-reportable product error. After #1472 wave E added the+ // `ProviderUserState` bucket (which anchors on+ // `"missing required fields"` regardless of HTTP status, so it also+ // catches the 500-wrapped composio variant), the Jira missing-subdomain+ // shape lands there rather than in the generic `BackendUserError`+ // bucket. Either expected-kind silences Sentry — assert the tighter+ // bucket so a regression in the precedence ordering surfaces here.+ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::ProviderUserState),+ "Jira ConnectedAccount_MissingRequiredFields must classify as ProviderUserState \+ (more specific than BackendUserError per #1472 wave E); got: {msg}"+ );+}++/// Complementary: a Jira 400 where the slug is *not*+/// `ConnectedAccount_MissingRequiredFields` (e.g. a token revocation)+/// must still classify as `BackendUserError` via the outer 400 shape —+/// not as an unexpected error that would create Sentry noise.+#[tokio::test]+async fn jira_generic_400_classifies_as_backend_user_error() {+ use crate::core::observability::{expected_error_kind, ExpectedErrorKind};++ let app = Router::new().route(+ "/agent-integrations/composio/authorize",+ post(|| async {+ (+ StatusCode::BAD_REQUEST,+ Json(json!({+ "success": false,+ "error": "Composio authorization failed: 400 {\"error\":{\"message\":\"Invalid subdomain\",\"slug\":\"ConnectedAccount_InvalidSubdomain\",\"status\":400}}"+ })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/authorize",+ &json!({ "toolkit": "jira" }),+ )+ .await+ .expect_err("400 must surface as Err");+ let msg = format!("{err:#}");+ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::BackendUserError),+ "Jira generic 400 must classify as BackendUserError; got: {msg}"+ );+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client_session_expiry_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client_session_expiry_tests.rsnew file mode 100644index 0000000000..4c580411a9--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client_session_expiry_tests.rs@@ -0,0 +1,311 @@+use super::*;++// ── TAURI-RUST-84E: session-JWT 401 → session-expiry recovery ─────++/// Root-cause regression guard for TAURI-RUST-84E. A `401 Unauthorized` from+/// the OpenHuman backend's `/agent-integrations/*` routes is the backend+/// rejecting our app-session JWT. The propagated error string MUST:+/// 1. classify as `SessionExpired` (so it stays demoted from Sentry — the+/// noise suppression the prior fix established), AND+/// 2. be recognised by `is_session_expired_message` (the same predicate the+/// JSON-RPC dispatcher uses to publish `DomainEvent::SessionExpired` and+/// drive re-login).+///+/// This couples the exact wire string `IntegrationClient::post`/`get` builds+/// for a session-JWT 401 to the session-expiry classifier — if either side+/// drifts, web_search (and every other backend-proxied tool) would silently+/// stop driving re-login on session expiry, leaving the user stuck behind an+/// opaque "parallel search failed: Invalid token" with no sign-in nudge.+#[tokio::test]+async fn post_401_session_jwt_classifies_as_session_expired() {+ use crate::core::observability::{+ expected_error_kind, is_session_expired_message, ExpectedErrorKind,+ };++ // Canonical TAURI-RUST-84E shape: backend auth middleware rejects the+ // session JWT with `401 {"error":"Invalid token"}`.+ let app = Router::new().route(+ "/agent-integrations/parallel/search",+ post(|| async {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "Invalid token" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/parallel/search",+ &json!({ "objective": "x" }),+ )+ .await+ .expect_err("401 must surface as Err");+ let msg = format!("{err:#}");++ // The propagated message carries the SESSION_EXPIRED sentinel so the model+ // (and any caller that wraps it, e.g. `parallel search failed: {e:#}`)+ // sees an actionable "sign in again" instruction.+ assert!(+ msg.contains("SESSION_EXPIRED"),+ "session-JWT 401 must carry the SESSION_EXPIRED sentinel; got: {msg}"+ );++ // 1. Demotes from Sentry: classifies as SessionExpired (expected kind),+ // not a hard error.+ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::SessionExpired),+ "session-JWT 401 must classify as SessionExpired (stays demoted from Sentry); got: {msg}"+ );++ // 2. Recognised by the session-expiry predicate that the JSON-RPC+ // dispatcher keys `DomainEvent::SessionExpired` publication on — so the+ // re-login flow fires (the client also publishes it directly to cover+ // the swallowing agent loop, but this keeps the propagation path+ // correct too).+ assert!(+ is_session_expired_message(&msg),+ "session-JWT 401 must be recognised by is_session_expired_message so re-login \+ fires; got: {msg}"+ );+}++/// GET counterpart — the connections/toolkits/pricing reads must drive the+/// same session-expiry recovery on a session-JWT 401.+#[tokio::test]+async fn get_401_session_jwt_classifies_as_session_expired() {+ use crate::core::observability::{+ expected_error_kind, is_session_expired_message, ExpectedErrorKind,+ };++ let app = Router::new().route(+ "/agent-integrations/composio/connections",+ get(|| async {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "Invalid token" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .get::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/connections",+ )+ .await+ .expect_err("401 must surface as Err");+ let msg = format!("{err:#}");++ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::SessionExpired),+ "GET session-JWT 401 must classify as SessionExpired; got: {msg}"+ );+ assert!(+ is_session_expired_message(&msg),+ "GET session-JWT 401 must be recognised by is_session_expired_message; got: {msg}"+ );+}++/// Negative guard (task #3 — the key correctness risk): a NON-401 4xx must NOT+/// be turned into session-expiry. A 403 (authz/scope rejection on a+/// backend-mediated resource) or a 400 (user-input failure) must keep the+/// generic `BackendUserError` / `ProviderUserState` classification so we never+/// log the user out for an unrelated integration problem. If the 401 arm ever+/// widened to swallow other statuses, this catches it.+#[tokio::test]+async fn non_401_4xx_does_not_classify_as_session_expired() {+ use crate::core::observability::{expected_error_kind, is_session_expired_message};++ // 403 — e.g. an authz/scope rejection on a backend-mediated provider+ // resource. This is NOT a dead session; it must stay a generic backend+ // user-error and must NOT publish SessionExpired.+ let app = Router::new().route(+ "/agent-integrations/composio/connections",+ get(|| async {+ (+ StatusCode::FORBIDDEN,+ Json(json!({ "success": false, "error": "forbidden" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .get::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/connections",+ )+ .await+ .expect_err("403 must surface as Err");+ let msg = format!("{err:#}");++ assert!(+ !msg.contains("SESSION_EXPIRED"),+ "403 must NOT be turned into a session-expiry sentinel; got: {msg}"+ );+ assert!(+ !is_session_expired_message(&msg),+ "403 must NOT be recognised as session expiry (would log the user out for an \+ unrelated integration authz problem); got: {msg}"+ );+ // It still demotes from Sentry as a generic backend user-error (the prior+ // behaviour), just not as session-expiry.+ assert!(+ expected_error_kind(&msg).is_some(),+ "403 should still classify as an expected backend user-error; got: {msg}"+ );+ assert_ne!(+ expected_error_kind(&msg),+ Some(crate::core::observability::ExpectedErrorKind::SessionExpired),+ "403 must NOT classify as SessionExpired; got: {msg}"+ );+}++// ── Composio "soft" auth path (#4281) ─────────────────────────────++/// The trigger-catalog reads are the only routes treated as "soft" (sentinel+/// surfaced for an in-place CTA, no global sign-out). Every other backend route+/// stays authoritative — a 401 there drives the full re-login.+#[test]+fn composio_soft_auth_path_covers_only_trigger_reads() {+ use super::super::is_composio_soft_auth_path;+ // Soft: GET available catalog (with and without query), GET active-triggers list.+ assert!(is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/triggers/available"+ ));+ assert!(is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/triggers/available?toolkit=gmail&connectionId=ca_x"+ ));+ assert!(is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/triggers"+ ));+ // GET active-triggers list with a `toolkit` query (the `?` boundary).+ assert!(is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/triggers?toolkit=gmail"+ ));+ // Path-boundary guard: a bare prefix must NOT match an unrelated route+ // that merely begins with "triggers" (CodeRabbit catch).+ assert!(!is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/triggersXYZ"+ ));+ // Authoritative — a 401 here must still log the user out:+ // trigger WRITES (enable/disable/create POST to the same path)…+ assert!(!is_composio_soft_auth_path(+ "POST",+ "/agent-integrations/composio/triggers"+ ));+ // …and every non-trigger backend route.+ assert!(!is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/connections"+ ));+ assert!(!is_composio_soft_auth_path(+ "GET",+ "/agent-integrations/composio/toolkits"+ ));+ assert!(!is_composio_soft_auth_path(+ "POST",+ "/agent-integrations/composio/execute"+ ));+ assert!(!is_composio_soft_auth_path(+ "POST",+ "/agent-integrations/parallel/search"+ ));+}++/// A 401 on the trigger-catalog read still carries the `SESSION_EXPIRED`+/// sentinel — the trigger panel classifies it (`CoreRpcError.kind ===+/// 'auth_expired'`) and renders the in-place "Sign in again" CTA. The+/// difference from the authoritative arm (no global `SessionExpired` publish)+/// is asserted via the path gate above; here we lock the wire contract the UI+/// depends on so a future refactor can't silently drop the sentinel and leave+/// the panel with no actionable error (#4281).+#[tokio::test]+async fn get_401_composio_triggers_keeps_sentinel_for_in_place_cta() {+ use crate::core::observability::{+ expected_error_kind, is_session_expired_message, ExpectedErrorKind,+ };++ let app = Router::new().route(+ "/agent-integrations/composio/triggers/available",+ get(|| async {+ (+ StatusCode::UNAUTHORIZED,+ Json(json!({ "success": false, "error": "Invalid token" })),+ )+ .into_response()+ }),+ );+ let base = start_mock_backend(app).await;+ let client = client_for(base);+ let err = client+ .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:#}");++ assert!(+ msg.contains("SESSION_EXPIRED"),+ "triggers 401 must still carry the sentinel so the panel shows the CTA; got: {msg}"+ );+ assert_eq!(+ expected_error_kind(&msg),+ Some(ExpectedErrorKind::SessionExpired),+ "triggers 401 must still classify as SessionExpired (stays demoted from Sentry); got: {msg}"+ );+ assert!(+ is_session_expired_message(&msg),+ "triggers 401 must stay recognisable as session expiry for the frontend classifier; got: {msg}"+ );+}++// ── Unit: `sanitize_backend_url` (issue #2075) ────────────────────++#[test]+fn sanitize_backend_url_strips_inference_path() {+ // Regression: a misconfigured `BACKEND_URL` baked into the build+ // (`https://api.tinyhumans.ai/openai/v1/chat/completions`) used to+ // become every integration call's prefix, producing 404s such as+ // `…/openai/v1/chat/completions/agent-integrations/composio/connections`.+ let cleaned = sanitize_backend_url("https://api.tinyhumans.ai/openai/v1/chat/completions");+ assert_eq!(cleaned, "https://api.tinyhumans.ai");+}++#[test]+fn sanitize_backend_url_idempotent_on_clean_root() {+ let cleaned = sanitize_backend_url("https://api.tinyhumans.ai");+ assert_eq!(cleaned, "https://api.tinyhumans.ai");+}++#[test]+fn sanitize_backend_url_preserves_empty_input() {+ // Empty / unparseable input must round-trip unchanged so we don't+ // overwrite a caller's explicit "no backend" sentinel.+ assert_eq!(sanitize_backend_url(""), "");+}++#[test]+fn integration_client_new_strips_inference_path_from_backend_url() {+ let client = IntegrationClient::new(+ "https://api.tinyhumans.ai/openai/v1/chat/completions".to_string(),+ "token".to_string(),+ );+ assert_eq!(client.backend_url, "https://api.tinyhumans.ai");+}diff --git a/crates/openhuman-tinyhumans/src/integrations/client_tests.rs b/crates/openhuman-tinyhumans/src/integrations/client_tests.rsnew file mode 100644index 0000000000..19623e2618--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/client_tests.rs@@ -0,0 +1,116 @@+//! Tests for the shared integrations HTTP client.+//!+//! Focus: backend error body propagation. Pre-fix, non-2xx responses+//! discarded the body (`let _body_text = …`) leaving callers with a+//! generic `"Backend returned 400 …"` message — see #1296. These tests+//! lock in the new behaviour where `extract_error_detail` pulls the+//! envelope's `error` field (or falls back to truncated raw text) and+//! the bail message includes it.++use super::*;+use axum::{+ http::StatusCode,+ response::IntoResponse,+ routing::{get, post},+ Json, Router,+};+use serde_json::json;+use std::sync::Arc;++// ── Integration: HTTP error propagation through `post`/`get` ──────++async fn start_mock_backend(app: Router) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ format!("http://127.0.0.1:{}", addr.port())+}++fn client_for(base: String) -> IntegrationClient {+ IntegrationClient::new(base, "test-token".into())+}++/// The `x-sdk-name` each of `IntegrationClient`'s two transports sent.+///+/// The verb methods go out through the SDK and are tagged. `get_bytes` drives+/// the separate `download_client`, which deliberately is NOT tagged: it follows+/// a 302 to presigned S3 storage, and reqwest preserves non-sensitive headers+/// across a cross-host redirect, so tagging it would hand the product identity+/// to the storage provider. Two independent transports with deliberately+/// opposite expectations, so both are asserted.+struct ProductIdentitySeen {+ sdk: Option<String>,+ download: Option<String>,+}++async fn product_identity_seen_by_backend() -> ProductIdentitySeen {+ use crate::backend::transport::plain::TEST_PRODUCT_HEADER as PRODUCT_IDENTITY_HEADER;++ fn sink_header(sink: &Arc<std::sync::Mutex<Option<String>>>, headers: &axum::http::HeaderMap) {+ *sink.lock().unwrap() = headers+ .get(PRODUCT_IDENTITY_HEADER)+ .and_then(|value| value.to_str().ok())+ .map(str::to_string);+ }++ let sdk_seen: Arc<std::sync::Mutex<Option<String>>> = Arc::new(std::sync::Mutex::new(None));+ let download_seen: Arc<std::sync::Mutex<Option<String>>> =+ Arc::new(std::sync::Mutex::new(None));+ let sdk_sink = sdk_seen.clone();+ let download_sink = download_seen.clone();++ let app = Router::new()+ .route(+ "/agent-integrations/composio/execute",+ post(move |headers: axum::http::HeaderMap| {+ let sink = sdk_sink.clone();+ async move {+ sink_header(&sink, &headers);+ Json(json!({ "success": true, "data": {} })).into_response()+ }+ }),+ )+ .route(+ "/agent-integrations/file-storage/files/f1/download",+ get(move |headers: axum::http::HeaderMap| {+ let sink = download_sink.clone();+ async move {+ sink_header(&sink, &headers);+ "file-bytes".into_response()+ }+ }),+ );+ let base = start_mock_backend(app).await;++ let client = client_for(base);+ let sdk_result = client+ .post::<serde_json::Value>(+ &Default::default(),+ "/agent-integrations/composio/execute",+ &json!({}),+ )+ .await;+ let download_result = client+ .get_bytes(+ &Default::default(),+ "/agent-integrations/file-storage/files/f1/download",+ )+ .await;++ sdk_result.expect("mock backend returns a success envelope");+ download_result.expect("mock backend returns file bytes");++ let sdk = sdk_seen.lock().unwrap().clone();+ let download = download_seen.lock().unwrap().clone();+ ProductIdentitySeen { sdk, download }+}++#[path = "client_error_propagation_tests.rs"]+mod error_propagation_tests;+#[path = "client_session_expiry_tests.rs"]+mod session_expiry_tests;++#[path = "client_api_key_tests.rs"]+mod api_key_tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/mod.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/mod.rsnew file mode 100644index 0000000000..0b5f2f2f00--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/mod.rs@@ -0,0 +1,17 @@+//! File storage domain — agent tools for managed cloud file storage backed by+//! the OpenHuman backend's `file_storage` provider+//! (`/agent-integrations/file-storage/*`, S3 under the hood).+//!+//! The backend owns the bucket, billing (S3 rates + margin, charged via the+//! standard integration billing flow), per-user quota (1 GiB), and TTL+//! enforcement (7 days free / up to 1 year paid); these tools upload from and+//! download into the agent's action dir and expose list / link / visibility /+//! delete operations.++pub mod tools;+pub mod types;++pub use tools::{+ build_file_storage_tools, StorageDeleteFileTool, StorageDownloadFileTool, StorageGetLinkTool,+ StorageListFilesTool, StorageSetVisibilityTool, StorageUploadFileTool,+};diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/delete.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/delete.rsnew file mode 100644index 0000000000..a9744c4032--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/delete.rs@@ -0,0 +1,112 @@+//! `storage_delete_file` — permanently delete a stored file.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::{file_path, readonly_autonomy_block, validate_file_id};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;+use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};++use crate::integrations::file_storage::types::DeleteResponse;++pub struct StorageDeleteFileTool {+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+}++impl StorageDeleteFileTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self::new_with_security(client, Arc::new(SecurityPolicy::default()))+ }++ pub fn new_with_security(+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+ ) -> Self {+ Self { client, security }+ }+}++#[async_trait]+impl Tool for StorageDeleteFileTool {+ fn name(&self) -> &str {+ "storage_delete_file"+ }++ fn description(&self) -> &str {+ "Permanently delete a file from managed cloud file storage, freeing quota. \+ Deletion is free and cannot be undone."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "file_id": { "type": "string", "description": "The stored file's id" }+ },+ "required": ["file_id"]+ })+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Write+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn external_effect(&self) -> bool {+ true+ }++ 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 StorageDeleteFileTool {+ /// 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> {+ if let Some(blocked) = readonly_autonomy_block(&self.security) {+ return Ok(blocked);+ }++ let file_id = match validate_file_id(&args) {+ Ok(id) => id,+ Err(e) => return Ok(ToolResult::error(e)),+ };+ tracing::debug!("[file_storage] deleting file_id={file_id}");+ match self+ .client+ .delete::<DeleteResponse>(approval, &file_path(&file_id, ""))+ .await+ {+ Ok(resp) if resp.deleted => Ok(ToolResult::success_with_markdown(+ json!({ "file_id": file_id, "deleted": true }),+ format!("Deleted file {file_id}."),+ )),+ Ok(_) => Ok(ToolResult::error(format!(+ "Backend did not confirm deletion of file {file_id}"+ ))),+ Err(e) => Ok(ToolResult::error(format!("Failed to delete file: {e}"))),+ }+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/download.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/download.rsnew file mode 100644index 0000000000..f065c1ed96--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/download.rs@@ -0,0 +1,168 @@+//! `storage_download_file` — download a stored file into the agent workspace.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::{+ action_dir_for_context, extension_for_content_type, file_path, readonly_autonomy_block,+ sanitize_filename, validate_file_id, DOWNLOADS_DIR,+};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;+use tinytools::ToolRunContext;+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolResult};++pub struct StorageDownloadFileTool {+ client: Arc<IntegrationClient>,+ action_dir: PathBuf,+ security: Arc<SecurityPolicy>,+}++impl StorageDownloadFileTool {+ pub fn new(client: Arc<IntegrationClient>, action_dir: PathBuf) -> Self {+ Self::new_with_security(client, action_dir, Arc::new(SecurityPolicy::default()))+ }++ pub fn new_with_security(+ client: Arc<IntegrationClient>,+ action_dir: PathBuf,+ security: Arc<SecurityPolicy>,+ ) -> Self {+ Self {+ client,+ action_dir,+ security,+ }+ }++ async fn run(+ &self,+ args: Value,+ action_dir: &Path,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ if let Some(blocked) = readonly_autonomy_block(&self.security) {+ return Ok(blocked);+ }++ let file_id = match validate_file_id(&args) {+ Ok(id) => id,+ Err(e) => return Ok(ToolResult::error(e)),+ };+ let requested_name = args+ .get("filename")+ .and_then(|v| v.as_str())+ .and_then(sanitize_filename);++ tracing::debug!("[file_storage] downloading file_id={file_id}");+ let (body, content_type, server_name) = match self+ .client+ .get_bytes(approval, &file_path(&file_id, "/download"))+ .await+ {+ Ok(t) => t,+ Err(e) => return Ok(ToolResult::error(format!("File download failed: {e}"))),+ };++ // Naming: explicit arg > server Content-Disposition > file_id + a+ // content-type-derived extension (mirrors persist_media's scheme).+ let filename = requested_name+ .or_else(|| server_name.as_deref().and_then(sanitize_filename))+ .unwrap_or_else(|| {+ format!(+ "{file_id}.{}",+ extension_for_content_type(content_type.as_deref())+ )+ });++ let dir = action_dir.join(DOWNLOADS_DIR);+ if let Err(e) = tokio::fs::create_dir_all(&dir).await {+ return Ok(ToolResult::error(format!(+ "failed to create downloads dir {}: {e}",+ dir.display()+ )));+ }+ let path = dir.join(&filename);+ if let Err(e) = tokio::fs::write(&path, &body).await {+ return Ok(ToolResult::error(format!(+ "failed to write {}: {e}",+ path.display()+ )));+ }+ tracing::debug!(+ "[file_storage] saved file_id={} → {} ({} bytes)",+ file_id,+ path.display(),+ body.len()+ );++ let payload = json!({+ "file_id": file_id,+ "path": path.display().to_string(),+ "size": body.len(),+ "content_type": content_type,+ });+ Ok(ToolResult::success_with_markdown(+ payload,+ format!(+ "Downloaded file {} ({} bytes) → {}",+ file_id,+ body.len(),+ path.display()+ ),+ ))+ }+}++#[async_trait]+impl Tool for StorageDownloadFileTool {+ fn name(&self) -> &str {+ "storage_download_file"+ }++ fn description(&self) -> &str {+ "Download a file from managed cloud file storage into the agent workspace and \+ return the saved local path. Egress is billed at S3 rates plus margin."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "file_id": { "type": "string", "description": "The stored file's id (from storage_upload_file / storage_list_files)" },+ "filename": { "type": "string", "description": "Optional local filename to save as (defaults to the stored filename)" }+ },+ "required": ["file_id"]+ })+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Write+ }++ fn external_effect(&self) -> bool {+ true+ }++ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ self.run(args, &self.action_dir, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: Value,+ _options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let action_dir = action_dir_for_context(&self.action_dir, context, self.name());+ let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);+ self.run(args, &action_dir, &approval).await+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rsnew file mode 100644index 0000000000..82556bf092--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/helpers.rs@@ -0,0 +1,202 @@+//! Shared path/id/mime helpers used by every file-storage tool.++use std::path::{Path, PathBuf};++use serde_json::Value;+use tinytools::ToolRunContext;++use crate::security::SecurityPolicy;+use tinytools::ToolResult;++pub(super) const FILES_PATH: &str = "/agent-integrations/file-storage/files";++/// Subdirectory (under `action_dir`) where downloaded files are stored.+/// Mirrors `media_generation`'s `generated-media/` root — the action dir is+/// the agent's canonical read/write root, so this stays read-only-container+/// compatible.+pub(super) const DOWNLOADS_DIR: &str = "storage-downloads";++/// Resolve `raw` (absolute or relative to `action_dir`) to a canonical path+/// and reject anything that escapes the action dir (the agent's workspace).+/// The file must exist — canonicalization also resolves symlinks, so a+/// symlink pointing outside the workspace is rejected too.+pub(super) fn resolve_upload_path(action_dir: &Path, raw: &str) -> Result<PathBuf, String> {+ let candidate = {+ let p = Path::new(raw);+ if p.is_absolute() {+ p.to_path_buf()+ } else {+ action_dir.join(p)+ }+ };+ let root = action_dir.canonicalize().map_err(|e| {+ format!(+ "workspace dir {} is not accessible: {e}",+ action_dir.display()+ )+ })?;+ let resolved = candidate.canonicalize().map_err(|e| {+ format!(+ "path {} does not exist or is not readable: {e}",+ candidate.display()+ )+ })?;+ if !resolved.starts_with(&root) {+ return Err(format!(+ "path {} escapes the agent workspace ({}) — only files inside the workspace can be uploaded",+ raw,+ root.display()+ ));+ }+ if !resolved.is_file() {+ return Err(format!("path {} is not a regular file", resolved.display()));+ }+ Ok(resolved)+}++/// Validate a caller-supplied file id before interpolating it into a URL+/// path segment.+pub(super) fn validate_file_id(args: &Value) -> Result<String, String> {+ let id = args+ .get("file_id")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .unwrap_or_default();+ if id.is_empty() {+ return Err("file_id is required".to_string());+ }+ if !id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ {+ return Err(format!("file_id '{id}' contains invalid characters"));+ }+ Ok(id.to_string())+}++/// Parse + validate a `visibility` arg value.+pub(super) fn validate_visibility(raw: &str) -> Result<String, String> {+ match raw.trim().to_ascii_lowercase().as_str() {+ v @ ("public" | "private") => Ok(v.to_string()),+ other => Err(format!(+ "visibility must be 'public' or 'private' (got '{other}')"+ )),+ }+}++/// Strip path separators / traversal from a caller- or server-supplied+/// filename so it always lands directly inside the downloads dir.+pub(super) fn sanitize_filename(name: &str) -> Option<String> {+ let base = name+ .rsplit(['/', '\\'])+ .next()+ .unwrap_or(name)+ .trim()+ .trim_matches('.');+ if base.is_empty() {+ return None;+ }+ let safe: String = base+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ' ') {+ c+ } else {+ '_'+ }+ })+ .collect();+ let safe = safe.trim().to_string();+ if safe.is_empty() {+ None+ } else {+ Some(safe)+ }+}++/// Pick a file extension from a content type (mirrors+/// `media_generation::download::extension_for`'s content-type branch, plus+/// common document types).+pub(super) fn extension_for_content_type(content_type: Option<&str>) -> &'static str {+ let Some(ct) = content_type else { return "bin" };+ let ct = ct.to_ascii_lowercase();+ for (needle, ext) in [+ ("png", "png"),+ ("webp", "webp"),+ ("jpeg", "jpg"),+ ("jpg", "jpg"),+ ("gif", "gif"),+ ("mp4", "mp4"),+ ("webm", "webm"),+ ("pdf", "pdf"),+ ("zip", "zip"),+ ("json", "json"),+ ("csv", "csv"),+ ("html", "html"),+ ("text/plain", "txt"),+ ] {+ if ct.contains(needle) {+ return ext;+ }+ }+ "bin"+}++/// Guess a mime type from a filename extension for the multipart upload+/// part. Best-effort — the backend stores whatever we send and S3 doesn't+/// care; unknown extensions fall back to `application/octet-stream`.+pub(super) fn mime_for_path(path: &Path) -> &'static str {+ match path+ .extension()+ .and_then(|e| e.to_str())+ .map(|e| e.to_ascii_lowercase())+ .as_deref()+ {+ Some("png") => "image/png",+ Some("jpg" | "jpeg") => "image/jpeg",+ Some("gif") => "image/gif",+ Some("webp") => "image/webp",+ Some("mp4") => "video/mp4",+ Some("webm") => "video/webm",+ Some("pdf") => "application/pdf",+ Some("zip") => "application/zip",+ Some("json") => "application/json",+ Some("csv") => "text/csv",+ Some("html" | "htm") => "text/html",+ Some("txt" | "md" | "log") => "text/plain",+ _ => "application/octet-stream",+ }+}++/// Resolve the effective action dir for a call, preferring the TinyAgents+/// workspace from the execution context (mirrors `media_generation`).+pub(super) fn action_dir_for_context(+ default_action_dir: &Path,+ context: Option<&dyn ToolRunContext>,+ tool_name: &str,+) -> PathBuf {+ if let Some(workspace) = context.and_then(|ctx| ctx.workspace()) {+ tracing::debug!(+ tool = tool_name,+ workspace_root = %workspace.root.display(),+ policy_id = %workspace.policy_id,+ "[file_storage] using ToolExecutionContext workspace root"+ );+ return workspace.root.clone();+ }+ default_action_dir.to_path_buf()+}++pub(super) fn file_path(file_id: &str, suffix: &str) -> String {+ format!("{FILES_PATH}/{file_id}{suffix}")+}++pub(super) fn readonly_autonomy_block(security: &SecurityPolicy) -> Option<ToolResult> {+ if security.can_act() {+ None+ } else {+ Some(ToolResult::error(+ "[policy-blocked] Action blocked: autonomy is read-only",+ ))+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/link.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/link.rsnew file mode 100644index 0000000000..e1d312d810--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/link.rs@@ -0,0 +1,129 @@+//! `storage_get_link` — presigned short-lived download link for a stored file.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::{file_path, readonly_autonomy_block, validate_file_id};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;+use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};++use crate::integrations::file_storage::types::LinkResponse;++pub struct StorageGetLinkTool {+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+}++impl StorageGetLinkTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self::new_with_security(client, Arc::new(SecurityPolicy::default()))+ }++ pub fn new_with_security(+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+ ) -> Self {+ Self { client, security }+ }+}++#[async_trait]+impl Tool for StorageGetLinkTool {+ fn name(&self) -> &str {+ "storage_get_link"+ }++ fn description(&self) -> &str {+ "Generate a short-lived presigned download link for a stored file (works for \+ private files; 60s to 7 days, default 1 hour). Link generation is billed as \+ egress at S3 rates plus margin. For a stable permanent URL, set the file's \+ visibility to public instead."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "file_id": { "type": "string", "description": "The stored file's id" },+ "expires_in_seconds": { "type": "integer", "minimum": 60, "maximum": 604800, "description": "Link lifetime in seconds (default 3600)" }+ },+ "required": ["file_id"]+ })+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Write+ }++ fn external_effect(&self) -> bool {+ true+ }++ 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 StorageGetLinkTool {+ /// 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> {+ if let Some(blocked) = readonly_autonomy_block(&self.security) {+ return Ok(blocked);+ }++ let file_id = match validate_file_id(&args) {+ Ok(id) => id,+ Err(e) => return Ok(ToolResult::error(e)),+ };+ let mut body = json!({});+ if let Some(secs) = args.get("expires_in_seconds").and_then(|v| v.as_u64()) {+ body["expiresInSeconds"] = json!(secs.clamp(60, 604_800));+ }+ tracing::debug!("[file_storage] generating link for file_id={file_id}");+ match self+ .client+ .post::<LinkResponse>(approval, &file_path(&file_id, "/link"), &body)+ .await+ {+ Ok(resp) => Ok(ToolResult::success_with_markdown(+ json!({+ "file_id": file_id,+ "url": resp.url,+ "expires_at": resp.expires_at,+ "cost_usd": resp.cost_usd,+ }),+ format!(+ "Presigned link for {} (expires {}): {}\nCost: ${:.4}",+ file_id,+ resp.expires_at.as_deref().unwrap_or("unknown"),+ resp.url,+ resp.cost_usd+ ),+ )),+ Err(e) => Ok(ToolResult::error(format!(+ "Failed to generate download link: {e}"+ ))),+ }+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/list.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/list.rsnew file mode 100644index 0000000000..9e0b46161b--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/list.rs@@ -0,0 +1,105 @@+//! `storage_list_files` — list stored files and quota usage.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::FILES_PATH;+use crate::integrations::IntegrationClient;+use tinytools::{Tool, ToolCategory, ToolResult};++use crate::integrations::file_storage::types::{FileMeta, ListFilesResponse};++pub struct StorageListFilesTool {+ client: Arc<IntegrationClient>,+}++impl StorageListFilesTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StorageListFilesTool {+ fn name(&self) -> &str {+ "storage_list_files"+ }++ fn description(&self) -> &str {+ "List your files in managed cloud file storage with sizes, visibility, expiry, \+ and current storage usage against the 1 GiB quota. Listing is free."+ }++ fn parameters_schema(&self) -> Value {+ json!({ "type": "object", "properties": {} })+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ 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>(approval, FILES_PATH)+ .await+ {+ Ok(resp) => {+ let mut lines = vec![format!(+ "{} file(s), using {} of {} bytes:",+ resp.files.len(),+ resp.usage.used_bytes,+ resp.usage.limit_bytes+ )];+ for f in &resp.files {+ lines.push(format!(+ "- {} — {} ({} bytes, {}, expires {}){}",+ f.file_id,+ f.filename,+ f.size,+ f.visibility,+ f.expires_at.as_deref().unwrap_or("unknown"),+ f.public_url+ .as_deref()+ .map(|u| format!(" — {u}"))+ .unwrap_or_default(),+ ));+ }+ let payload = json!({+ "files": resp.files.iter().map(FileMeta::to_json).collect::<Vec<_>>(),+ "next_cursor": resp.next_cursor,+ "usage": {+ "used_bytes": resp.usage.used_bytes,+ "limit_bytes": resp.usage.limit_bytes,+ },+ });+ Ok(ToolResult::success_with_markdown(payload, lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!("Failed to list files: {e}"))),+ }+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/mod.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/mod.rsnew file mode 100644index 0000000000..2dc77d2642--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/mod.rs@@ -0,0 +1,42 @@+//! Agent-facing file-storage tools backed by the OpenHuman backend's+//! `file_storage` provider (S3 under the hood).+//!+//! **Endpoints** (see the file-storage API contract):+//! - `POST /agent-integrations/file-storage/files` (multipart upload)+//! - `GET /agent-integrations/file-storage/files` (list)+//! - `GET /agent-integrations/file-storage/files/{id}/download` (302 → presigned S3)+//! - `POST /agent-integrations/file-storage/files/{id}/link` (presigned link)+//! - `PATCH /agent-integrations/file-storage/files/{id}` (visibility)+//! - `DELETE /agent-integrations/file-storage/files/{id}`+//!+//! Billing: uploads are charged upfront for the whole TTL at S3 rates plus a+//! margin; downloads and link generation are charged as egress. Quota is+//! 1 GiB per user; TTL is 7 days on the free plan / up to 1 year on paid+//! plans. Public files get a stable public URL.++#[cfg(test)]+#[path = "../tools_tests.rs"]+mod tools_tests;++mod delete;+mod download;+mod helpers;+mod link;+mod list;+mod registry;+mod upload;+mod visibility;++pub use delete::StorageDeleteFileTool;+pub use download::StorageDownloadFileTool;+pub use link::StorageGetLinkTool;+pub use list::StorageListFilesTool;+pub use registry::build_file_storage_tools;+pub use upload::StorageUploadFileTool;+pub use visibility::StorageSetVisibilityTool;++// Test-only bridges: `tools_tests.rs` (kept as-is; not part of the unsplit+// batch) reaches these through `use super::{...}`, mirroring the flat scope+// it had when `include!` spliced everything into one file.+#[cfg(test)]+use helpers::{resolve_upload_path, sanitize_filename};diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/registry.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/registry.rsnew file mode 100644index 0000000000..8dce9c3eb2--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/registry.rs@@ -0,0 +1,62 @@+//! Builds the full file-storage tool surface for a running config.++use std::path::Path;+use std::sync::Arc;++use crate::config::Config;+use crate::security::SecurityPolicy;+use tinytools::Tool;++use super::delete::StorageDeleteFileTool;+use super::download::StorageDownloadFileTool;+use super::link::StorageGetLinkTool;+use super::list::StorageListFilesTool;+use super::upload::StorageUploadFileTool;+use super::visibility::StorageSetVisibilityTool;++/// Build the file-storage tool surface. Returns empty when no integration+/// client is configured (no backend URL / not signed in), mirroring+/// `build_media_tools`.+pub fn build_file_storage_tools(root_config: &Config, action_dir: &Path) -> Vec<Box<dyn Tool>> {+ let Some(client) = crate::integrations::build_client(root_config) else {+ tracing::debug!("[file_storage] no integration client — file-storage tools skipped");+ return Vec::new();+ };++ let action_dir = action_dir.to_path_buf();+ let security = Arc::new(SecurityPolicy::from_config(+ &root_config.autonomy,+ &root_config.workspace_dir,+ &root_config.action_dir,+ ));+ let tools: Vec<Box<dyn Tool>> = vec![+ Box::new(StorageUploadFileTool::new_with_security(+ Arc::clone(&client),+ action_dir.clone(),+ Arc::clone(&security),+ )),+ Box::new(StorageDownloadFileTool::new_with_security(+ Arc::clone(&client),+ action_dir,+ Arc::clone(&security),+ )),+ Box::new(StorageListFilesTool::new(Arc::clone(&client))),+ Box::new(StorageGetLinkTool::new_with_security(+ Arc::clone(&client),+ Arc::clone(&security),+ )),+ Box::new(StorageSetVisibilityTool::new_with_security(+ Arc::clone(&client),+ Arc::clone(&security),+ )),+ Box::new(StorageDeleteFileTool::new_with_security(+ Arc::clone(&client),+ Arc::clone(&security),+ )),+ ];+ tracing::debug!(+ "[file_storage] registered {} file-storage tools",+ tools.len()+ );+ tools+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/upload.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/upload.rsnew file mode 100644index 0000000000..d7eeb0e9dd--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/upload.rs@@ -0,0 +1,202 @@+//! `storage_upload_file` — upload a workspace file to managed cloud storage.++use std::path::{Path, PathBuf};+use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::{mime_for_path, readonly_autonomy_block, resolve_upload_path};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;+use tinytools::ToolRunContext;+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolResult};++use super::helpers::{action_dir_for_context, FILES_PATH};+use crate::integrations::file_storage::types::UploadResponse;++pub struct StorageUploadFileTool {+ client: Arc<IntegrationClient>,+ action_dir: PathBuf,+ security: Arc<SecurityPolicy>,+}++impl StorageUploadFileTool {+ pub fn new(client: Arc<IntegrationClient>, action_dir: PathBuf) -> Self {+ Self::new_with_security(client, action_dir, Arc::new(SecurityPolicy::default()))+ }++ pub fn new_with_security(+ client: Arc<IntegrationClient>,+ action_dir: PathBuf,+ security: Arc<SecurityPolicy>,+ ) -> Self {+ Self {+ client,+ action_dir,+ security,+ }+ }++ async fn run(+ &self,+ args: Value,+ action_dir: &Path,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ if let Some(blocked) = readonly_autonomy_block(&self.security) {+ return Ok(blocked);+ }++ let raw_path = match args.get("path").and_then(|v| v.as_str()) {+ Some(p) if !p.trim().is_empty() => p.trim(),+ _ => return Ok(ToolResult::error("path is required")),+ };+ let resolved = match resolve_upload_path(action_dir, raw_path) {+ Ok(p) => p,+ Err(e) => return Ok(ToolResult::error(e)),+ };++ let visibility = match args.get("visibility").and_then(|v| v.as_str()) {+ Some(v) => match super::helpers::validate_visibility(v) {+ Ok(v) => Some(v),+ Err(e) => return Ok(ToolResult::error(e)),+ },+ None => None,+ };+ let ttl_days = match args.get("ttl_days") {+ Some(v) => match v.as_u64() {+ Some(d) if d >= 1 => Some(d),+ _ => return Ok(ToolResult::error("ttl_days must be a positive integer")),+ },+ None => None,+ };++ let bytes = match tokio::fs::read(&resolved).await {+ Ok(b) => b,+ Err(e) => {+ return Ok(ToolResult::error(format!(+ "failed to read {}: {e}",+ resolved.display()+ )))+ }+ };+ let filename = resolved+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("file")+ .to_string();+ let mime = mime_for_path(&resolved);++ tracing::debug!(+ "[file_storage] uploading {} ({} bytes, mime={}, visibility={:?}, ttl_days={:?})",+ resolved.display(),+ bytes.len(),+ mime,+ visibility,+ ttl_days+ );++ let part = match reqwest::multipart::Part::bytes(bytes)+ .file_name(filename.clone())+ .mime_str(mime)+ {+ Ok(p) => p,+ Err(e) => return Ok(ToolResult::error(format!("invalid mime '{mime}': {e}"))),+ };+ let mut form = reqwest::multipart::Form::new().part("file", part);+ if let Some(v) = &visibility {+ form = form.text("visibility", v.clone());+ }+ if let Some(d) = ttl_days {+ form = form.text("ttlDays", d.to_string());+ }++ match self+ .client+ .upload_multipart::<UploadResponse>(approval, FILES_PATH, form)+ .await+ {+ Ok(resp) => {+ let mut lines = vec![format!(+ "Uploaded {} ({} bytes) as file_id {} — visibility {}, expires {}.",+ resp.filename,+ resp.size,+ resp.file_id,+ resp.visibility,+ resp.expires_at.as_deref().unwrap_or("unknown"),+ )];+ if let Some(url) = &resp.public_url {+ lines.push(format!("Public URL: {url}"));+ }+ lines.push(format!("Cost: ${:.4}", resp.cost_usd));+ let payload = json!({+ "file_id": resp.file_id,+ "filename": resp.filename,+ "size": resp.size,+ "content_type": resp.content_type,+ "visibility": resp.visibility,+ "expires_at": resp.expires_at,+ "public_url": resp.public_url,+ "cost_usd": resp.cost_usd,+ });+ Ok(ToolResult::success_with_markdown(payload, lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!("File upload failed: {e}"))),+ }+ }+}++#[async_trait]+impl Tool for StorageUploadFileTool {+ fn name(&self) -> &str {+ "storage_upload_file"+ }++ fn description(&self) -> &str {+ "Upload a file from the agent workspace to managed cloud file storage and get a \+ file_id (and, for public files, a stable public URL). The path must be inside the \+ agent workspace. Files are billed at S3 rates plus margin (storage for the whole \+ TTL charged upfront on upload). Quota: 1 GiB per user. TTL: 7 days free / up to \+ 1 year on paid plans."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "File to upload — absolute or relative to the agent workspace; must resolve inside the workspace" },+ "visibility": { "type": "string", "enum": ["public", "private"], "description": "Default private. Public files get a stable public URL anyone can fetch (egress billed to you)." },+ "ttl_days": { "type": "integer", "minimum": 1, "description": "File lifetime in days (clamped to plan max: 7 free / 365 paid). Default: plan max." }+ },+ "required": ["path"]+ })+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Execute+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn external_effect(&self) -> bool {+ true+ }++ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ self.run(args, &self.action_dir, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: Value,+ _options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let action_dir = action_dir_for_context(&self.action_dir, context, self.name());+ let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);+ self.run(args, &action_dir, &approval).await+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/visibility.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/visibility.rsnew file mode 100644index 0000000000..8e83b47b19--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools/visibility.rs@@ -0,0 +1,127 @@+//! `storage_set_visibility` — flip a stored file between public and private.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use super::helpers::{file_path, readonly_autonomy_block, validate_file_id, validate_visibility};+use crate::integrations::IntegrationClient;+use crate::security::SecurityPolicy;+use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};++use crate::integrations::file_storage::types::FileMeta;++pub struct StorageSetVisibilityTool {+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+}++impl StorageSetVisibilityTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self::new_with_security(client, Arc::new(SecurityPolicy::default()))+ }++ pub fn new_with_security(+ client: Arc<IntegrationClient>,+ security: Arc<SecurityPolicy>,+ ) -> Self {+ Self { client, security }+ }+}++#[async_trait]+impl Tool for StorageSetVisibilityTool {+ fn name(&self) -> &str {+ "storage_set_visibility"+ }++ fn description(&self) -> &str {+ "Change a stored file's visibility. Public files get a stable public URL anyone \+ can fetch (egress billed to you); private files are only reachable via \+ authenticated download or presigned links. Visibility changes are free."+ }++ fn parameters_schema(&self) -> Value {+ json!({+ "type": "object",+ "properties": {+ "file_id": { "type": "string", "description": "The stored file's id" },+ "visibility": { "type": "string", "enum": ["public", "private"], "description": "New visibility" }+ },+ "required": ["file_id", "visibility"]+ })+ }++ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::Write+ }++ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }++ fn external_effect(&self) -> bool {+ true+ }++ 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 StorageSetVisibilityTool {+ /// 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> {+ if let Some(blocked) = readonly_autonomy_block(&self.security) {+ return Ok(blocked);+ }++ let file_id = match validate_file_id(&args) {+ Ok(id) => id,+ Err(e) => return Ok(ToolResult::error(e)),+ };+ let visibility = match args.get("visibility").and_then(|v| v.as_str()) {+ Some(v) => match validate_visibility(v) {+ Ok(v) => v,+ Err(e) => return Ok(ToolResult::error(e)),+ },+ None => return Ok(ToolResult::error("visibility is required")),+ };+ tracing::debug!("[file_storage] setting visibility={visibility} for file_id={file_id}");+ match self+ .client+ .patch::<FileMeta>(+ approval,+ &file_path(&file_id, ""),+ &json!({ "visibility": visibility }),+ )+ .await+ {+ Ok(meta) => {+ let mut md = format!("File {} is now {}.", meta.file_id, meta.visibility);+ if let Some(url) = &meta.public_url {+ md.push_str(&format!("\nPublic URL: {url}"));+ }+ Ok(ToolResult::success_with_markdown(meta.to_json(), md))+ }+ Err(e) => Ok(ToolResult::error(format!(+ "Failed to change file visibility: {e}"+ ))),+ }+ }+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rsnew file mode 100644index 0000000000..bd8202cdec--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/tools_tests.rs@@ -0,0 +1,555 @@+use std::path::PathBuf;+use std::sync::Arc;++use serde_json::json;++use super::{+ resolve_upload_path, sanitize_filename, StorageDeleteFileTool, StorageDownloadFileTool,+ StorageGetLinkTool, StorageListFilesTool, StorageSetVisibilityTool, StorageUploadFileTool,+};+use crate::integrations::IntegrationClient;+use crate::security::{AutonomyLevel, SecurityPolicy};+use tinytools::{PermissionLevel, Tool, ToolCategory};++fn dummy_client() -> Arc<IntegrationClient> {+ // No requests are made in these tests; the URL/token are placeholders.+ Arc::new(IntegrationClient::new(+ "http://127.0.0.1:0".to_string(),+ "test-token".to_string(),+ ))+}++// ── Metadata / schema ───────────────────────────────────────────────++#[test]+fn upload_tool_schema_and_metadata() {+ let tool = StorageUploadFileTool::new(dummy_client(), PathBuf::from("/tmp"));+ assert_eq!(tool.name(), "storage_upload_file");+ assert_eq!(tool.permission_level(), PermissionLevel::Execute);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(tool.external_effect());++ let schema = tool.parameters_schema();+ assert_eq!(schema["required"], json!(["path"]));+ let props = schema["properties"].as_object().unwrap();+ for key in ["path", "visibility", "ttl_days"] {+ assert!(props.contains_key(key), "missing upload property {key}");+ }+}++#[test]+fn download_tool_schema_and_metadata() {+ let tool = StorageDownloadFileTool::new(dummy_client(), PathBuf::from("/tmp"));+ assert_eq!(tool.name(), "storage_download_file");+ assert_eq!(tool.permission_level(), PermissionLevel::Write);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(tool.external_effect());++ let schema = tool.parameters_schema();+ assert_eq!(schema["required"], json!(["file_id"]));+ let props = schema["properties"].as_object().unwrap();+ for key in ["file_id", "filename"] {+ assert!(props.contains_key(key), "missing download property {key}");+ }+}++#[test]+fn list_tool_metadata() {+ let tool = StorageListFilesTool::new(dummy_client());+ assert_eq!(tool.name(), "storage_list_files");+ assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(!tool.external_effect());+}++#[test]+fn get_link_tool_schema_and_metadata() {+ let tool = StorageGetLinkTool::new(dummy_client());+ assert_eq!(tool.name(), "storage_get_link");+ assert_eq!(tool.permission_level(), PermissionLevel::Write);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(tool.external_effect());++ let schema = tool.parameters_schema();+ assert_eq!(schema["required"], json!(["file_id"]));+ let props = schema["properties"].as_object().unwrap();+ for key in ["file_id", "expires_in_seconds"] {+ assert!(props.contains_key(key), "missing link property {key}");+ }+}++#[test]+fn set_visibility_tool_schema_and_metadata() {+ let tool = StorageSetVisibilityTool::new(dummy_client());+ assert_eq!(tool.name(), "storage_set_visibility");+ assert_eq!(tool.permission_level(), PermissionLevel::Write);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(tool.external_effect());++ let schema = tool.parameters_schema();+ assert_eq!(schema["required"], json!(["file_id", "visibility"]));+}++#[test]+fn delete_tool_schema_and_metadata() {+ let tool = StorageDeleteFileTool::new(dummy_client());+ assert_eq!(tool.name(), "storage_delete_file");+ assert_eq!(tool.permission_level(), PermissionLevel::Write);+ assert_eq!(tool.category(), ToolCategory::Workflow);+ assert!(tool.external_effect());+ assert_eq!(tool.parameters_schema()["required"], json!(["file_id"]));+}++// ── Arg validation (no network) ─────────────────────────────────────++#[tokio::test]+async fn upload_rejects_missing_path_without_network() {+ let tool = StorageUploadFileTool::new(dummy_client(), PathBuf::from("/tmp"));+ let res = tool.execute(json!({})).await.unwrap();+ assert!(res.is_error);+ assert!(res.output().contains("path is required"));+}++#[tokio::test]+async fn upload_rejects_path_escaping_workspace() {+ let tmp = tempfile::tempdir().unwrap();+ // A real file OUTSIDE the workspace root.+ let outside = tempfile::tempdir().unwrap();+ let secret = outside.path().join("secret.txt");+ std::fs::write(&secret, b"nope").unwrap();++ let tool = StorageUploadFileTool::new(dummy_client(), tmp.path().to_path_buf());++ // Absolute path outside the workspace.+ let res = tool+ .execute(json!({ "path": secret.display().to_string() }))+ .await+ .unwrap();+ assert!(res.is_error, "absolute escape must be rejected: {res:?}");+ assert!(res.output().contains("escapes"), "got: {}", res.output());++ // Relative traversal out of the workspace.+ let rel = format!(+ "../{}/secret.txt",+ outside.path().file_name().unwrap().to_str().unwrap()+ );+ let res = tool.execute(json!({ "path": rel })).await.unwrap();+ assert!(res.is_error, "relative escape must be rejected: {res:?}");+}++#[tokio::test]+async fn upload_rejects_nonexistent_file() {+ let tmp = tempfile::tempdir().unwrap();+ let tool = StorageUploadFileTool::new(dummy_client(), tmp.path().to_path_buf());+ let res = tool+ .execute(json!({ "path": "missing.txt" }))+ .await+ .unwrap();+ assert!(res.is_error);+}++#[tokio::test]+async fn upload_rejects_bad_visibility_and_ttl() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(tmp.path().join("a.txt"), b"hi").unwrap();+ let tool = StorageUploadFileTool::new(dummy_client(), tmp.path().to_path_buf());++ let res = tool+ .execute(json!({ "path": "a.txt", "visibility": "everyone" }))+ .await+ .unwrap();+ assert!(res.is_error);+ assert!(res.output().contains("visibility"));++ let res = tool+ .execute(json!({ "path": "a.txt", "ttl_days": 0 }))+ .await+ .unwrap();+ assert!(res.is_error);+ assert!(res.output().contains("ttl_days"));+}++#[tokio::test]+async fn download_rejects_missing_or_invalid_file_id() {+ let tool = StorageDownloadFileTool::new(dummy_client(), PathBuf::from("/tmp"));+ let res = tool.execute(json!({})).await.unwrap();+ assert!(res.is_error);+ let res = tool.execute(json!({ "file_id": "../etc" })).await.unwrap();+ assert!(res.is_error);+}++#[tokio::test]+async fn get_link_rejects_missing_file_id() {+ let tool = StorageGetLinkTool::new(dummy_client());+ let res = tool.execute(json!({})).await.unwrap();+ assert!(res.is_error);+}++#[tokio::test]+async fn set_visibility_rejects_missing_or_invalid_args() {+ let tool = StorageSetVisibilityTool::new(dummy_client());+ let res = tool.execute(json!({ "file_id": "f1" })).await.unwrap();+ assert!(res.is_error);+ let res = tool+ .execute(json!({ "file_id": "f1", "visibility": "hidden" }))+ .await+ .unwrap();+ assert!(res.is_error);+}++#[tokio::test]+async fn delete_rejects_missing_file_id() {+ let tool = StorageDeleteFileTool::new(dummy_client());+ let res = tool.execute(json!({})).await.unwrap();+ assert!(res.is_error);+}++// ── Path / filename helpers ─────────────────────────────────────────++#[test]+fn resolve_upload_path_accepts_inside_and_rejects_outside() {+ let tmp = tempfile::tempdir().unwrap();+ let inner = tmp.path().join("sub");+ std::fs::create_dir_all(&inner).unwrap();+ let file = inner.join("data.bin");+ std::fs::write(&file, b"x").unwrap();++ // Relative path inside the root resolves.+ let ok = resolve_upload_path(tmp.path(), "sub/data.bin").unwrap();+ assert!(ok.ends_with("data.bin"));++ // Traversal escaping the root is rejected.+ let err = resolve_upload_path(&inner, "../../etc/hosts").unwrap_err();+ assert!(+ err.contains("escapes") || err.contains("not exist"),+ "got: {err}"+ );++ // A directory is not uploadable.+ let err = resolve_upload_path(tmp.path(), "sub").unwrap_err();+ assert!(err.contains("not a regular file"), "got: {err}");+}++#[test]+fn sanitize_filename_strips_separators_and_traversal() {+ assert_eq!(+ sanitize_filename("report.pdf").as_deref(),+ Some("report.pdf")+ );+ assert_eq!(+ sanitize_filename("../../evil.sh").as_deref(),+ Some("evil.sh")+ );+ assert_eq!(sanitize_filename("a/b\\c.txt").as_deref(), Some("c.txt"));+ assert!(sanitize_filename("..").is_none());+ assert!(sanitize_filename(" ").is_none());+}++// ── End-to-end flows against a mock backend (wiremock) ──────────────++use wiremock::matchers::{body_string_contains, header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++fn client_for(server: &MockServer) -> Arc<IntegrationClient> {+ Arc::new(IntegrationClient::new(server.uri(), "tok".to_string()))+}++fn readonly_security() -> Arc<SecurityPolicy> {+ Arc::new(SecurityPolicy {+ autonomy: AutonomyLevel::ReadOnly,+ ..SecurityPolicy::default()+ })+}++#[tokio::test]+async fn storage_transfer_tools_block_readonly_autonomy_before_network() {+ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(tmp.path().join("a.txt"), b"hi").unwrap();++ let upload = StorageUploadFileTool::new_with_security(+ dummy_client(),+ tmp.path().to_path_buf(),+ readonly_security(),+ );+ let upload_res = upload.execute(json!({ "path": "a.txt" })).await.unwrap();+ assert!(upload_res.is_error);+ assert!(upload_res.output().contains("[policy-blocked]"));++ let download = StorageDownloadFileTool::new_with_security(+ dummy_client(),+ tmp.path().to_path_buf(),+ readonly_security(),+ );+ let download_res = download+ .execute(json!({ "file_id": "file_123" }))+ .await+ .unwrap();+ assert!(download_res.is_error);+ assert!(download_res.output().contains("[policy-blocked]"));++ let get_link = StorageGetLinkTool::new_with_security(dummy_client(), readonly_security());+ let link_res = get_link+ .execute(json!({ "file_id": "file_123" }))+ .await+ .unwrap();+ assert!(link_res.is_error);+ assert!(link_res.output().contains("[policy-blocked]"));++ let set_visibility =+ StorageSetVisibilityTool::new_with_security(dummy_client(), readonly_security());+ let visibility_res = set_visibility+ .execute(json!({ "file_id": "file_123", "visibility": "public" }))+ .await+ .unwrap();+ assert!(visibility_res.is_error);+ assert!(visibility_res.output().contains("[policy-blocked]"));++ let delete = StorageDeleteFileTool::new_with_security(dummy_client(), readonly_security());+ let delete_res = delete+ .execute(json!({ "file_id": "file_123" }))+ .await+ .unwrap();+ assert!(delete_res.is_error);+ assert!(delete_res.output().contains("[policy-blocked]"));+}++#[tokio::test]+async fn upload_tool_posts_multipart_and_reports_file_id() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .and(header("authorization", "Bearer tok"))+ // Multipart body carries the file part + our extra form fields.+ .and(body_string_contains("name=\"file\""))+ .and(body_string_contains("HELLO-BYTES"))+ .and(body_string_contains("name=\"visibility\""))+ .and(body_string_contains("name=\"ttlDays\""))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "fileId": "file-1",+ "filename": "hello.txt",+ "size": 11,+ "contentType": "text/plain",+ "visibility": "public",+ "expiresAt": "2026-07-12T00:00:00.000Z",+ "publicUrl": "https://api.example/agent-integrations/file-storage/public/file-1",+ "costUsd": 0.0001+ }+ })))+ .expect(1)+ .mount(&server)+ .await;++ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(tmp.path().join("hello.txt"), b"HELLO-BYTES").unwrap();++ let tool = StorageUploadFileTool::new(client_for(&server), tmp.path().to_path_buf());+ let res = tool+ .execute(json!({ "path": "hello.txt", "visibility": "public", "ttl_days": 7 }))+ .await+ .unwrap();++ assert!(!res.is_error, "expected success, got {res:?}");+ let out = res.output();+ assert!(out.contains("file-1"), "output should carry file_id: {out}");+ assert!(+ out.contains("public"),+ "output should carry public url/visibility: {out}"+ );+}++#[tokio::test]+async fn download_tool_follows_redirect_and_persists_file() {+ let server = MockServer::start().await;+ // The backend 302s to a presigned URL; reqwest follows it (same host in+ // this test, but the redirect-following behavior is what's exercised).+ let presigned = format!("{}/s3/blob", server.uri());+ Mock::given(method("GET"))+ .and(path(+ "/agent-integrations/file-storage/files/file-2/download",+ ))+ .and(header("authorization", "Bearer tok"))+ .respond_with(ResponseTemplate::new(302).insert_header("Location", presigned.as_str()))+ .mount(&server)+ .await;+ Mock::given(method("GET"))+ .and(path("/s3/blob"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_raw(b"RAW-CONTENT".to_vec(), "text/plain")+ .insert_header("Content-Disposition", "attachment; filename=\"notes.txt\""),+ )+ .mount(&server)+ .await;++ let tmp = tempfile::tempdir().unwrap();+ let tool = StorageDownloadFileTool::new(client_for(&server), tmp.path().to_path_buf());+ let res = tool.execute(json!({ "file_id": "file-2" })).await.unwrap();++ assert!(!res.is_error, "expected success, got {res:?}");+ let saved = tmp.path().join("storage-downloads").join("notes.txt");+ assert_eq!(std::fs::read(&saved).unwrap(), b"RAW-CONTENT");+ assert!(res.output().contains("notes.txt"));+}++#[tokio::test]+async fn download_tool_honors_explicit_filename() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(+ "/agent-integrations/file-storage/files/file-3/download",+ ))+ .respond_with(ResponseTemplate::new(200).set_body_raw(b"BYTES".to_vec(), "application/pdf"))+ .mount(&server)+ .await;++ let tmp = tempfile::tempdir().unwrap();+ let tool = StorageDownloadFileTool::new(client_for(&server), tmp.path().to_path_buf());+ let res = tool+ .execute(json!({ "file_id": "file-3", "filename": "../sneaky/mine.pdf" }))+ .await+ .unwrap();++ assert!(!res.is_error, "expected success, got {res:?}");+ // Traversal in the requested name is stripped to the basename.+ let saved = tmp.path().join("storage-downloads").join("mine.pdf");+ assert_eq!(std::fs::read(&saved).unwrap(), b"BYTES");+}++#[tokio::test]+async fn list_tool_renders_files_and_usage() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "files": [+ {+ "fileId": "file-1",+ "filename": "hello.txt",+ "size": 11,+ "contentType": "text/plain",+ "visibility": "public",+ "expiresAt": "2026-07-12T00:00:00.000Z",+ "createdAt": "2026-07-05T00:00:00.000Z",+ "publicUrl": "https://api.example/agent-integrations/file-storage/public/file-1"+ }+ ],+ "usage": { "usedBytes": 11, "limitBytes": 1073741824 }+ }+ })))+ .mount(&server)+ .await;++ let tool = StorageListFilesTool::new(client_for(&server));+ let res = tool.execute(json!({})).await.unwrap();+ assert!(!res.is_error, "expected success, got {res:?}");+ let out = res.output();+ assert!(out.contains("file-1"));+ assert!(out.contains("hello.txt"));+}++#[tokio::test]+async fn get_link_tool_posts_expiry_and_returns_url() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files/file-1/link"))+ .and(body_string_contains("expiresInSeconds"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "url": "https://s3.example/presigned?sig=abc",+ "expiresAt": "2026-07-05T01:00:00.000Z",+ "costUsd": 0.0001+ }+ })))+ .mount(&server)+ .await;++ let tool = StorageGetLinkTool::new(client_for(&server));+ let res = tool+ .execute(json!({ "file_id": "file-1", "expires_in_seconds": 120 }))+ .await+ .unwrap();+ assert!(!res.is_error, "expected success, got {res:?}");+ assert!(res.output().contains("https://s3.example/presigned"));+}++#[tokio::test]+async fn set_visibility_tool_patches_and_reports_public_url() {+ let server = MockServer::start().await;+ Mock::given(method("PATCH"))+ .and(path("/agent-integrations/file-storage/files/file-1"))+ .and(body_string_contains("\"visibility\":\"public\""))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": {+ "fileId": "file-1",+ "filename": "hello.txt",+ "size": 11,+ "visibility": "public",+ "expiresAt": "2026-07-12T00:00:00.000Z",+ "publicUrl": "https://api.example/agent-integrations/file-storage/public/file-1"+ }+ })))+ .mount(&server)+ .await;++ let tool = StorageSetVisibilityTool::new(client_for(&server));+ let res = tool+ .execute(json!({ "file_id": "file-1", "visibility": "public" }))+ .await+ .unwrap();+ assert!(!res.is_error, "expected success, got {res:?}");+ assert!(res.output().contains("public"));+ assert!(res.output().contains("file-storage/public/file-1"));+}++#[tokio::test]+async fn delete_tool_deletes_and_confirms() {+ let server = MockServer::start().await;+ Mock::given(method("DELETE"))+ .and(path("/agent-integrations/file-storage/files/file-1"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": { "deleted": true }+ })))+ .mount(&server)+ .await;++ let tool = StorageDeleteFileTool::new(client_for(&server));+ let res = tool.execute(json!({ "file_id": "file-1" })).await.unwrap();+ assert!(!res.is_error, "expected success, got {res:?}");+ assert!(+ res.output().contains("\"deleted\": true"),+ "got: {}",+ res.output()+ );+ assert!(res.output_for_llm(true).contains("Deleted"));+}++#[tokio::test]+async fn tools_surface_backend_envelope_errors() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/agent-integrations/file-storage/files"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": false,+ "error": "Insufficient balance"+ })))+ .mount(&server)+ .await;++ let tmp = tempfile::tempdir().unwrap();+ std::fs::write(tmp.path().join("a.txt"), b"hi").unwrap();+ let tool = StorageUploadFileTool::new(client_for(&server), tmp.path().to_path_buf());+ let res = tool.execute(json!({ "path": "a.txt" })).await.unwrap();+ assert!(res.is_error);+ assert!(+ res.output().contains("Insufficient balance"),+ "got: {}",+ res.output()+ );+}diff --git a/crates/openhuman-tinyhumans/src/integrations/file_storage/types.rs b/crates/openhuman-tinyhumans/src/integrations/file_storage/types.rsnew file mode 100644index 0000000000..b9c8088f32--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/file_storage/types.rs@@ -0,0 +1,104 @@+//! Shared types for the `file_storage` agent tools.+//!+//! These mirror the backend's `file_storage` integration contract+//! (`/agent-integrations/file-storage/*`) — see the file-storage API contract.+//! Every response arrives inside the standard `{ success, data, error }`+//! envelope handled by `IntegrationClient`; these structs are the `data`+//! payloads.++use serde::Deserialize;+use serde_json::json;++/// Metadata for a stored file as returned by list / metadata / visibility+/// endpoints.+#[derive(Debug, Clone, Deserialize)]+pub struct FileMeta {+ #[serde(rename = "fileId")]+ pub file_id: String,+ pub filename: String,+ #[serde(default)]+ pub size: u64,+ #[serde(rename = "contentType", default)]+ pub content_type: Option<String>,+ #[serde(default)]+ pub visibility: String,+ #[serde(rename = "expiresAt", default)]+ pub expires_at: Option<String>,+ #[serde(rename = "createdAt", default)]+ pub created_at: Option<String>,+ /// Stable public URL — present only when `visibility == "public"`.+ #[serde(rename = "publicUrl", default)]+ pub public_url: Option<String>,+}++impl FileMeta {+ pub fn to_json(&self) -> serde_json::Value {+ json!({+ "file_id": self.file_id,+ "filename": self.filename,+ "size": self.size,+ "content_type": self.content_type,+ "visibility": self.visibility,+ "expires_at": self.expires_at,+ "created_at": self.created_at,+ "public_url": self.public_url,+ })+ }+}++/// `POST /files` (multipart upload) response.+#[derive(Debug, Clone, Deserialize)]+pub struct UploadResponse {+ #[serde(rename = "fileId")]+ pub file_id: String,+ pub filename: String,+ #[serde(default)]+ pub size: u64,+ #[serde(rename = "contentType", default)]+ pub content_type: Option<String>,+ #[serde(default)]+ pub visibility: String,+ #[serde(rename = "expiresAt", default)]+ pub expires_at: Option<String>,+ #[serde(rename = "publicUrl", default)]+ pub public_url: Option<String>,+ #[serde(rename = "costUsd", default)]+ pub cost_usd: f64,+}++/// Storage usage summary embedded in the list response.+#[derive(Debug, Clone, Deserialize, Default)]+pub struct StorageUsage {+ #[serde(rename = "usedBytes", default)]+ pub used_bytes: u64,+ #[serde(rename = "limitBytes", default)]+ pub limit_bytes: u64,+}++/// `GET /files` response.+#[derive(Debug, Clone, Deserialize)]+pub struct ListFilesResponse {+ #[serde(default)]+ pub files: Vec<FileMeta>,+ #[serde(rename = "nextCursor", default)]+ pub next_cursor: Option<String>,+ #[serde(default)]+ pub usage: StorageUsage,+}++/// `POST /files/:fileId/link` response — a short-lived presigned GET URL.+#[derive(Debug, Clone, Deserialize)]+pub struct LinkResponse {+ pub url: String,+ #[serde(rename = "expiresAt", default)]+ pub expires_at: Option<String>,+ #[serde(rename = "costUsd", default)]+ pub cost_usd: f64,+}++/// `DELETE /files/:fileId` response.+#[derive(Debug, Clone, Deserialize)]+pub struct DeleteResponse {+ #[serde(default)]+ pub deleted: bool,+}diff --git a/crates/openhuman-tinyhumans/src/integrations/media/provider.rs b/crates/openhuman-tinyhumans/src/integrations/media/provider.rsnew file mode 100644index 0000000000..719412a1a6--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/media/provider.rs@@ -0,0 +1,261 @@+//! Host adapter: OpenRouter media generators reached through the OpenHuman+//! backend's `/agent-integrations/openrouter` proxy.+//!+//! TinyInference owns the wire contract (`POST /images`, `POST /videos`,+//! `GET /videos/{id}`, `GET /videos/{id}/content`); this module supplies only+//! what the host owns:+//!+//! - **Endpoint and headers** — the backend transport's `raw_client()` (which+//! already carries `x-sdk-name` and the version headers) and the+//! `/agent-integrations/openrouter` base URL.+//! - **Credential** — a per-request resolver over+//! [`resolve_backend_credential`], so a desktop session JWT and a library+//! API key both work and a refreshed session is picked up.+//! - **Policy** — local-only enforcement and the egress disclosure before any+//! request leaves the device, and the managed-credit budget gate before a+//! billed submit. These are the same gates `IntegrationClient` applies to+//! every `/agent-integrations/*` call.++use std::sync::Arc;++use async_trait::async_trait;+use tinyagents_harness::tinyinference_image::{+ self as ti_image, BearerResolver, GeneratedMedia, ImageGenerator, ImageRequest, ImageResponse,+ MediaAuth, MediaModel, MediaTransport, OpenRouterImageGenerator,+};+use tinyagents_harness::tinyinference_video::{+ self as ti_video, OpenRouterVideoGenerator, VideoGenerator, VideoJob, VideoJobStatus,+ VideoRequest,+};++use crate::backend::BackendClient;+use crate::config::Config;+use crate::security::approval::ApprovalChatContext;+use crate::security::credentials::session_support::{+ resolve_backend_credential, BackendCredential,+};++/// 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,+>;++/// The image and video generators for this process.+pub struct MediaGenerators {+ /// Image generation.+ pub image: Arc<dyn ImageGenerator>,+ /// Video generation.+ pub video: Arc<dyn VideoGenerator>,+ /// Binds the generators to a turn's chat so their egress disclosures reach+ /// it. `None` for generators with no disclosures to route (mocks).+ router: Option<GeneratorRouter>,+}++impl MediaGenerators {+ /// Generators with no egress routing.+ pub fn new(image: Arc<dyn ImageGenerator>, video: Arc<dyn VideoGenerator>) -> Self {+ Self {+ image,+ video,+ router: None,+ }+ }++ /// The generators for one call of a turn whose chat routing is `chat`: the+ /// egress disclosures they raise are surfaced to that chat. An explicit+ /// value, so a call made off the chat task still discloses to its own chat.+ pub fn routed(&self, chat: Option<&ApprovalChatContext>) -> MediaGenerators {+ match &self.router {+ Some(router) => {+ let (image, video) = router(chat.cloned());+ MediaGenerators {+ image,+ video,+ router: self.router.clone(),+ }+ }+ None => MediaGenerators {+ image: Arc::clone(&self.image),+ video: Arc::clone(&self.video),+ router: None,+ },+ }+ }+}++/// Builds generators against the managed backend, or `None` when no backend+/// transport is installed (a core with no TinyHumans connection).+pub fn managed_generators(config: &Config) -> Option<MediaGenerators> {+ let client = match BackendClient::from_config(config) {+ Ok(client) => client,+ Err(error) => {+ tracing::debug!(%error, "[media_generation] no backend client; media tools skipped");+ return None;+ }+ };+ let http = match client.raw_client() {+ Ok(http) => http,+ Err(error) => {+ tracing::debug!(%error, "[media_generation] no backend transport; media tools skipped");+ return None;+ }+ };+ let base = match client.url_for(OPENROUTER_PROXY_PATH) {+ Ok(url) => url,+ Err(error) => {+ tracing::debug!(%error, "[media_generation] cannot build proxy URL; media tools skipped");+ return None;+ }+ };+ let config = Arc::new(config.clone());+ let transport = MediaTransport::new(MediaAuth::Bearer(bearer_resolver(Arc::clone(&config))))+ .with_client(http)+ .with_base_url(base.as_str());+ tracing::debug!(base = %base, "[media_generation] managed OpenRouter media generators ready");+ // The generators are built once per chat binding: `routed` rebuilds them+ // around a guard that discloses to that chat.+ let build = Arc::new(move |chat: Option<ApprovalChatContext>| {+ let image: Arc<dyn ImageGenerator> = Arc::new(GuardedImage {+ inner: OpenRouterImageGenerator::with_transport(transport.clone()),+ guard: Guard {+ config: Arc::clone(&config),+ chat: chat.clone(),+ },+ });+ let video: Arc<dyn VideoGenerator> = Arc::new(GuardedVideo {+ inner: OpenRouterVideoGenerator::with_transport(transport.clone()),+ guard: Guard {+ config: Arc::clone(&config),+ chat,+ },+ });+ (image, video)+ });+ let (image, video) = build(None);+ Some(MediaGenerators {+ image,+ video,+ router: Some(build),+ })+}++/// Resolves the backend credential on every request, so a session refreshed+/// mid-run is used and an API-key host needs no session at all.+pub(crate) fn bearer_resolver(config: Arc<Config>) -> BearerResolver {+ Arc::new(move || match resolve_backend_credential(&config) {+ Ok(BackendCredential::Session(token) | BackendCredential::ApiKey(token)) => Ok(token),+ Err(error) => Err(ti_image::Error::Auth(error)),+ })+}++/// Host policy applied before a request leaves the device.+struct Guard {+ config: Arc<Config>,+ /// The chat the call's disclosures are surfaced to; `None` outside a chat+ /// turn.+ chat: Option<ApprovalChatContext>,+}++impl Guard {+ /// Local-only enforcement, then the egress disclosure. A blocked call is+ /// neither disclosed nor sent.+ fn admit(&self, route: &str) -> ti_image::Result<()> {+ let descriptor = crate::security::egress::EgressDescriptor::integration(format!(+ "{OPENROUTER_PROXY_PATH}/{route}"+ ));+ crate::security::egress::enforce_egress(&descriptor).map_err(|error| {+ tracing::info!(route, %error, "[media_generation] blocked by privacy policy");+ ti_image::Error::Validation(format!("blocked by the privacy policy: {error}"))+ })?;+ crate::security::egress::emit_external_transfer(self.chat.as_ref(), descriptor);+ Ok(())+ }++ /// Refuses a billed submit when managed credits are exhausted.+ async fn budget(&self) -> ti_image::Result<()> {+ if crate::integrations::client::budget_gate::managed_tool_budget_exhausted(&self.config)+ .await+ {+ tracing::info!("[media_generation] managed credits exhausted; submit refused");+ return Err(ti_image::Error::Validation(+ "Managed cloud tools are disabled because your OpenHuman AI credits are exhausted. \+ Add credits or route the task to user-supplied providers."+ .into(),+ ));+ }+ Ok(())+ }+}++struct GuardedImage {+ inner: OpenRouterImageGenerator,+ guard: Guard,+}++#[async_trait]+impl ImageGenerator for GuardedImage {+ fn name(&self) -> &str {+ "openhuman-openrouter"+ }++ fn default_model(&self) -> &str {+ self.inner.default_model()+ }++ async fn generate(&self, request: ImageRequest) -> ti_image::Result<ImageResponse> {+ self.guard.admit("images")?;+ self.guard.budget().await?;+ self.inner.generate(request).await+ }++ async fn list_models(&self) -> ti_image::Result<Vec<MediaModel>> {+ self.guard.admit("images/models")?;+ self.inner.list_models().await+ }+}++struct GuardedVideo {+ inner: OpenRouterVideoGenerator,+ guard: Guard,+}++#[async_trait]+impl VideoGenerator for GuardedVideo {+ fn name(&self) -> &str {+ "openhuman-openrouter"+ }++ fn default_model(&self) -> &str {+ self.inner.default_model()+ }++ async fn submit(&self, request: VideoRequest) -> ti_video::Result<VideoJob> {+ self.guard.admit("videos")?;+ self.guard.budget().await?;+ self.inner.submit(request).await+ }++ async fn poll(&self, job_id: &str) -> ti_video::Result<VideoJobStatus> {+ self.guard.admit("videos/{jobId}")?;+ self.inner.poll(job_id).await+ }++ async fn content(&self, job_id: &str, index: usize) -> ti_video::Result<GeneratedMedia> {+ self.guard.admit("videos/{jobId}/content")?;+ self.inner.content(job_id, index).await+ }++ async fn list_models(&self) -> ti_video::Result<Vec<MediaModel>> {+ self.guard.admit("videos/models")?;+ self.inner.list_models().await+ }+}++#[cfg(test)]+#[path = "provider_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/media/provider_tests.rs b/crates/openhuman-tinyhumans/src/integrations/media/provider_tests.rsnew file mode 100644index 0000000000..60343427b4--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/media/provider_tests.rs@@ -0,0 +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 --git a/crates/openhuman-tinyhumans/src/integrations/tools.rs b/crates/openhuman-tinyhumans/src/integrations/tools.rsnew file mode 100644index 0000000000..4cb3d10d6a--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/tools.rs@@ -0,0 +1,10 @@+use super::IntegrationClient;++mod google_places;+mod stock_prices;++pub use google_places::{GooglePlacesDetailsTool, GooglePlacesSearchTool};+pub use stock_prices::{+ StockCommodityTool, StockCryptoSeriesTool, StockExchangeRateTool, StockOptionsTool,+ StockQuoteTool,+};diff --git a/crates/openhuman-tinyhumans/src/integrations/tools/google_places.rs b/crates/openhuman-tinyhumans/src/integrations/tools/google_places.rsnew file mode 100644index 0000000000..161d70c807--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/tools/google_places.rs@@ -0,0 +1,348 @@+//! Google Places integration tools — location search and place details.+//!+//! **Scope**: All (agent loop + CLI/RPC).+//!+//! **Endpoints**:+//! - `POST /agent-integrations/google-places/search`+//! - `POST /agent-integrations/google-places/details`+//!+//! **Pricing** (fetched from backend):+//! - Search: ~$0.01/request+//! - Details: ~$0.01/request+//!+//! The backend handles Google API keys, billing, and rate limiting.++use super::IntegrationClient;+use async_trait::async_trait;+use serde::Deserialize;+use serde_json::json;+use std::sync::Arc;+use tinytools::{Tool, ToolResult};++// ── Response types ──────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+struct SearchResponse {+ results: Vec<PlaceResult>,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct PlaceResult {+ #[serde(rename = "placeId", default)]+ place_id: String,+ #[serde(default)]+ name: String,+ #[serde(rename = "formattedAddress", default)]+ formatted_address: String,+ #[serde(default)]+ rating: Option<f64>,+ #[serde(rename = "userRatingCount", default)]+ user_rating_count: Option<u64>,+ #[serde(rename = "googleMapsUri", default)]+ google_maps_uri: Option<String>,+}++#[derive(Debug, Deserialize)]+struct DetailsResponse {+ place: PlaceDetails,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct PlaceDetails {+ #[serde(rename = "placeId", default)]+ place_id: String,+ #[serde(default)]+ name: String,+ #[serde(rename = "formattedAddress", default)]+ formatted_address: String,+ #[serde(default)]+ rating: Option<f64>,+ #[serde(rename = "userRatingCount", default)]+ user_rating_count: Option<u64>,+ #[serde(rename = "googleMapsUri", default)]+ google_maps_uri: Option<String>,+ #[serde(rename = "websiteUri", default)]+ website_uri: Option<String>,+ #[serde(rename = "nationalPhoneNumber", default)]+ national_phone_number: Option<String>,+ #[serde(rename = "businessStatus", default)]+ business_status: Option<String>,+ #[serde(rename = "regularOpeningHours", default)]+ regular_opening_hours: Option<OpeningHours>,+}++#[derive(Debug, Deserialize)]+struct OpeningHours {+ #[serde(rename = "openNow", default)]+ open_now: Option<bool>,+ #[serde(rename = "weekdayDescriptions", default)]+ weekday_descriptions: Vec<String>,+}++// ── GooglePlacesSearchTool ──────────────────────────────────────────++/// Search for places and businesses by text query.+pub struct GooglePlacesSearchTool {+ client: Arc<IntegrationClient>,+}++impl GooglePlacesSearchTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for GooglePlacesSearchTool {+ fn name(&self) -> &str {+ "google_places_search"+ }++ fn description(&self) -> &str {+ "Search for places, businesses, or points of interest using Google Places. \+ Returns names, addresses, ratings, and place IDs that can be used with \+ google_places_details for more information. Cost is per request, billed by the backend."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Search query (e.g. 'coffee shops near Times Square')"+ },+ "max_results": {+ "type": "integer",+ "description": "Maximum number of results (1-20, default 10)",+ "minimum": 1,+ "maximum": 20,+ "default": 10+ }+ },+ "required": ["query"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 GooglePlacesSearchTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let query = args+ .get("query")+ .and_then(|v| v.as_str())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;++ if query.trim().is_empty() {+ return Ok(ToolResult::error("Search query cannot be empty"));+ }++ let max_results = args+ .get("max_results")+ .and_then(|v| v.as_u64())+ .unwrap_or(10)+ .clamp(1, 20);++ let body = json!({+ "query": query,+ "maxResults": max_results+ });++ tracing::debug!("[google_places_search] query={:?}", query);++ match self+ .client+ .post::<SearchResponse>(approval, "/agent-integrations/google-places/search", &body)+ .await+ {+ Ok(resp) => {+ if resp.results.is_empty() {+ return Ok(ToolResult::success(format!(+ "No places found for: {}",+ query+ )));+ }++ let mut lines = vec![format!(+ "Found {} place(s) for: {}",+ resp.results.len(),+ query+ )];++ for (i, place) in resp.results.iter().enumerate() {+ lines.push(format!("\n{}. {}", i + 1, place.name));+ lines.push(format!(" Address: {}", place.formatted_address));+ if let Some(rating) = place.rating {+ let count = place.user_rating_count.unwrap_or(0);+ lines.push(format!(" Rating: {:.1}/5 ({} reviews)", rating, count));+ }+ lines.push(format!(" Place ID: {}", place.place_id));+ if let Some(ref uri) = place.google_maps_uri {+ lines.push(format!(" Maps: {}", uri));+ }+ }++ lines.push(format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!(+ "Google Places search failed: {e}"+ ))),+ }+ }+}++// ── GooglePlacesDetailsTool ─────────────────────────────────────────++/// Get detailed information about a specific place by place ID.+pub struct GooglePlacesDetailsTool {+ client: Arc<IntegrationClient>,+}++impl GooglePlacesDetailsTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for GooglePlacesDetailsTool {+ fn name(&self) -> &str {+ "google_places_details"+ }++ fn description(&self) -> &str {+ "Get detailed information about a specific place including hours, phone number, \+ website, rating, and business status. Requires a place ID from google_places_search. \+ Cost is per request, billed by the backend."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "place_id": {+ "type": "string",+ "description": "Google Places ID (from google_places_search results)"+ }+ },+ "required": ["place_id"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 GooglePlacesDetailsTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let place_id = args+ .get("place_id")+ .and_then(|v| v.as_str())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: place_id"))?;++ if place_id.trim().is_empty() {+ return Ok(ToolResult::error("place_id cannot be empty"));+ }++ let body = json!({ "placeId": place_id });++ tracing::debug!("[google_places_details] placeId={}", place_id);++ match self+ .client+ .post::<DetailsResponse>(approval, "/agent-integrations/google-places/details", &body)+ .await+ {+ Ok(resp) => {+ let p = &resp.place;+ let mut lines = vec![+ p.name.to_string(),+ format!("Address: {}", p.formatted_address),+ ];++ if let Some(rating) = p.rating {+ let count = p.user_rating_count.unwrap_or(0);+ lines.push(format!("Rating: {:.1}/5 ({} reviews)", rating, count));+ }++ if let Some(ref status) = p.business_status {+ lines.push(format!("Status: {}", status));+ }++ if let Some(ref phone) = p.national_phone_number {+ lines.push(format!("Phone: {}", phone));+ }++ if let Some(ref website) = p.website_uri {+ lines.push(format!("Website: {}", website));+ }++ if let Some(ref hours) = p.regular_opening_hours {+ if let Some(open_now) = hours.open_now {+ lines.push(format!("Open now: {}", if open_now { "Yes" } else { "No" }));+ }+ if !hours.weekday_descriptions.is_empty() {+ lines.push("Hours:".to_string());+ for desc in &hours.weekday_descriptions {+ lines.push(format!(" {}", desc));+ }+ }+ }++ if let Some(ref uri) = p.google_maps_uri {+ lines.push(format!("Maps: {}", uri));+ }++ lines.push(format!("Place ID: {}", p.place_id));+ lines.push(format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!(+ "Google Places details failed: {e}"+ ))),+ }+ }+}++#[cfg(test)]+#[path = "google_places_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/tools/google_places_tests.rs b/crates/openhuman-tinyhumans/src/integrations/tools/google_places_tests.rsnew file mode 100644index 0000000000..dd6a48ee56--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/tools/google_places_tests.rs@@ -0,0 +1,117 @@+use super::*;+use tinytools::ToolScope;++fn test_client() -> Arc<IntegrationClient> {+ Arc::new(IntegrationClient::new("http://test".into(), "tok".into()))+}++// ── GooglePlacesSearchTool ──────────────────────────────────────++#[test]+fn search_tool_metadata() {+ let tool = GooglePlacesSearchTool::new(test_client());+ assert_eq!(tool.name(), "google_places_search");+ assert_eq!(tool.scope(), ToolScope::All);+ assert!(tool.description().contains("Search for places"));+}++#[test]+fn search_schema_has_required_query() {+ let tool = GooglePlacesSearchTool::new(test_client());+ let schema = tool.parameters_schema();+ assert_eq!(schema["type"], "object");+ assert!(schema["properties"]["query"].is_object());+ let required = schema["required"].as_array().unwrap();+ assert!(required.iter().any(|v| v == "query"));+}++#[tokio::test]+async fn search_rejects_missing_query() {+ let tool = GooglePlacesSearchTool::new(test_client());+ assert!(tool.execute(json!({})).await.is_err());+}++#[tokio::test]+async fn search_rejects_empty_query() {+ let tool = GooglePlacesSearchTool::new(test_client());+ let result = tool.execute(json!({"query": ""})).await.unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("empty"));+}++#[test]+fn search_response_deserializes() {+ let json = r#"{+ "results": [+ {+ "placeId": "ChIJ123",+ "name": "Test Cafe",+ "formattedAddress": "123 Main St",+ "rating": 4.5,+ "userRatingCount": 100+ }+ ],+ "costUsd": 0.01+ }"#;+ let resp: SearchResponse = serde_json::from_str(json).unwrap();+ assert_eq!(resp.results.len(), 1);+ assert_eq!(resp.results[0].name, "Test Cafe");+ assert!((resp.cost_usd - 0.01).abs() < f64::EPSILON);+}++// ── GooglePlacesDetailsTool ─────────────────────────────────────++#[test]+fn details_tool_metadata() {+ let tool = GooglePlacesDetailsTool::new(test_client());+ assert_eq!(tool.name(), "google_places_details");+ assert_eq!(tool.scope(), ToolScope::All);+ assert!(tool.description().contains("detailed information"));+}++#[test]+fn details_schema_has_required_place_id() {+ let tool = GooglePlacesDetailsTool::new(test_client());+ let schema = tool.parameters_schema();+ let required = schema["required"].as_array().unwrap();+ assert!(required.iter().any(|v| v == "place_id"));+}++#[tokio::test]+async fn details_rejects_missing_place_id() {+ let tool = GooglePlacesDetailsTool::new(test_client());+ assert!(tool.execute(json!({})).await.is_err());+}++#[tokio::test]+async fn details_rejects_empty_place_id() {+ let tool = GooglePlacesDetailsTool::new(test_client());+ let result = tool.execute(json!({"place_id": ""})).await.unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("empty"));+}++#[test]+fn details_response_deserializes() {+ let json = r#"{+ "place": {+ "placeId": "ChIJ123",+ "name": "Test Cafe",+ "formattedAddress": "123 Main St",+ "rating": 4.5,+ "userRatingCount": 100,+ "websiteUri": "https://test.com",+ "nationalPhoneNumber": "+1 555-1234",+ "businessStatus": "OPERATIONAL",+ "regularOpeningHours": {+ "openNow": true,+ "weekdayDescriptions": ["Monday: 9 AM - 5 PM"]+ }+ },+ "costUsd": 0.01+ }"#;+ let resp: DetailsResponse = serde_json::from_str(json).unwrap();+ assert_eq!(resp.place.name, "Test Cafe");+ assert_eq!(resp.place.website_uri.as_deref(), Some("https://test.com"));+ assert!(resp.place.regular_opening_hours.unwrap().open_now.unwrap());+}diff --git a/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices.rs b/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices.rsnew file mode 100644index 0000000000..6aea5592e3--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices.rs@@ -0,0 +1,737 @@+//! Stock-price / market-data integration tools (backed by Alpha Vantage on the backend).+//!+//! **Scope**: All (agent loop + CLI/RPC).+//!+//! **Endpoints** (mounted under `/agent-integrations/financial-apis/*` on the backend,+//! which proxies Alpha Vantage):+//! - `POST /quote` — `GLOBAL_QUOTE` for stocks and indices+//! - `POST /options` — `REALTIME_OPTIONS` (optional greeks)+//! - `POST /exchange-rate` — `CURRENCY_EXCHANGE_RATE` (FX and crypto, e.g. BTC/USD)+//! - `POST /crypto-series` — `DIGITAL_CURRENCY_DAILY` OHLCV+//! - `POST /commodity` — futures: WTI / BRENT / NATURAL_GAS+//!+//! Pricing is metered by the backend; the response includes `costUsd` per call.++use super::IntegrationClient;+use async_trait::async_trait;+use serde::Deserialize;+use serde_json::json;+use std::sync::Arc;+use tinytools::{Tool, ToolExposure, ToolResult};++const PATH_QUOTE: &str = "/agent-integrations/financial-apis/quote";+const PATH_OPTIONS: &str = "/agent-integrations/financial-apis/options";+const PATH_EXCHANGE_RATE: &str = "/agent-integrations/financial-apis/exchange-rate";+const PATH_CRYPTO_SERIES: &str = "/agent-integrations/financial-apis/crypto-series";+const PATH_COMMODITY: &str = "/agent-integrations/financial-apis/commodity";++// ── Response types ──────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+struct QuoteResponse {+ quote: Quote,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct Quote {+ symbol: String,+ price: f64,+ open: f64,+ high: f64,+ low: f64,+ volume: f64,+ #[serde(rename = "previousClose")]+ previous_close: f64,+ change: f64,+ #[serde(rename = "changePercent", default)]+ change_percent: String,+ #[serde(rename = "latestTradingDay", default)]+ latest_trading_day: String,+}++#[derive(Debug, Deserialize)]+struct ExchangeRateResponse {+ rate: ExchangeRate,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct ExchangeRate {+ #[serde(rename = "fromCurrency")]+ from_currency: String,+ #[serde(rename = "toCurrency")]+ to_currency: String,+ rate: f64,+ #[serde(default)]+ bid: Option<f64>,+ #[serde(default)]+ ask: Option<f64>,+ #[serde(rename = "lastRefreshed", default)]+ last_refreshed: String,+ #[serde(rename = "timeZone", default)]+ time_zone: String,+}++#[derive(Debug, Deserialize)]+struct OptionsResponse {+ symbol: String,+ #[serde(default)]+ contracts: Vec<serde_json::Value>,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct CryptoSeriesResponse {+ series: CryptoSeries,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct CryptoSeries {+ symbol: String,+ market: String,+ series: Vec<CryptoSeriesPoint>,+}++#[derive(Debug, Deserialize)]+struct CryptoSeriesPoint {+ date: String,+ open: f64,+ high: f64,+ low: f64,+ close: f64,+ volume: f64,+}++#[derive(Debug, Deserialize)]+struct CommodityResponse {+ series: CommoditySeries,+ #[serde(rename = "costUsd", default)]+ cost_usd: f64,+}++#[derive(Debug, Deserialize)]+struct CommoditySeries {+ commodity: String,+ interval: String,+ #[serde(default)]+ unit: String,+ series: Vec<CommodityPoint>,+}++#[derive(Debug, Deserialize)]+struct CommodityPoint {+ date: String,+ #[serde(default)]+ value: Option<f64>,+}++// ── StockQuoteTool ──────────────────────────────────────────────────++/// Latest quote for a stock or index (e.g. `AAPL`, `SPY`).+pub struct StockQuoteTool {+ client: Arc<IntegrationClient>,+}++impl StockQuoteTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StockQuoteTool {+ /// Deferred: market data is a niche capability on a general assistant, and+ /// these five schemas cost ~720 tokens on every turn of every agent that+ /// carries them. The names are self-describing, so `tool_search("stock+ /// price")` finds them on the turns that need them.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn name(&self) -> &str {+ "stock_quote"+ }++ fn description(&self) -> &str {+ "Latest price for a stock or index ticker (e.g. AAPL, MSFT, SPY). \+ Returns price, open/high/low, volume, previous close, and percent change. \+ For crypto prices (e.g. BTC, ETH) or FX rates, use `stock_exchange_rate` instead."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "symbol": {+ "type": "string",+ "description": "Stock or index ticker, e.g. AAPL, MSFT, SPY"+ }+ },+ "required": ["symbol"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 StockQuoteTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let symbol = args+ .get("symbol")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: symbol"))?;++ tracing::info!("[stock_quote] symbol={}", symbol);++ let body = json!({ "symbol": symbol });+ match self+ .client+ .post::<QuoteResponse>(approval, PATH_QUOTE, &body)+ .await+ {+ Ok(resp) => {+ let q = &resp.quote;+ let mut out = format!(+ "{} — ${:.4}\n open ${:.4} high ${:.4} low ${:.4}\n prev close ${:.4} change {:+.4} ({})\n volume {}",+ q.symbol,+ q.price,+ q.open,+ q.high,+ q.low,+ q.previous_close,+ q.change,+ q.change_percent,+ q.volume,+ );+ if !q.latest_trading_day.is_empty() {+ out.push_str(&format!("\n latest trading day {}", q.latest_trading_day));+ }+ out.push_str(&format!("\n\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(out))+ }+ Err(e) => Ok(ToolResult::error(format!("Stock quote failed: {e}"))),+ }+ }+}++// ── StockExchangeRateTool ───────────────────────────────────────────++/// Realtime exchange rate for FX or crypto (e.g. BTC/USD, EUR/USD).+pub struct StockExchangeRateTool {+ client: Arc<IntegrationClient>,+}++impl StockExchangeRateTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StockExchangeRateTool {+ /// Deferred: market data is a niche capability on a general assistant, and+ /// these five schemas cost ~720 tokens on every turn of every agent that+ /// carries them. The names are self-describing, so `tool_search("stock+ /// price")` finds them on the turns that need them.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn name(&self) -> &str {+ "stock_exchange_rate"+ }++ fn description(&self) -> &str {+ "Realtime exchange rate between two currencies — works for both FX (USD, EUR, JPY, …) \+ and digital currencies (BTC, ETH, …). Use this for questions like \+ \"what is the price of BTC?\" (BTC → USD) or \"how much is 1 EUR in USD?\". \+ Returns rate plus bid/ask when available."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "from_currency": {+ "type": "string",+ "description": "Source currency (fiat or crypto), e.g. BTC, ETH, USD, EUR"+ },+ "to_currency": {+ "type": "string",+ "description": "Target currency, e.g. USD"+ }+ },+ "required": ["from_currency", "to_currency"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 StockExchangeRateTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let from = args+ .get("from_currency")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: from_currency"))?;+ let to = args+ .get("to_currency")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: to_currency"))?;++ tracing::info!("[stock_exchange_rate] {}->{}", from, to);++ let body = json!({ "fromCurrency": from, "toCurrency": to });+ match self+ .client+ .post::<ExchangeRateResponse>(approval, PATH_EXCHANGE_RATE, &body)+ .await+ {+ Ok(resp) => {+ let r = &resp.rate;+ let mut out = format!("{}/{} = {}\n", r.from_currency, r.to_currency, r.rate);+ if let Some(bid) = r.bid {+ out.push_str(&format!(" bid {}\n", bid));+ }+ if let Some(ask) = r.ask {+ out.push_str(&format!(" ask {}\n", ask));+ }+ if !r.last_refreshed.is_empty() {+ out.push_str(&format!(+ " last refreshed {} {}\n",+ r.last_refreshed, r.time_zone+ ));+ }+ out.push_str(&format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(out))+ }+ Err(e) => Ok(ToolResult::error(format!("Exchange rate failed: {e}"))),+ }+ }+}++// ── StockOptionsTool ────────────────────────────────────────────────++/// Realtime options chain for a symbol.+pub struct StockOptionsTool {+ client: Arc<IntegrationClient>,+}++impl StockOptionsTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StockOptionsTool {+ /// Deferred: market data is a niche capability on a general assistant, and+ /// these five schemas cost ~720 tokens on every turn of every agent that+ /// carries them. The names are self-describing, so `tool_search("stock+ /// price")` finds them on the turns that need them.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn name(&self) -> &str {+ "stock_options"+ }++ fn description(&self) -> &str {+ "Realtime options chain for a stock symbol. Returns active option contracts \+ (calls and puts) with strike, expiration, last/bid/ask, volume, and open interest. \+ Set `require_greeks = true` to also include delta, gamma, theta, vega, rho, and IV."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "symbol": { "type": "string", "description": "Stock ticker, e.g. AAPL" },+ "require_greeks": {+ "type": "boolean",+ "description": "Include greeks and implied volatility (default false)",+ "default": false+ }+ },+ "required": ["symbol"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 StockOptionsTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let symbol = args+ .get("symbol")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: symbol"))?;+ let require_greeks = args+ .get("require_greeks")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);++ tracing::info!(+ "[stock_options] symbol={} greeks={}",+ symbol,+ require_greeks+ );++ let body = json!({ "symbol": symbol, "requireGreeks": require_greeks });+ match self+ .client+ .post::<OptionsResponse>(approval, PATH_OPTIONS, &body)+ .await+ {+ Ok(resp) => {+ let total = resp.contracts.len();+ let mut lines = vec![format!(+ "{} options chain — {} active contracts",+ resp.symbol, total+ )];+ for c in resp.contracts.iter().take(20) {+ let typ = c.get("type").and_then(|v| v.as_str()).unwrap_or("?");+ let exp = c.get("expiration").and_then(|v| v.as_str()).unwrap_or("?");+ let strike = c.get("strike").and_then(|v| v.as_str()).unwrap_or("?");+ let last = c.get("last").and_then(|v| v.as_str()).unwrap_or("");+ let bid = c.get("bid").and_then(|v| v.as_str()).unwrap_or("");+ let ask = c.get("ask").and_then(|v| v.as_str()).unwrap_or("");+ lines.push(format!(+ " {} {} @ {} last {} bid {} ask {}",+ typ, exp, strike, last, bid, ask+ ));+ }+ if total > 20 {+ lines.push(format!(" …and {} more contracts", total - 20));+ }+ lines.push(format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!("Stock options failed: {e}"))),+ }+ }+}++// ── StockCryptoSeriesTool ───────────────────────────────────────────++/// Daily OHLCV series for a crypto pair (e.g. BTC/USD historical).+pub struct StockCryptoSeriesTool {+ client: Arc<IntegrationClient>,+}++impl StockCryptoSeriesTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StockCryptoSeriesTool {+ /// Deferred: market data is a niche capability on a general assistant, and+ /// these five schemas cost ~720 tokens on every turn of every agent that+ /// carries them. The names are self-describing, so `tool_search("stock+ /// price")` finds them on the turns that need them.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn name(&self) -> &str {+ "stock_crypto_series"+ }++ fn description(&self) -> &str {+ "Daily OHLCV series for a digital currency (e.g. BTC, ETH). \+ Returns the most recent N days of open / high / low / close / volume. \+ For a single spot price, prefer `stock_exchange_rate`."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "symbol": { "type": "string", "description": "Crypto symbol, e.g. BTC, ETH" },+ "market": {+ "type": "string",+ "description": "Quote market, default USD",+ "default": "USD"+ },+ "limit": {+ "type": "integer",+ "description": "Max points to return (most recent first), default 30",+ "minimum": 1,+ "maximum": 1000,+ "default": 30+ }+ },+ "required": ["symbol"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 StockCryptoSeriesTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let symbol = args+ .get("symbol")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: symbol"))?;++ let mut body = json!({ "symbol": symbol });+ if let Some(m) = args.get("market").and_then(|v| v.as_str()) {+ body["market"] = json!(m);+ }+ if let Some(l) = args.get("limit").and_then(|v| v.as_u64()) {+ body["limit"] = json!(l.clamp(1, 1000));+ }++ tracing::info!("[stock_crypto_series] symbol={}", symbol);++ match self+ .client+ .post::<CryptoSeriesResponse>(approval, PATH_CRYPTO_SERIES, &body)+ .await+ {+ Ok(resp) => {+ let s = &resp.series;+ let mut lines = vec![format!(+ "{}/{} — {} day(s)",+ s.symbol,+ s.market,+ s.series.len()+ )];+ for p in s.series.iter().take(30) {+ lines.push(format!(+ " {} o {:.2} h {:.2} l {:.2} c {:.2} v {:.2}",+ p.date, p.open, p.high, p.low, p.close, p.volume+ ));+ }+ if s.series.len() > 30 {+ lines.push(format!(" …and {} more rows", s.series.len() - 30));+ }+ lines.push(format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!("Crypto series failed: {e}"))),+ }+ }+}++// ── StockCommodityTool ──────────────────────────────────────────────++/// Commodity / futures price series — WTI, BRENT, NATURAL_GAS.+pub struct StockCommodityTool {+ client: Arc<IntegrationClient>,+}++impl StockCommodityTool {+ pub fn new(client: Arc<IntegrationClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl Tool for StockCommodityTool {+ /// Deferred: market data is a niche capability on a general assistant, and+ /// these five schemas cost ~720 tokens on every turn of every agent that+ /// carries them. The names are self-describing, so `tool_search("stock+ /// price")` finds them on the turns that need them.+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Deferred+ }++ fn name(&self) -> &str {+ "stock_commodity"+ }++ fn description(&self) -> &str {+ "Commodity / futures price series — WTI crude, Brent crude, or natural gas. \+ Returns dated value points at daily, weekly, or monthly granularity."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "commodity": {+ "type": "string",+ "enum": ["WTI", "BRENT", "NATURAL_GAS"],+ "description": "Commodity to fetch"+ },+ "interval": {+ "type": "string",+ "enum": ["daily", "weekly", "monthly"],+ "description": "Sampling interval (default daily)",+ "default": "daily"+ },+ "limit": {+ "type": "integer",+ "description": "Max points (default 30)",+ "minimum": 1,+ "maximum": 1000,+ "default": 30+ }+ },+ "required": ["commodity"]+ })+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.run(args, &Default::default()).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::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 StockCommodityTool {+ /// Runs the tool for a turn whose approval context is `approval`.+ pub(crate) async fn run(+ &self,+ args: serde_json::Value,+ approval: &crate::security::approval::ApprovalTurnContext,+ ) -> anyhow::Result<ToolResult> {+ let commodity = args+ .get("commodity")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow::anyhow!("Missing required parameter: commodity"))?;++ let mut body = json!({ "commodity": commodity });+ if let Some(i) = args.get("interval").and_then(|v| v.as_str()) {+ body["interval"] = json!(i);+ }+ if let Some(l) = args.get("limit").and_then(|v| v.as_u64()) {+ body["limit"] = json!(l.clamp(1, 1000));+ }++ tracing::info!("[stock_commodity] {}", commodity);++ match self+ .client+ .post::<CommodityResponse>(approval, PATH_COMMODITY, &body)+ .await+ {+ Ok(resp) => {+ let s = &resp.series;+ let mut lines = vec![format!(+ "{} ({}) — {} ({})",+ s.commodity,+ s.interval,+ if s.unit.is_empty() { "value" } else { &s.unit },+ s.series.len()+ )];+ for p in s.series.iter().take(30) {+ let v = p+ .value+ .map(|v| format!("{:.4}", v))+ .unwrap_or_else(|| "n/a".into());+ lines.push(format!(" {} {}", p.date, v));+ }+ if s.series.len() > 30 {+ lines.push(format!(" …and {} more rows", s.series.len() - 30));+ }+ lines.push(format!("\nCost: ${:.4}", resp.cost_usd));+ Ok(ToolResult::success(lines.join("\n")))+ }+ Err(e) => Ok(ToolResult::error(format!("Commodity series failed: {e}"))),+ }+ }+}++#[cfg(test)]+#[path = "stock_prices_tests.rs"]+mod tests;diff --git a/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices_tests.rs b/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices_tests.rsnew file mode 100644index 0000000000..f87e6a8c44--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/tools/stock_prices_tests.rs@@ -0,0 +1,95 @@+use super::*;+use tinytools::ToolScope;++fn test_client() -> Arc<IntegrationClient> {+ Arc::new(IntegrationClient::new("http://test".into(), "tok".into()))+}++#[test]+fn quote_tool_metadata() {+ let t = StockQuoteTool::new(test_client());+ assert_eq!(t.name(), "stock_quote");+ assert_eq!(t.scope(), ToolScope::All);+ assert!(t.description().to_lowercase().contains("stock"));+}++#[test]+fn exchange_rate_tool_metadata() {+ let t = StockExchangeRateTool::new(test_client());+ assert_eq!(t.name(), "stock_exchange_rate");+ let schema = t.parameters_schema();+ let req = schema["required"].as_array().unwrap();+ assert!(req.iter().any(|v| v == "from_currency"));+ assert!(req.iter().any(|v| v == "to_currency"));+}++#[test]+fn options_tool_metadata() {+ let t = StockOptionsTool::new(test_client());+ assert_eq!(t.name(), "stock_options");+}++#[test]+fn crypto_series_tool_metadata() {+ let t = StockCryptoSeriesTool::new(test_client());+ assert_eq!(t.name(), "stock_crypto_series");+}++#[test]+fn commodity_tool_metadata() {+ let t = StockCommodityTool::new(test_client());+ assert_eq!(t.name(), "stock_commodity");+}++#[tokio::test]+async fn quote_rejects_missing_symbol() {+ let t = StockQuoteTool::new(test_client());+ assert!(t.execute(json!({})).await.is_err());+}++#[tokio::test]+async fn exchange_rate_rejects_missing_currency() {+ let t = StockExchangeRateTool::new(test_client());+ assert!(t.execute(json!({"from_currency": "BTC"})).await.is_err());+}++#[test]+fn quote_response_deserializes() {+ let json = r#"{+ "quote": {+ "symbol": "AAPL",+ "price": 271.06,+ "open": 270.0,+ "high": 272.5,+ "low": 269.5,+ "volume": 1000000,+ "previousClose": 268.5,+ "change": 2.56,+ "changePercent": "0.95%",+ "latestTradingDay": "2026-04-23"+ },+ "costUsd": 0.001+ }"#;+ let resp: QuoteResponse = serde_json::from_str(json).unwrap();+ assert_eq!(resp.quote.symbol, "AAPL");+ assert!((resp.quote.price - 271.06).abs() < 1e-6);+}++#[test]+fn exchange_rate_response_deserializes() {+ let json = r#"{+ "rate": {+ "fromCurrency": "BTC",+ "toCurrency": "USD",+ "rate": 77421.13,+ "bid": 77418.0,+ "ask": 77424.26,+ "lastRefreshed": "2026-04-23 10:00:00",+ "timeZone": "UTC"+ },+ "costUsd": 0.001+ }"#;+ let resp: ExchangeRateResponse = serde_json::from_str(json).unwrap();+ assert_eq!(resp.rate.from_currency, "BTC");+ assert!((resp.rate.rate - 77421.13).abs() < 1e-6);+}diff --git a/crates/openhuman-tinyhumans/src/integrations/types.rs b/crates/openhuman-tinyhumans/src/integrations/types.rsnew file mode 100644index 0000000000..ff6e8b4957--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/types.rs@@ -0,0 +1,43 @@+//! Shared types for agent integration tools.++use serde::Deserialize;++// ── Pricing types (fetched from backend) ────────────────────────────++/// Per-integration pricing returned by `GET /agent-integrations/pricing`.+#[derive(Debug, Clone, Default, Deserialize)]+pub struct IntegrationPricing {+ #[serde(default)]+ pub integrations: PricingIntegrations,+}++#[derive(Debug, Clone, Default, Deserialize)]+pub struct PricingIntegrations {+ #[serde(default)]+ pub google_places: Option<IntegrationPricingEntry>,+ #[serde(default)]+ pub parallel: Option<IntegrationPricingEntry>,+ #[serde(default)]+ pub tinyfish: Option<IntegrationPricingEntry>,+}++#[derive(Debug, Clone, Deserialize)]+pub struct IntegrationPricingEntry {+ #[serde(default)]+ pub available: bool,+ #[serde(default)]+ pub pricing: serde_json::Value,+}++// ── Backend response envelope ───────────────────────────────────────++/// Standard `{ success, data, error }` envelope from the backend.+#[derive(Debug, Deserialize)]+pub struct BackendResponse<T> {+ #[allow(dead_code)]+ pub success: bool,+ pub data: Option<T>,+ #[serde(default)]+ #[allow(dead_code)]+ pub error: Option<String>,+}diff --git a/crates/openhuman-tinyhumans/src/integrations/web3/client.rs b/crates/openhuman-tinyhumans/src/integrations/web3/client.rsnew file mode 100644index 0000000000..4ce4fad77b--- /dev/null+++ b/crates/openhuman-tinyhumans/src/integrations/web3/client.rs@@ -0,0 +1,85 @@+//! Thin HTTP wrapper over the openhuman backend's `/agent-integrations/crypto/*`+//! routes (deBridge DLN — see backend PR #852). All calls go through the shared+//! [`IntegrationClient`] so they inherit Bearer JWT auth, timeout, the+//! `{success,data}` envelope parsing, and proxy behavior.+//!+//! Responses are returned as raw `serde_json::Value` (the unwrapped `data`+//! payload) — deBridge returns a large nested quote/tx object and we pass the+//! parts we don't explicitly consume through unchanged.++use std::sync::Arc;++use serde_json::Value;++use crate::config::Config;+use crate::integrations::IntegrationClient;++const LOG_PREFIX: &str = "[web3]";++/// High-level client for the backend-proxied deBridge crypto operations.+#[derive(Clone)]+pub struct CryptoClient {+ inner: Arc<IntegrationClient>,+}++impl CryptoClient {+ pub fn new(inner: Arc<IntegrationClient>) -> Self {+ Self { inner }+ }++ /// Build from config; errors when the user is not signed in (no session+ /// token) — the same gate the composio tools use.+ pub fn from_config(config: &Config) -> Result<Self, String> {+ let inner = crate::integrations::build_client(config).ok_or_else(|| {+ "web3 requires a signed-in session (no backend auth token available)".to_string()+ })?;+ Ok(Self::new(inner))+ }++ /// `GET /agent-integrations/crypto/routes` — chains deBridge can+ /// swap/bridge between.+ pub async fn routes(&self) -> Result<Value, String> {+ tracing::debug!("{LOG_PREFIX} routes");+ self.inner+ .get::<Value>(+ &crate::security::approval::ApprovalTurnContext::default(),+ "/agent-integrations/crypto/routes",+ )+ .await+ .map_err(|e| format!("web3 routes failed: {e}"))+ }++ /// `POST /agent-integrations/crypto/swap` — single-chain swap quote + tx.+ pub async fn swap_tx(&self, body: &Value) -> Result<Value, String> {+ // Log only non-sensitive correlation fields — the body embeds wallet+ // addresses (sender / recipient) which must not be emitted in full.+ tracing::debug!("{LOG_PREFIX} swap_tx chain_id={:?}", body.get("chainId"));+ self.inner+ .post::<Value>(+ &crate::security::approval::ApprovalTurnContext::default(),+ "/agent-integrations/crypto/swap",+ body,+ )+ .await+ .map_err(|e| format!("web3 swap quote failed: {e}"))+ }++ /// `POST /agent-integrations/crypto/bridge` — cross-chain bridge quote + tx.+ pub async fn bridge_tx(&self, body: &Value) -> Result<Value, String> {+ // Log only chain ids — the body embeds recipient / order-authority+ // wallet addresses which must not be emitted in full.+ tracing::debug!(+ "{LOG_PREFIX} bridge_tx src={:?} dst={:?}",+ body.get("srcChainId"),+ body.get("dstChainId")+ );+ self.inner+ .post::<Value>(+ &crate::security::approval::ApprovalTurnContext::default(),+ "/agent-integrations/crypto/bridge",+ body,+ )+ .await+ .map_err(|e| format!("web3 bridge quote failed: {e}"))+ }+}