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
fix(network): correct gate host resolution to use hostname instead of IP
Steven Enamakeld7d377fcbf53
diff --git a/crates/openhuman-core/src/tools/impl/network/gate.rs b/crates/openhuman-core/src/tools/impl/network/gate.rsnew file mode 100644index 0000000000..3ff0260a33--- /dev/null+++ b/crates/openhuman-core/src/tools/impl/network/gate.rs@@ -0,0 +1,85 @@+//! `SecurityPolicy` as the network tools' [`NetGate`].+//!+//! A mechanical mapping: every method is one call the tools used to make on+//! the policy, the privacy-mode egress gate or the runtime proxy config+//! directly, with the same argument and the same answer. No policy is decided+//! here; the adapter only names the questions.++use tinytools_std::network::NetGate;++use crate::security::egress::{+ emit_external_transfer, local_only_tool_block, DataKind, EgressDescriptor,+};+use crate::security::{CommandClass, GateDecision, SecurityPolicy};++/// Build the egress descriptor for an outbound HTTP request (privacy epic S2,+/// #4436). The host is the destination; a request body carries tool arguments+/// and any custom headers (e.g. an `Authorization` token) are metadata that+/// also leaves the device — so a header-only call is not under-reported as+/// URL-only (codex P2, PR #4812). Pure over its inputs so it is unit-testable+/// off the network path.+pub(super) fn network_egress_descriptor(+ host: &str,+ has_body: bool,+ has_headers: bool,+) -> EgressDescriptor {+ let mut desc = EgressDescriptor::network_fetch(host);+ if has_body {+ desc = desc.with_data_kind(DataKind::ToolArguments);+ }+ if has_headers {+ desc = desc.with_data_kind(DataKind::Metadata);+ }+ desc+}++impl NetGate for SecurityPolicy {+ fn can_act(&self) -> bool {+ SecurityPolicy::can_act(self)+ }++ fn is_rate_limited(&self) -> bool {+ SecurityPolicy::is_rate_limited(self)+ }++ fn record_action(&self) -> bool {+ SecurityPolicy::record_action(self)+ }++ fn network_needs_approval(&self) -> bool {+ self.gate_decision(CommandClass::Network) == GateDecision::Prompt+ }++ fn local_only_block(&self, host: &str) -> Option<String> {+ local_only_tool_block(&EgressDescriptor::network_fetch(host))+ }++ fn disclose(&self, host: &str, has_body: bool, has_headers: bool) {+ emit_external_transfer(network_egress_descriptor(host, has_body, has_headers));+ }++ fn prepare_client(+ &self,+ service: &str,+ builder: reqwest::ClientBuilder,+ ) -> reqwest::ClientBuilder {+ crate::config::apply_runtime_proxy_to_builder(builder, service)+ }++ fn timeout_client(+ &self,+ service: &str,+ timeout_secs: u64,+ connect_timeout_secs: u64,+ ) -> reqwest::Client {+ crate::config::build_runtime_proxy_client_with_timeouts(+ service,+ timeout_secs,+ connect_timeout_secs,+ )+ }+}++#[cfg(test)]+#[path = "gate_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/tools/impl/network/gate_tests.rs b/crates/openhuman-core/src/tools/impl/network/gate_tests.rsnew file mode 100644index 0000000000..a90f9377a6--- /dev/null+++ b/crates/openhuman-core/src/tools/impl/network/gate_tests.rs@@ -0,0 +1,219 @@+use super::*;+use crate::security::{AutonomyLevel, SecurityPolicy};+use serde_json::json;+use std::sync::Arc;+use tinytools::{PermissionLevel, Tool};+use tinytools_std::network::{CurlTool, HttpRequestTool, PushoverTool, WebFetchTool};++fn policy(autonomy: AutonomyLevel, max_actions_per_hour: u32) -> Arc<SecurityPolicy> {+ Arc::new(SecurityPolicy {+ autonomy,+ max_actions_per_hour,+ ..SecurityPolicy::default()+ })+}++fn http(security: Arc<SecurityPolicy>) -> HttpRequestTool {+ super::super::host::http_request_tool(security, vec!["example.com".into()], 1_000_000, 30)+}++// --- the gate answers with the policy's own decisions -----------------------++#[test]+fn read_only_autonomy_cannot_act() {+ let gate: &dyn NetGate = &SecurityPolicy {+ autonomy: AutonomyLevel::ReadOnly,+ ..SecurityPolicy::default()+ };+ assert!(!gate.can_act());+}++#[test]+fn the_action_budget_is_shared_with_the_policy() {+ let security = policy(AutonomyLevel::Supervised, 1);+ let gate: &dyn NetGate = security.as_ref();+ assert!(!gate.is_rate_limited());+ assert!(gate.record_action());+ assert!(gate.is_rate_limited());+ assert!(!gate.record_action());+}++#[test]+fn supervised_network_asks_for_approval_and_read_only_does_not() {+ let supervised = policy(AutonomyLevel::Supervised, 100);+ let read_only = policy(AutonomyLevel::ReadOnly, 100);+ assert_eq!(+ NetGate::network_needs_approval(supervised.as_ref()),+ supervised.gate_decision(CommandClass::Network) == GateDecision::Prompt+ );+ assert!(NetGate::network_needs_approval(supervised.as_ref()));+ assert!(!NetGate::network_needs_approval(read_only.as_ref()));+}++// --- privacy mode ------------------------------------------------------------++#[test]+fn local_only_privacy_mode_refuses_with_the_policy_blocked_marker() {+ let _mode = super::super::local_only_scope();+ let msg = NetGate::local_only_block(&SecurityPolicy::default(), "example.com")+ .expect("LocalOnly blocks a network fetch");+ assert!(msg.contains("[policy-blocked]"), "got: {msg}");+ assert!(msg.contains("Local-only"), "got: {msg}");+ assert!(msg.contains("example.com"), "names the host: {msg}");+}++#[test]+fn standard_privacy_mode_lets_the_request_through() {+ let _mode = crate::security::live_policy::test_privacy_scope(crate::config::PrivacyMode::Standard);+ assert!(NetGate::local_only_block(&SecurityPolicy::default(), "example.com").is_none());+}++// --- the tools, through the real policy ---------------------------------------++#[tokio::test]+async fn http_request_blocks_readonly_mode() {+ let tool = http(policy(AutonomyLevel::ReadOnly, 100));+ let result = tool+ .execute(json!({"url": "https://example.com"}))+ .await+ .unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("read-only"));+}++#[tokio::test]+async fn http_request_blocks_when_rate_limited() {+ let tool = http(policy(AutonomyLevel::Supervised, 0));+ let result = tool+ .execute(json!({"url": "https://example.com"}))+ .await+ .unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("rate limit"));+}++#[tokio::test]+async fn http_request_is_blocked_under_local_only_privacy_mode() {+ // Privacy epic S7 (#4441): under LocalOnly the request is refused with a+ // `[policy-blocked]` result before URL validation / network.+ let _mode = super::super::local_only_scope();+ let result = http(Arc::new(SecurityPolicy::default()))+ .execute(json!({"url": "https://example.com"}))+ .await+ .unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("[policy-blocked]"), "got: {}", result.output());+ assert!(result.output().contains("Local-only"), "got: {}", result.output());+}++#[tokio::test]+async fn web_fetch_and_curl_are_blocked_under_local_only_privacy_mode() {+ let _mode = super::super::local_only_scope();+ let security = Arc::new(SecurityPolicy::default());+ let fetch = super::super::host::web_fetch_tool(+ security.clone(),+ vec!["example.com".into()],+ None,+ None,+ );+ let curl = CurlTool::new(+ security,+ vec!["example.com".into()],+ std::env::temp_dir(),+ "downloads".into(),+ 1024,+ 30,+ );+ for result in [+ fetch+ .execute(json!({"url": "https://example.com/data"}))+ .await+ .unwrap(),+ curl.execute(json!({"url": "https://example.com/x"}))+ .await+ .unwrap(),+ ] {+ assert!(result.is_error);+ assert!(result.output().contains("[policy-blocked]"), "got: {}", result.output());+ assert!(result.output().contains("Local-only"), "got: {}", result.output());+ }+}++#[tokio::test]+async fn pushover_honours_read_only_and_the_rate_limit() {+ let read_only = PushoverTool::new(policy(AutonomyLevel::ReadOnly, 100), "/tmp".into());+ let result = read_only.execute(json!({"message": "hello"})).await.unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("read-only"));++ let limited = PushoverTool::new(policy(AutonomyLevel::Full, 0), "/tmp".into());+ let result = limited.execute(json!({"message": "hello"})).await.unwrap();+ assert!(result.is_error);+ assert!(result.output().contains("rate limit"));+}++#[test]+fn supervised_http_request_is_external_effect_for_approval_gate() {+ let tool = http(policy(AutonomyLevel::Supervised, 100));+ assert_eq!(tool.permission_level(), PermissionLevel::Write);+ assert!(tool.external_effect_with_args(&json!({+ "url": "https://example.com/api",+ "method": "POST",+ "headers": { "Authorization": "Bearer token" },+ "body": "{}"+ })));+}++#[test]+fn readonly_http_request_is_not_external_effect_because_execute_blocks() {+ let tool = http(policy(AutonomyLevel::ReadOnly, 100));+ assert!(!tool.external_effect_with_args(&json!({+ "url": "https://example.com/api",+ "method": "GET"+ })));+}++#[test]+fn web_fetch_is_read_only_and_never_prompts() {+ let tool: WebFetchTool = super::super::host::web_fetch_tool(+ policy(AutonomyLevel::Supervised, 100),+ vec![],+ None,+ None,+ );+ assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);+}++// --- egress descriptor -------------------------------------------------------++#[test]+fn egress_descriptor_reports_host_and_url_kind_when_bare() {+ // A bodyless, headerless GET discloses only the destination host + URL.+ let desc = network_egress_descriptor("api.example.com", false, false);+ assert_eq!(desc.provider_slug, "network");+ assert_eq!(desc.service, "api.example.com");+ assert!(desc.is_external);+ assert_eq!(desc.data_kinds, vec![DataKind::Url]);+}++#[test]+fn egress_descriptor_adds_tool_arguments_for_body() {+ let desc = network_egress_descriptor("api.example.com", true, false);+ assert!(desc.data_kinds.contains(&DataKind::ToolArguments));+ assert!(!desc.data_kinds.contains(&DataKind::Metadata));+}++#[test]+fn egress_descriptor_reports_headers_as_metadata_even_without_body() {+ // Regression for the under-reporting fix: a header-only call (e.g. an+ // Authorization token, no body) must still disclose the header metadata.+ let desc = network_egress_descriptor("api.example.com", false, true);+ assert!(desc.data_kinds.contains(&DataKind::Metadata));+}++#[test]+fn egress_descriptor_reports_both_body_and_headers() {+ let desc = network_egress_descriptor("api.example.com", true, true);+ assert!(desc.data_kinds.contains(&DataKind::ToolArguments));+ assert!(desc.data_kinds.contains(&DataKind::Metadata));+}diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rsnew file mode 100644index 0000000000..976dbf2038--- /dev/null+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@ -0,0 +1,185 @@+//! Host wiring for the network tools that live in `tinytools_std::network`.+//!+//! The tools take their limits' fallbacks, their HTML engine and their 402+//! handler from the host. This file is where OpenHuman supplies them: the+//! `[http_request]` defaults, TinyJuice for page extraction, and (with the+//! `web3` feature) the x402 payment flow.++use std::sync::Arc;++use serde_json::Value;+use tinytools_std::network::{+ HtmlExtractor, HttpLimits, HttpRequestTool, NetGate, WebFetchTool,+};++use crate::config::HttpRequestConfig;+use crate::inference::tokenjuice::focus::{summary_focus_property, SUMMARY_FOCUS_ARG};++/// The fallbacks for a `0` limit, from the `[http_request]` schema defaults, so+/// the tools, the schema and the 5→6 migration share one source.+fn http_limits() -> HttpLimits {+ let defaults = HttpRequestConfig::default();+ HttpLimits {+ max_response_size: defaults.max_response_size,+ timeout_secs: defaults.timeout_secs,+ }+}++/// TinyJuice as `web_fetch`'s page engine. `tinyjuice` owns content+/// transforms; see the dependency note in `Cargo.toml` for why this is a direct+/// call and not a trip through the module bus.+#[derive(Debug)]+struct TinyJuiceHtml;++impl HtmlExtractor for TinyJuiceHtml {+ fn looks_like_html(&self, body: &str) -> bool {+ matches!(+ tinyjuice::detect_content_kind(body, &tinyjuice::types::ContentHint::default()),+ tinyjuice::types::ContentKind::Html+ )+ }++ fn to_markdown(&self, html: &str) -> String {+ tinyjuice::compressors::html::html_to_markdown(html)+ }+}++/// `http_request`, with the x402 402-retry wired in when `web3` is compiled.+pub fn http_request_tool(+ gate: Arc<dyn NetGate>,+ allowed_domains: Vec<String>,+ max_response_size: usize,+ timeout_secs: u64,+) -> HttpRequestTool {+ let tool = HttpRequestTool::new(+ gate,+ allowed_domains,+ max_response_size,+ timeout_secs,+ http_limits(),+ );+ #[cfg(feature = "web3")]+ let tool = tool.with_payment_hook(Arc::new(x402::X402PaymentHook));+ tool+}++/// `web_fetch`, converting HTML through TinyJuice and opting into TinyJuice's+/// optional `summary_focus` argument.+pub fn web_fetch_tool(+ gate: Arc<dyn NetGate>,+ allowed_domains: Vec<String>,+ max_bytes: Option<usize>,+ timeout_secs: Option<u64>,+) -> WebFetchTool {+ WebFetchTool::new(+ gate,+ allowed_domains,+ max_bytes,+ timeout_secs,+ http_limits(),+ Arc::new(TinyJuiceHtml),+ )+ // Opts into a caller-steered summary; see `tokenjuice::focus`.+ .with_schema_property(SUMMARY_FOCUS_ARG, summary_focus_property())+}++/// The `summary_focus` schema as this file wires it, for tests.+#[cfg(test)]+pub(super) fn summary_focus_schema() -> Value {+ summary_focus_property()+}++#[cfg(feature = "web3")]+mod x402 {+ //! x402 machine payment for `http_request`'s `402 Payment Required` retry.++ use async_trait::async_trait;+ use base64::engine::Engine as _;+ use tinytools_std::network::{PaymentAttempt, PaymentHook, PaymentOutcome};++ use crate::web3::x402;++ #[derive(Debug)]+ pub(super) struct X402PaymentHook;++ #[async_trait]+ impl PaymentHook for X402PaymentHook {+ async fn pay(+ &self,+ url: &str,+ response_headers: &reqwest::header::HeaderMap,+ ) -> Result<PaymentAttempt, String> {+ let payment_result = x402::handle_402_and_pay(response_headers, url)+ .await+ .map_err(|e| format!("x402 payment failed: {e}"))?;++ // Stamped with the ledger's session and the active chat thread, exactly as+ // the `x402_request` tool stamps its own.+ let record = x402::pending_record(&payment_result);+ let record_id = record.id.clone();+ let _ = x402::store::with_ledger_mut(|l| l.record_payment(record));++ log::debug!(+ "[tool.http_request] retrying with x402 payment header amount={} asset={}",+ payment_result.amount_atomic,+ payment_result.asset+ );++ let url = url.to_string();+ Ok(PaymentAttempt {+ headers: vec![("PAYMENT-SIGNATURE".to_string(), payment_result.header_value)],+ settle: Box::new(move |outcome| settle(&record_id, &url, &outcome)),+ })+ }+ }++ /// Write the retry's result back onto the ledger entry the payment opened.+ fn settle(record_id: &str, url: &str, outcome: &PaymentOutcome) {+ let settled_status = if outcome.success {+ x402::PaymentStatus::Settled+ } else {+ x402::PaymentStatus::Failed+ };+ let tx_sig = outcome+ .payment_response+ .as_deref()+ .and_then(|b64| base64::engine::general_purpose::STANDARD.decode(b64).ok())+ .and_then(|bytes| serde_json::from_slice::<x402::SettlementResponse>(&bytes).ok())+ .and_then(|r| {+ if r.success && !r.transaction.is_empty() {+ Some(r.transaction)+ } else {+ None+ }+ });++ let _ = x402::store::with_ledger_mut(|l| {+ if let Some(rec) = l+ .recent_payments(100)+ .into_iter()+ .find(|r| r.id == record_id)+ {+ let mut updated = rec;+ updated.status = settled_status;+ updated.tx_signature = tx_sig.clone();+ l.record_payment(updated);+ }+ });++ if settled_status == x402::PaymentStatus::Settled {+ log::debug!(+ "[tool.http_request] x402 payment settled for {url} tx={:?}",+ tx_sig+ );+ } else {+ log::warn!(+ "[tool.http_request] x402 payment retry returned status {}",+ outcome.status+ );+ }+ }+}++#[cfg(test)]+#[path = "host_tests.rs"]+mod tests;