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
chore: files changed crates/openhuman-core/src/tools/impl/browser/image_info.rs,crates/openhuman-cor
Steven Enamakela2b482737f06
diff --git a/crates/openhuman-core/src/tools/impl/browser/image_info.rs b/crates/openhuman-core/src/tools/impl/browser/image_info.rsdeleted file mode 100644index 720808576f..0000000000--- a/crates/openhuman-core/src/tools/impl/browser/image_info.rs+++ /dev/null@@ -1,209 +0,0 @@-use crate::security::SecurityPolicy;-use async_trait::async_trait;-use serde_json::json;-use std::fmt::Write;-use std::sync::Arc;-use tinytools::{Tool, ToolResult};--/// Maximum file size we will read and base64-encode (5 MB).-const MAX_IMAGE_BYTES: u64 = 5_242_880;--/// Tool to read image metadata and optionally return base64-encoded data.-///-/// Since providers are currently text-only, this tool extracts what it can-/// (file size, format, dimensions from header bytes) and provides base64-/// data for future multimodal provider support.-pub struct ImageInfoTool {- security: Arc<SecurityPolicy>,-}--impl ImageInfoTool {- pub fn new(security: Arc<SecurityPolicy>) -> Self {- Self { security }- }-- /// Detect image format from first few bytes (magic numbers).- fn detect_format(bytes: &[u8]) -> &'static str {- if bytes.len() < 4 {- return "unknown";- }- if bytes.starts_with(b"\x89PNG") {- "png"- } else if bytes.starts_with(b"\xFF\xD8\xFF") {- "jpeg"- } else if bytes.starts_with(b"GIF8") {- "gif"- } else if bytes.starts_with(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {- "webp"- } else if bytes.starts_with(b"BM") {- "bmp"- } else {- "unknown"- }- }-- /// Try to extract dimensions from image header bytes.- /// Returns (width, height) if detectable.- fn extract_dimensions(bytes: &[u8], format: &str) -> Option<(u32, u32)> {- match format {- "png" => {- // PNG IHDR chunk: bytes 16-19 = width, 20-23 = height (big-endian)- if bytes.len() >= 24 {- let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);- let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);- Some((w, h))- } else {- None- }- }- "gif" => {- // GIF: bytes 6-7 = width, 8-9 = height (little-endian)- if bytes.len() >= 10 {- let w = u32::from(u16::from_le_bytes([bytes[6], bytes[7]]));- let h = u32::from(u16::from_le_bytes([bytes[8], bytes[9]]));- Some((w, h))- } else {- None- }- }- "bmp" => {- // BMP: bytes 18-21 = width, 22-25 = height (little-endian, signed)- if bytes.len() >= 26 {- let w = u32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);- let h_raw = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);- let h = h_raw.unsigned_abs();- Some((w, h))- } else {- None- }- }- "jpeg" => Self::jpeg_dimensions(bytes),- _ => None,- }- }-- /// Parse JPEG SOF markers to extract dimensions.- fn jpeg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {- let mut i = 2; // skip SOI marker- while i + 1 < bytes.len() {- if bytes[i] != 0xFF {- return None;- }- let marker = bytes[i + 1];- i += 2;-- // SOF0..SOF3 markers contain dimensions- if (0xC0..=0xC3).contains(&marker) {- if i + 7 <= bytes.len() {- let h = u32::from(u16::from_be_bytes([bytes[i + 3], bytes[i + 4]]));- let w = u32::from(u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]));- return Some((w, h));- }- return None;- }-- // Skip this segment- if i + 1 < bytes.len() {- let seg_len = u16::from_be_bytes([bytes[i], bytes[i + 1]]) as usize;- if seg_len < 2 {- return None; // Malformed segment (valid segments have length >= 2)- }- i += seg_len;- } else {- return None;- }- }- None- }-}--#[async_trait]-impl Tool for ImageInfoTool {- fn name(&self) -> &str {- "image_info"- }-- fn description(&self) -> &str {- "Read image file metadata (format, dimensions, size) and optionally return base64-encoded data."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "path": {- "type": "string",- "description": "Path to the image file (absolute or relative to workspace)"- },- "include_base64": {- "type": "boolean",- "description": "Include base64-encoded image data in output (default: false)"- }- },- "required": ["path"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let path_str = args- .get("path")- .and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;-- let include_base64 = args- .get("include_base64")- .and_then(serde_json::Value::as_bool)- .unwrap_or(false);-- // Security check: validate path string, resolve symlinks, confirm workspace containment.- let resolved = match self.security.validate_path(path_str).await {- Ok(p) => p,- Err(msg) => return Ok(ToolResult::error(msg)),- };-- let metadata = tokio::fs::metadata(&resolved)- .await- .map_err(|e| anyhow::anyhow!("Failed to read file metadata: {e}"))?;-- let file_size = metadata.len();-- if file_size > MAX_IMAGE_BYTES {- return Ok(ToolResult::error(format!(- "Image too large: {file_size} bytes (max {MAX_IMAGE_BYTES} bytes)"- )));- }-- let bytes = tokio::fs::read(&resolved)- .await- .map_err(|e| anyhow::anyhow!("Failed to read image file: {e}"))?;-- let format = Self::detect_format(&bytes);- let dimensions = Self::extract_dimensions(&bytes, format);-- let mut output = format!("File: {path_str}\nFormat: {format}\nSize: {file_size} bytes");-- if let Some((w, h)) = dimensions {- let _ = write!(output, "\nDimensions: {w}x{h}");- }-- if include_base64 {- use base64::Engine;- let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);- let mime = match format {- "png" => "image/png",- "jpeg" => "image/jpeg",- "gif" => "image/gif",- "webp" => "image/webp",- "bmp" => "image/bmp",- _ => "application/octet-stream",- };- let _ = write!(output, "\ndata:{mime};base64,{encoded}");- }-- Ok(ToolResult::success(output))- }-}--#[cfg(test)]-#[path = "image_info_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/browser/image_info_tests.rs b/crates/openhuman-core/src/tools/impl/browser/image_info_tests.rsdeleted file mode 100644index 803d2b057d..0000000000--- a/crates/openhuman-core/src/tools/impl/browser/image_info_tests.rs+++ /dev/null@@ -1,299 +0,0 @@-use super::*;-use crate::security::{AutonomyLevel, SecurityPolicy};--fn test_security() -> Arc<SecurityPolicy> {- Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Full,- workspace_dir: std::env::temp_dir(),- workspace_only: false,- forbidden_paths: vec![],- ..SecurityPolicy::default()- })-}--#[test]-fn image_info_tool_name() {- let tool = ImageInfoTool::new(test_security());- assert_eq!(tool.name(), "image_info");-}--#[test]-fn image_info_tool_description() {- let tool = ImageInfoTool::new(test_security());- assert!(!tool.description().is_empty());- assert!(tool.description().contains("image"));-}--#[test]-fn image_info_tool_schema() {- let tool = ImageInfoTool::new(test_security());- let schema = tool.parameters_schema();- assert!(schema["properties"]["path"].is_object());- assert!(schema["properties"]["include_base64"].is_object());- let required = schema["required"].as_array().unwrap();- assert!(required.contains(&json!("path")));-}--#[test]-fn image_info_tool_spec() {- let tool = ImageInfoTool::new(test_security());- let spec = tool.spec();- assert_eq!(spec.name, "image_info");- assert!(spec.parameters.is_object());-}--// ── Format detection ────────────────────────────────────────--#[test]-fn detect_png() {- let bytes = b"\x89PNG\r\n\x1a\n";- assert_eq!(ImageInfoTool::detect_format(bytes), "png");-}--#[test]-fn detect_jpeg() {- let bytes = b"\xFF\xD8\xFF\xE0";- assert_eq!(ImageInfoTool::detect_format(bytes), "jpeg");-}--#[test]-fn detect_gif() {- let bytes = b"GIF89a";- assert_eq!(ImageInfoTool::detect_format(bytes), "gif");-}--#[test]-fn detect_webp() {- let bytes = b"RIFF\x00\x00\x00\x00WEBP";- assert_eq!(ImageInfoTool::detect_format(bytes), "webp");-}--#[test]-fn detect_bmp() {- let bytes = b"BM\x00\x00";- assert_eq!(ImageInfoTool::detect_format(bytes), "bmp");-}--#[test]-fn detect_unknown_short() {- let bytes = b"\x00\x01";- assert_eq!(ImageInfoTool::detect_format(bytes), "unknown");-}--#[test]-fn detect_unknown_garbage() {- let bytes = b"this is not an image";- assert_eq!(ImageInfoTool::detect_format(bytes), "unknown");-}--// ── Dimension extraction ────────────────────────────────────--#[test]-fn png_dimensions() {- // Minimal PNG IHDR: 8-byte signature + 4-byte length + 4-byte IHDR + 4-byte width + 4-byte height- let mut bytes = vec![- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature- 0x00, 0x00, 0x00, 0x0D, // IHDR length- 0x49, 0x48, 0x44, 0x52, // "IHDR"- 0x00, 0x00, 0x03, 0x20, // width: 800- 0x00, 0x00, 0x02, 0x58, // height: 600- ];- bytes.extend_from_slice(&[0u8; 10]); // padding- let dims = ImageInfoTool::extract_dimensions(&bytes, "png");- assert_eq!(dims, Some((800, 600)));-}--#[test]-fn gif_dimensions() {- let bytes = [- 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, // GIF89a- 0x40, 0x01, // width: 320 (LE)- 0xF0, 0x00, // height: 240 (LE)- ];- let dims = ImageInfoTool::extract_dimensions(&bytes, "gif");- assert_eq!(dims, Some((320, 240)));-}--#[test]-fn bmp_dimensions() {- let mut bytes = vec![0u8; 26];- bytes[0] = b'B';- bytes[1] = b'M';- // width at offset 18 (LE): 1024- bytes[18] = 0x00;- bytes[19] = 0x04;- bytes[20] = 0x00;- bytes[21] = 0x00;- // height at offset 22 (LE): 768- bytes[22] = 0x00;- bytes[23] = 0x03;- bytes[24] = 0x00;- bytes[25] = 0x00;- let dims = ImageInfoTool::extract_dimensions(&bytes, "bmp");- assert_eq!(dims, Some((1024, 768)));-}--#[test]-fn jpeg_dimensions() {- // Minimal JPEG-like byte sequence with SOF0 marker- let mut bytes: Vec<u8> = vec![- 0xFF, 0xD8, // SOI- 0xFF, 0xE0, // APP0 marker- 0x00, 0x10, // APP0 length = 16- ];- bytes.extend_from_slice(&[0u8; 14]); // APP0 payload- bytes.extend_from_slice(&[- 0xFF, 0xC0, // SOF0 marker- 0x00, 0x11, // SOF0 length- 0x08, // precision- 0x01, 0xE0, // height: 480- 0x02, 0x80, // width: 640- ]);- let dims = ImageInfoTool::extract_dimensions(&bytes, "jpeg");- assert_eq!(dims, Some((640, 480)));-}--#[test]-fn jpeg_malformed_zero_length_segment() {- // Zero-length segment should return None instead of looping forever- let bytes: Vec<u8> = vec![- 0xFF, 0xD8, // SOI- 0xFF, 0xE0, // APP0 marker- 0x00, 0x00, // length = 0 (malformed)- ];- let dims = ImageInfoTool::extract_dimensions(&bytes, "jpeg");- assert!(dims.is_none());-}--#[test]-fn unknown_format_no_dimensions() {- let bytes = b"random data here";- let dims = ImageInfoTool::extract_dimensions(bytes, "unknown");- assert!(dims.is_none());-}--// ── Execute tests ───────────────────────────────────────────--#[tokio::test]-async fn execute_missing_path() {- let tool = ImageInfoTool::new(test_security());- let result = tool.execute(json!({})).await;- assert!(result.is_err());-}--#[tokio::test]-async fn execute_nonexistent_file() {- let tool = ImageInfoTool::new(test_security());- let result = tool- .execute(json!({"path": "nonexistent_image_xyz.png"}))- .await- .unwrap();- assert!(result.is_error);- assert!(- result.output().contains("not allowed") || result.output().contains("Failed to resolve"),- "unexpected error: {}",- result.output()- );-}--#[tokio::test]-async fn execute_real_file() {- // Create a minimal valid PNG- let dir = std::env::temp_dir().join("openhuman_image_info_test");- let _ = tokio::fs::create_dir_all(&dir).await;- let png_path = dir.join("test.png");-- // Minimal 1x1 red PNG (67 bytes)- let png_bytes: Vec<u8> = vec![- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // signature- 0x00, 0x00, 0x00, 0x0D, // IHDR length- 0x49, 0x48, 0x44, 0x52, // IHDR- 0x00, 0x00, 0x00, 0x01, // width: 1- 0x00, 0x00, 0x00, 0x01, // height: 1- 0x08, 0x02, 0x00, 0x00, 0x00, // bit depth, color type, etc.- 0x90, 0x77, 0x53, 0xDE, // CRC- 0x00, 0x00, 0x00, 0x0C, // IDAT length- 0x49, 0x44, 0x41, 0x54, // IDAT- 0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC,- 0x33, // CRC- 0x00, 0x00, 0x00, 0x00, // IEND length- 0x49, 0x45, 0x4E, 0x44, // IEND- 0xAE, 0x42, 0x60, 0x82, // CRC- ];- tokio::fs::write(&png_path, &png_bytes).await.unwrap();-- let tool = ImageInfoTool::new(test_security());- let result = tool- .execute(json!({"path": png_path.to_string_lossy()}))- .await- .unwrap();- assert!(!result.is_error);- assert!(result.output().contains("Format: png"));- assert!(result.output().contains("Dimensions: 1x1"));- assert!(!result.output().contains("data:"));-- // Clean up- let _ = tokio::fs::remove_dir_all(&dir).await;-}--/// A decompression-bomb-shaped PNG (a header claiming an enormous canvas,-/// backed by a file well under `MAX_IMAGE_BYTES`) must not blow up memory or-/// hang: `extract_dimensions` reads four fixed IHDR bytes and never inflates-/// pixel data, so the claimed 60000x60000 canvas is read as fast as any other-/// header and no allocation is proportional to it.-#[tokio::test]-async fn execute_reports_a_bomb_shaped_header_without_decoding_pixels() {- let dir = std::env::temp_dir().join("openhuman_image_info_bomb");- let _ = tokio::fs::create_dir_all(&dir).await;- let png_path = dir.join("bomb.png");-- let mut bytes = vec![- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // signature- 0x00, 0x00, 0x00, 0x0D, // IHDR length- 0x49, 0x48, 0x44, 0x52, // "IHDR"- 0x00, 0x00, 0xEA, 0x60, // width: 60000- 0x00, 0x00, 0xEA, 0x60, // height: 60000- ];- bytes.extend_from_slice(&[0u8; 10]); // pad past the 24 bytes IHDR parsing reads- tokio::fs::write(&png_path, &bytes).await.unwrap();-- let tool = ImageInfoTool::new(test_security());- let result = tokio::time::timeout(- std::time::Duration::from_secs(2),- tool.execute(json!({"path": png_path.to_string_lossy()})),- )- .await- .expect("image-info execution must settle within two seconds")- .unwrap();- assert!(!result.is_error, "{}", result.output());- assert!(result.output().contains("Dimensions: 60000x60000"));-- let _ = tokio::fs::remove_dir_all(&dir).await;-}--#[tokio::test]-async fn execute_with_base64() {- let dir = std::env::temp_dir().join("openhuman_image_info_b64");- let _ = tokio::fs::create_dir_all(&dir).await;- let png_path = dir.join("test_b64.png");-- // Minimal 1x1 PNG- let png_bytes: Vec<u8> = vec![- 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,- 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,- 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08, 0xD7, 0x63, 0xF8,- 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC, 0x33, 0x00, 0x00, 0x00,- 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,- ];- tokio::fs::write(&png_path, &png_bytes).await.unwrap();-- let tool = ImageInfoTool::new(test_security());- let result = tool- .execute(json!({"path": png_path.to_string_lossy(), "include_base64": true}))- .await- .unwrap();- assert!(!result.is_error);- assert!(result.output().contains("data:image/png;base64,"));-- let _ = tokio::fs::remove_dir_all(&dir).await;-}diff --git a/crates/openhuman-core/src/tools/impl/browser/mod.rs b/crates/openhuman-core/src/tools/impl/browser/mod.rsindex c3c3f4c162..667e1e563a 100644--- a/crates/openhuman-core/src/tools/impl/browser/mod.rs+++ b/crates/openhuman-core/src/tools/impl/browser/mod.rs@@ -5,11 +5,9 @@mod browser;#[cfg(feature = "modules")]mod browser_open;-mod image_info;mod security;#[cfg(feature = "modules")]pub use browser::BrowserTool;#[cfg(feature = "modules")]pub use browser_open::BrowserOpenTool;-pub use image_info::ImageInfoTool;diff --git a/crates/openhuman-core/src/tools/impl/network/curl.rs b/crates/openhuman-core/src/tools/impl/network/curl.rsdeleted file mode 100644index 0243b022da..0000000000--- a/crates/openhuman-core/src/tools/impl/network/curl.rs+++ /dev/null@@ -1,416 +0,0 @@-//! `curl` — download files from the web to a path under the workspace.-//!-//! Distinct from `http_request`: instead of returning the body inline-//! (size-capped), `curl` streams to disk with a hard byte ceiling. Same-//! SSRF/allowlist guards (shared via `url_guard`), shares-//! `http_request.allowed_domains` so there is one allowlist to reason-//! about.--use crate::security::{CommandClass, GateDecision, SecurityPolicy};-use async_trait::async_trait;-use futures_util::StreamExt;-use sha2::{Digest, Sha256};-use std::path::{Component, Path, PathBuf};-use std::sync::Arc;-use std::time::Duration;-use tinytools::{PermissionLevel, Tool, ToolResult};-use tinytools_std::url_guard::{normalize_allowed_domains, validate_url_with_dns_check};-use tokio::fs;-use tokio::io::AsyncWriteExt;--pub struct CurlTool {- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- workspace_dir: PathBuf,- dest_subdir: String,- max_download_bytes: u64,- timeout_secs: u64,-}--impl CurlTool {- pub fn new(- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- workspace_dir: PathBuf,- dest_subdir: String,- max_download_bytes: u64,- timeout_secs: u64,- ) -> Self {- Self {- security,- allowed_domains: normalize_allowed_domains(allowed_domains),- workspace_dir,- dest_subdir: sanitize_dest_subdir(&dest_subdir),- max_download_bytes,- timeout_secs,- }- }-- /// Resolve a user-supplied dest path to an absolute path inside- /// `<workspace>/<dest_subdir>`. Rejects absolute paths, `..`- /// segments, and any other escape attempts.- fn resolve_dest(&self, dest: &str) -> anyhow::Result<PathBuf> {- let trimmed = dest.trim();- if trimmed.is_empty() {- anyhow::bail!("dest_path cannot be empty");- }-- let p = Path::new(trimmed);- if p.is_absolute() {- anyhow::bail!("dest_path must be relative — got absolute path");- }-- for component in p.components() {- match component {- Component::Normal(_) => {}- Component::CurDir => {}- Component::ParentDir => {- anyhow::bail!("dest_path may not contain '..'");- }- Component::Prefix(_) | Component::RootDir => {- anyhow::bail!("dest_path must be relative");- }- }- }-- let root = self.workspace_dir.join(&self.dest_subdir);- let resolved = root.join(p);-- // Belt-and-braces: ensure the resolved path still lives under root.- // Lexical check is sufficient because we already rejected `..`.- if !resolved.starts_with(&root) {- anyhow::bail!("dest_path resolves outside the downloads root");- }-- Ok(resolved)- }-- async fn validate_url(&self, raw_url: &str) -> anyhow::Result<String> {- validate_url_with_dns_check(raw_url, &self.allowed_domains)- .await- .map(|v| v.url)- }-- fn default_filename_from_url(url: &str) -> String {- let after_scheme = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);- let path_part = after_scheme.split_once('/').map(|(_, p)| p).unwrap_or("");- let last = path_part- .split('?')- .next()- .unwrap_or("")- .rsplit('/')- .next()- .unwrap_or("");- let cleaned: String = last- .chars()- .filter(|c| c.is_alphanumeric() || matches!(c, '.' | '-' | '_'))- .collect();- if cleaned.is_empty() {- "download.bin".into()- } else {- cleaned- }- }-}--#[async_trait]-impl Tool for CurlTool {- fn exposure(&self) -> tinytools::ToolExposure {- tinytools::ToolExposure::Deferred- }-- fn name(&self) -> &str {- "curl"- }-- fn description(&self) -> &str {- "Download a file from an http(s) URL into the workspace. The body is streamed to disk \- with a hard byte ceiling. Same allowlist as `http_request`. Returns the saved path, \- bytes written, content-type, and SHA-256 of the file."- }-- fn parameters_schema(&self) -> serde_json::Value {- serde_json::json!({- "type": "object",- "properties": {- "url": {- "type": "string",- "description": "HTTP or HTTPS URL of the file to download"- },- "dest_path": {- "type": "string",- "description": "Destination path relative to the downloads root inside the workspace. No '..' or absolute paths. If omitted, the filename is inferred from the URL."- },- "headers": {- "type": "object",- "description": "Optional HTTP headers (e.g. {\"Authorization\": \"Bearer …\"})",- "default": {}- }- },- "required": ["url"]- })- }-- /// Downloading from the network is the always-ask `Network` bucket — it- /// prompts the human in both ask-before-edit and Full; read-only is blocked- /// in `execute`.- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.security.gate_decision(CommandClass::Network) == GateDecision::Prompt- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let url = args- .get("url")- .and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;-- let dest_arg = args.get("dest_path").and_then(|v| v.as_str());- let headers_val = args- .get("headers")- .cloned()- .unwrap_or_else(|| serde_json::json!({}));-- if !self.security.can_act() {- tracing::debug!(target: "[curl]", url = %url, "blocked: autonomy read-only");- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: autonomy is read-only",- ));- }- if !self.security.record_action() {- tracing::debug!(target: "[curl]", url = %url, "blocked: rate limit");- return Ok(ToolResult::error("Action blocked: rate limit exceeded"));- }-- // Local-only enforcement (privacy epic S7, #4441): mirror the read-only- // `can_act()` deny above — under LocalOnly, refuse the download before- // URL validation / DNS so nothing leaves the device.- {- let host = reqwest::Url::parse(url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- if let Some(msg) = crate::security::egress::local_only_tool_block(- &crate::security::egress::EgressDescriptor::network_fetch(host.clone()),- ) {- // Log only the host, never the full URL: a raw URL can carry- // secrets in its query string (pre-signed links, tokens). The- // gate helper already logs `desc.service` (host only) too.- tracing::debug!(target: "[curl]", host = %host, "blocked: local-only privacy mode");- return Ok(ToolResult::error(msg));- }- }-- let url = match self.validate_url(url).await {- Ok(v) => v,- Err(e) => {- tracing::debug!(target: "[curl]", url = %url, reason = %e, "url validation failed");- return Ok(ToolResult::error(e.to_string()));- }- };-- // Egress spine (privacy epic S2/S7, #4436/#4441): a curl download- // contacts an external host — disclose the destination (and that custom- // headers ride along) before the request. Enforcement already ran at the- // top of `execute`; this is the observe-only disclosure for permitted- // downloads.- {- use crate::security::egress::{DataKind, EgressDescriptor};- let host = reqwest::Url::parse(&url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- let has_headers = headers_val- .as_object()- .map(|h| !h.is_empty())- .unwrap_or(false);- let mut desc = EgressDescriptor::network_fetch(host);- if has_headers {- desc = desc.with_data_kind(DataKind::Metadata);- }- crate::security::egress::emit_external_transfer(desc);- }-- let dest = match dest_arg {- Some(d) => d.to_string(),- None => Self::default_filename_from_url(&url),- };- let dest_path = match self.resolve_dest(&dest) {- Ok(p) => p,- Err(e) => {- tracing::debug!(target: "[curl]", url = %url, dest = %dest, reason = %e, "dest_path rejected");- return Ok(ToolResult::error(e.to_string()));- }- };-- if let Some(parent) = dest_path.parent() {- if let Err(e) = fs::create_dir_all(parent).await {- tracing::error!(target: "[curl]", url = %url, dest = %dest_path.display(), reason = %e, "create_dir_all failed");- return Ok(ToolResult::error(format!(- "Failed to create destination directory: {e}"- )));- }- }-- let builder = reqwest::Client::builder()- .timeout(Duration::from_secs(self.timeout_secs))- .connect_timeout(Duration::from_secs(10))- .redirect(reqwest::redirect::Policy::none());- let builder = crate::config::apply_runtime_proxy_to_builder(builder, "tool.curl");- let client = match builder.build() {- Ok(c) => c,- Err(e) => {- tracing::error!(target: "[curl]", reason = %e, "HTTP client build failed");- return Ok(ToolResult::error(format!("HTTP client build failed: {e}")));- }- };-- let mut request = client.get(&url);- if let Some(obj) = headers_val.as_object() {- for (k, v) in obj {- if let Some(s) = v.as_str() {- request = request.header(k, s);- }- }- }-- tracing::debug!(target: "[curl]", url = %url, dest = %dest_path.display(), "starting download");-- let response = match request.send().await {- Ok(r) => r,- Err(e) => {- tracing::error!(target: "[curl]", url = %url, reason = %e, "request send failed");- return Ok(ToolResult::error(format!("Request failed: {e}")));- }- };-- let status = response.status();- if !status.is_success() {- tracing::debug!(target: "[curl]", url = %url, status = %status.as_u16(), "non-success HTTP status");- return Ok(ToolResult::error(format!(- "HTTP {} {}",- status.as_u16(),- status.canonical_reason().unwrap_or("Unknown")- )));- }-- let content_type = response- .headers()- .get(reqwest::header::CONTENT_TYPE)- .and_then(|v| v.to_str().ok())- .unwrap_or("application/octet-stream")- .to_string();-- let mut file = match fs::File::create(&dest_path).await {- Ok(f) => f,- Err(e) => {- tracing::error!(target: "[curl]", dest = %dest_path.display(), reason = %e, "fs::File::create failed");- return Ok(ToolResult::error(format!(- "Failed to create destination file: {e}"- )));- }- };-- let mut hasher = Sha256::new();- let mut bytes_written: u64 = 0;- let mut stream = response.bytes_stream();-- while let Some(chunk) = stream.next().await {- let chunk = match chunk {- Ok(c) => c,- Err(e) => {- drop(file);- if let Err(rm) = fs::remove_file(&dest_path).await {- tracing::debug!(target: "[curl]", dest = %dest_path.display(), reason = %rm, "cleanup remove_file failed");- }- tracing::error!(target: "[curl]", url = %url, bytes_written, reason = %e, "stream error");- return Ok(ToolResult::error(format!("Stream error: {e}")));- }- };-- if bytes_written.saturating_add(chunk.len() as u64) > self.max_download_bytes {- let _ = file.flush().await;- drop(file);- if let Err(rm) = fs::remove_file(&dest_path).await {- tracing::debug!(target: "[curl]", dest = %dest_path.display(), reason = %rm, "cleanup remove_file failed");- }- tracing::error!(target: "[curl]", url = %url, bytes_written, max = self.max_download_bytes, "size cap exceeded — download aborted");- return Ok(ToolResult::error(format!(- "Download exceeded max_download_bytes ({} bytes)",- self.max_download_bytes- )));- }-- if let Err(e) = file.write_all(&chunk).await {- drop(file);- if let Err(rm) = fs::remove_file(&dest_path).await {- tracing::debug!(target: "[curl]", dest = %dest_path.display(), reason = %rm, "cleanup remove_file failed");- }- tracing::error!(target: "[curl]", dest = %dest_path.display(), bytes_written, reason = %e, "write_all failed");- return Ok(ToolResult::error(format!("Write failed: {e}")));- }- hasher.update(&chunk);- bytes_written += chunk.len() as u64;- }-- if let Err(e) = file.flush().await {- drop(file);- if let Err(rm) = fs::remove_file(&dest_path).await {- tracing::debug!(target: "[curl]", dest = %dest_path.display(), reason = %rm, "cleanup remove_file failed");- }- tracing::error!(target: "[curl]", dest = %dest_path.display(), bytes_written, reason = %e, "flush failed");- return Ok(ToolResult::error(format!("Flush failed: {e}")));- }-- let sha256 = format!("{:x}", hasher.finalize());-- tracing::debug!(- target: "[curl]",- url = %url,- dest = %dest_path.display(),- bytes = bytes_written,- content_type = %content_type,- sha256 = %sha256,- "download complete"- );-- let payload = serde_json::json!({- "path": dest_path.display().to_string(),- "bytes_written": bytes_written,- "content_type": content_type,- "sha256": sha256,- });- Ok(ToolResult::success(payload.to_string()))- }-}--/// Sanitize the configured `dest_subdir` so a malicious or misconfigured-/// `[curl].dest_subdir` cannot escape the workspace via absolute paths-/// or `..` segments. Drops disallowed components rather than panicking;-/// falls back to `"downloads"` if everything is filtered out.-fn sanitize_dest_subdir(raw: &str) -> String {- let trimmed = raw.trim();- if trimmed.is_empty() {- return "downloads".into();- }- let p = Path::new(trimmed);- let mut buf = PathBuf::new();- for component in p.components() {- match component {- Component::Normal(c) => buf.push(c),- // Drop everything else: absolute roots, prefixes, parent dirs, cur dirs.- _ => continue,- }- }- if buf.as_os_str().is_empty() {- return "downloads".into();- }- buf.to_string_lossy().into_owned()-}--#[cfg(test)]-#[path = "curl_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/network/curl_tests.rs b/crates/openhuman-core/src/tools/impl/network/curl_tests.rsdeleted file mode 100644index d62eb4b7fe..0000000000--- a/crates/openhuman-core/src/tools/impl/network/curl_tests.rs+++ /dev/null@@ -1,257 +0,0 @@-use super::*;-use crate::security::SecurityPolicy;-use tempfile::TempDir;-fn slash_norm(s: String) -> String {- s.replace('\\', "/")-}--fn tool(tmp: &TempDir, allow: Vec<&str>) -> CurlTool {- CurlTool::new(- Arc::new(SecurityPolicy::default()),- allow.into_iter().map(String::from).collect(),- tmp.path().to_path_buf(),- "downloads".into(),- 1024 * 1024,- 30,- )-}--#[test]-fn sanitize_dest_subdir_strips_absolute_paths() {- assert_eq!(- slash_norm(sanitize_dest_subdir("/etc/passwd")),- "etc/passwd"- );- assert_eq!(sanitize_dest_subdir("//foo"), "foo");-}--#[test]-fn sanitize_dest_subdir_strips_parent_segments() {- assert_eq!(sanitize_dest_subdir("../../etc"), "etc");- assert_eq!(slash_norm(sanitize_dest_subdir("a/../b")), "a/b");-}--#[test]-fn sanitize_dest_subdir_falls_back_to_downloads() {- assert_eq!(sanitize_dest_subdir(""), "downloads");- assert_eq!(sanitize_dest_subdir(" "), "downloads");- assert_eq!(sanitize_dest_subdir(".."), "downloads");- assert_eq!(sanitize_dest_subdir("/"), "downloads");-}--#[test]-fn sanitize_dest_subdir_keeps_normal_paths() {- assert_eq!(sanitize_dest_subdir("downloads"), "downloads");- assert_eq!(- slash_norm(sanitize_dest_subdir("artifacts/build")),- "artifacts/build"- );-}--#[test]-fn new_sanitizes_malicious_dest_subdir() {- let tmp = TempDir::new().unwrap();- let t = CurlTool::new(- Arc::new(SecurityPolicy::default()),- vec!["example.com".into()],- tmp.path().to_path_buf(),- "../../etc".into(),- 1024,- 30,- );- let resolved = t.resolve_dest("file.txt").unwrap();- // Sanitizer reduced "../../etc" to "etc"; resolution must stay under workspace.- assert!(resolved.starts_with(tmp.path().join("etc")));- assert!(resolved.starts_with(tmp.path()));-}--#[test]-fn resolve_dest_normal() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let p = t.resolve_dest("foo/bar.txt").unwrap();- assert!(p.starts_with(tmp.path().join("downloads")));- assert!(p.ends_with("foo/bar.txt"));-}--#[test]-fn resolve_dest_rejects_absolute() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let err = t.resolve_dest("/etc/passwd").unwrap_err().to_string();- assert!(err.contains("relative"));-}--#[test]-fn resolve_dest_rejects_parent_dir() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let err = t.resolve_dest("../etc/passwd").unwrap_err().to_string();- assert!(err.contains(".."));-}--#[test]-fn resolve_dest_rejects_nested_parent_dir() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let err = t.resolve_dest("a/../../b").unwrap_err().to_string();- assert!(err.contains(".."));-}--#[test]-fn resolve_dest_rejects_empty() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- assert!(t.resolve_dest("").is_err());- assert!(t.resolve_dest(" ").is_err());-}--#[tokio::test]-async fn validate_url_rejects_disallowed_domain() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let err = t- .validate_url("https://evil.test/archive.tar.gz")- .await- .unwrap_err()- .to_string();- assert!(err.contains("allowed websites"));-}--#[test]-fn default_filename_from_url_basic() {- assert_eq!(- CurlTool::default_filename_from_url("https://example.com/foo/bar.zip"),- "bar.zip"- );-}--#[test]-fn default_filename_from_url_query_stripped() {- assert_eq!(- CurlTool::default_filename_from_url("https://example.com/file.tar.gz?token=x"),- "file.tar.gz"- );-}--#[test]-fn default_filename_from_url_root_falls_back() {- assert_eq!(- CurlTool::default_filename_from_url("https://example.com/"),- "download.bin"- );-}--#[tokio::test]-async fn execute_blocks_when_rate_limited() {- let tmp = TempDir::new().unwrap();- let security = Arc::new(SecurityPolicy {- max_actions_per_hour: 0,- ..SecurityPolicy::default()- });- let t = CurlTool::new(- security,- vec!["example.com".into()],- tmp.path().into(),- "downloads".into(),- 1024,- 30,- );- let result = t- .execute(serde_json::json!({"url": "https://example.com/x"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("rate limit"));-}--#[tokio::test]-async fn execute_blocked_under_local_only_privacy_mode() {- // Privacy epic S7 (#4441): under LocalOnly the download is refused with a- // `[policy-blocked]` result before URL validation / network.- let _mode = super::super::local_only_scope();- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let result = t- .execute(serde_json::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()- );-}--/// Live integration smoke: downloads example.com (a tiny, stable-/// public page). Gated behind `OPENHUMAN_CURL_LIVE_TEST=1` so CI /-/// offline runs don't depend on the network.-#[tokio::test]-async fn live_download_example_com() {- if std::env::var("OPENHUMAN_CURL_LIVE_TEST").ok().as_deref() != Some("1") {- return;- }- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let result = t- .execute(serde_json::json!({- "url": "https://example.com/",- "dest_path": "example.html"- }))- .await- .unwrap();- assert!(!result.is_error, "live curl errored: {}", result.output());- let payload: serde_json::Value = serde_json::from_str(&result.output()).unwrap();- let bytes = payload["bytes_written"].as_u64().unwrap();- assert!(bytes > 100, "unexpectedly small download: {bytes} bytes");- let path = payload["path"].as_str().unwrap();- let content = std::fs::read_to_string(path).unwrap();- assert!(content.to_lowercase().contains("example domain"));-}--#[tokio::test]-async fn execute_rejects_allowlist_miss() {- let tmp = TempDir::new().unwrap();- let t = tool(&tmp, vec!["example.com"]);- let result = t- .execute(serde_json::json!({"url": "https://other.example.org/x"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("allowed websites"));-}--/// The downloads root cannot be created (a plain file already occupies its-/// path) — `create_dir_all` must be reported as a tool error, never a panic,-/// and no network request is attempted before that check runs. The URL uses-/// a public IPv4 literal (never actually contacted — `create_dir_all` fails-/// and returns before any HTTP client is built) so `validate_url_with_dns_check`-/// takes its IP-literal short-circuit and this test needs no live DNS.-#[tokio::test]-async fn execute_reports_a_create_dir_all_failure_rather_than_panicking() {- let tmp = TempDir::new().unwrap();- std::fs::write(tmp.path().join("downloads"), b"not a directory").unwrap();- let t = tool(&tmp, vec!["8.8.8.8"]);- let result = t- .execute(serde_json::json!({"url": "https://8.8.8.8/x", "dest_path": "sub/file.txt"}))- .await- .unwrap();- assert!(- result.is_error,- "an unwritable downloads root must be reported, not panic: {}",- result.output()- );- assert!(- result- .output()- .contains("Failed to create destination directory"),- "must fail at the create_dir_all step specifically, not e.g. DNS resolution: {}",- result.output()- );-}diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rsindex 976dbf2038..ea21c00e64 100644--- a/crates/openhuman-core/src/tools/impl/network/host.rs+++ b/crates/openhuman-core/src/tools/impl/network/host.rs@@ -83,12 +83,6 @@ pub fn web_fetch_tool(.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.diff --git a/crates/openhuman-core/src/tools/impl/network/host_tests.rs b/crates/openhuman-core/src/tools/impl/network/host_tests.rsnew file mode 100644index 0000000000..d57213003f--- /dev/null+++ b/crates/openhuman-core/src/tools/impl/network/host_tests.rs@@ -0,0 +1,101 @@+use super::*;+use crate::security::SecurityPolicy;+use serde_json::json;+use tinytools::Tool;++fn fetch() -> WebFetchTool {+ web_fetch_tool(+ Arc::new(SecurityPolicy::default()),+ vec!["example.com".into()],+ None,+ None,+ )+}++#[test]+fn web_fetch_opts_into_an_optional_summary_focus() {+ let schema = fetch().parameters_schema();+ assert_eq!(schema["properties"][SUMMARY_FOCUS_ARG]["type"], "string");+ assert!(!schema["required"]+ .as_array()+ .unwrap()+ .contains(&json!(SUMMARY_FOCUS_ARG)));+ // The tool's schema declares TinyJuice's own property, not a lookalike.+ assert!(crate::inference::tokenjuice::focus::declares_summary_focus(&schema));+}++/// The exact wire contract `web_fetch` had before it moved: name, description,+/// permission, exposure and the schema including `summary_focus`.+#[test]+fn web_fetch_advertises_its_pre_move_contract() {+ let tool = fetch();+ let described = json!({+ "name": tool.name(),+ "description": tool.description(),+ "permission_level": format!("{:?}", tool.permission_level()),+ "exposure": format!("{:?}", tool.exposure()),+ "schema": tool.parameters_schema(),+ });+ let expected: serde_json::Value = serde_json::from_str(+ r#"{+ "description": "GET a URL and read the page. HTML returns as Markdown (links kept, scripts dropped); `raw: true` for the body as sent. For POST or custom headers use `http_request`.",+ "exposure": "Direct",+ "name": "web_fetch",+ "permission_level": "ReadOnly",+ "schema": {+ "properties": {+ "max_bytes": {+ "description": "Truncate body at this many bytes (default 1_000_000).",+ "minimum": 1,+ "type": "integer"+ },+ "raw": {+ "description": "Return the body as sent.",+ "type": "boolean"+ },+ "summary_focus": {+ "description": "What you need from this result. A large result is summarized around this; the full output stays retrievable.",+ "type": "string"+ },+ "url": {+ "description": "Absolute http(s) URL.",+ "type": "string"+ }+ },+ "required": [+ "url"+ ],+ "type": "object"+ }+}"#,+ )+ .unwrap();+ assert_eq!(described, expected);+}++#[test]+fn zero_limits_fall_back_to_the_http_request_config_defaults() {+ let defaults = HttpRequestConfig::default();+ let limits = http_limits();+ assert_eq!(limits.max_response_size, defaults.max_response_size);+ assert_eq!(limits.timeout_secs, defaults.timeout_secs);+ assert_ne!(limits.max_response_size, 0);+ assert_ne!(limits.timeout_secs, 0);+}++#[test]+fn tinyjuice_detects_and_converts_html() {+ let page = "<!DOCTYPE html><html><body><p>hi</p></body></html>";+ assert!(TinyJuiceHtml.looks_like_html(page));+ assert!(!TinyJuiceHtml.looks_like_html("# Just a README\n\nSome prose.\n"));+ assert!(TinyJuiceHtml.to_markdown(page).contains("hi"));+}++#[cfg(feature = "web3")]+#[test]+fn http_request_with_web3_installs_the_payment_hook() {+ // A 402 without a hook would pass through unpaid; this pins that the host+ // wiring hands the tool one. The hook itself is exercised upstream.+ let tool = http_request_tool(Arc::new(SecurityPolicy::default()), vec![], 1024, 30);+ assert_eq!(tool.name(), "http_request");+}diff --git a/crates/openhuman-core/src/tools/impl/network/http_request.rs b/crates/openhuman-core/src/tools/impl/network/http_request.rsdeleted file mode 100644index 729933285d..0000000000--- a/crates/openhuman-core/src/tools/impl/network/http_request.rs+++ /dev/null@@ -1,454 +0,0 @@-use crate::config::HttpRequestConfig;-use crate::security::{CommandClass, GateDecision, SecurityPolicy};-use async_trait::async_trait;-use tinytools::{PermissionLevel, Tool, ToolResult};-use tinytools_std::url_guard::{normalize_allowed_domains, validate_url_with_dns_check};-// Only used by the `web3`-gated x402 402-retry path below.-#[cfg(feature = "web3")]-use base64::engine::Engine as _;-use serde_json::json;-use std::sync::Arc;-use std::time::Duration;--/// 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.-fn network_egress_descriptor(- url: &str,- has_body: bool,- has_headers: bool,-) -> crate::security::egress::EgressDescriptor {- use crate::security::egress::{DataKind, EgressDescriptor};- let host = reqwest::Url::parse(url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- 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-}--/// HTTP request tool for API interactions.-/// Supports GET, POST, PUT, DELETE methods with configurable security.-pub struct HttpRequestTool {- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- max_response_size: usize,- timeout_secs: u64,-}--impl HttpRequestTool {- pub fn new(- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- max_response_size: usize,- timeout_secs: u64,- ) -> Self {- // Treat `0` as "use default": a 0-byte cap or 0-second timeout is never- // a meaningful limit, only a footgun (see migration 5→6). Pull the- // fallbacks from `HttpRequestConfig::default()` so the tool, the schema- // default, and the migration share one source and can't drift. A `0`- // here means a stale/invalid config slipped past the migration, so- // surface it with a stable, grep-friendly, non-sensitive log line.- let defaults = HttpRequestConfig::default();- let max_response_size = if max_response_size == 0 {- log::warn!(- "[tool.http_request] coercing invalid limit field=max_response_size \- from=0 to={} (stale/invalid config — see migration 5→6)",- defaults.max_response_size- );- defaults.max_response_size- } else {- max_response_size- };- let timeout_secs = if timeout_secs == 0 {- log::warn!(- "[tool.http_request] coercing invalid limit field=timeout_secs \- from=0 to={} (stale/invalid config — see migration 5→6)",- defaults.timeout_secs- );- defaults.timeout_secs- } else {- timeout_secs- };- Self {- security,- allowed_domains: normalize_allowed_domains(allowed_domains),- max_response_size,- timeout_secs,- }- }-- async fn validate_url(&self, raw_url: &str) -> anyhow::Result<String> {- validate_url_with_dns_check(raw_url, &self.allowed_domains)- .await- .map(|v| v.url)- }-- fn validate_method(&self, method: &str) -> anyhow::Result<reqwest::Method> {- match method.to_uppercase().as_str() {- "GET" => Ok(reqwest::Method::GET),- "POST" => Ok(reqwest::Method::POST),- "PUT" => Ok(reqwest::Method::PUT),- "DELETE" => Ok(reqwest::Method::DELETE),- "PATCH" => Ok(reqwest::Method::PATCH),- "HEAD" => Ok(reqwest::Method::HEAD),- "OPTIONS" => Ok(reqwest::Method::OPTIONS),- _ => anyhow::bail!("Unsupported HTTP method: {method}. Supported: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS"),- }- }-- fn parse_headers(&self, headers: &serde_json::Value) -> Vec<(String, String)> {- let mut result = Vec::new();- if let Some(obj) = headers.as_object() {- for (key, value) in obj {- if let Some(str_val) = value.as_str() {- result.push((key.clone(), str_val.to_string()));- }- }- }- result- }-- fn redact_headers_for_display(headers: &[(String, String)]) -> Vec<(String, String)> {- headers- .iter()- .map(|(key, value)| {- let lower = key.to_lowercase();- let is_sensitive = lower.contains("authorization")- || lower.contains("api-key")- || lower.contains("apikey")- || lower.contains("token")- || lower.contains("secret");- if is_sensitive {- (key.clone(), "***REDACTED***".into())- } else {- (key.clone(), value.clone())- }- })- .collect()- }-- async fn execute_request(- &self,- url: &str,- method: reqwest::Method,- headers: Vec<(String, String)>,- body: Option<&str>,- ) -> anyhow::Result<reqwest::Response> {- let builder = reqwest::Client::builder()- .timeout(Duration::from_secs(self.timeout_secs))- .connect_timeout(Duration::from_secs(10))- .redirect(reqwest::redirect::Policy::none());- let builder = crate::config::apply_runtime_proxy_to_builder(builder, "tool.http_request");- let client = builder.build()?;-- let mut request = client.request(method, url);-- for (key, value) in headers {- request = request.header(&key, &value);- }-- if let Some(body_str) = body {- request = request.body(body_str.to_string());- }-- Ok(request.send().await?)- }-- // x402 machine-payment retry — gated with the `web3` feature (the x402- // domain, its ledger, and the `SettlementResponse`/`PaymentRecord` types- // are compiled out when web3 is disabled). With the feature off, a 402 is- // returned to the caller unpaid (see the call site).- #[cfg(feature = "web3")]- async fn handle_x402_payment(- &self,- _initial_response: reqwest::Response,- url: &str,- method: reqwest::Method,- headers: Vec<(String, String)>,- body: Option<&str>,- ) -> Result<reqwest::Response, String> {- use crate::web3::x402;-- log::debug!("[tool.http_request] 402 received with PAYMENT-REQUIRED, attempting x402 payment for {url}");-- let initial_headers = _initial_response.headers().clone();- let payment_result = x402::handle_402_and_pay(&initial_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 mut retry_headers = headers;- retry_headers.push(("PAYMENT-SIGNATURE".to_string(), payment_result.header_value));-- let response = self- .execute_request(url, method, retry_headers, body)- .await- .map_err(|e| format!("x402 retry request failed: {e}"))?;-- let settled_status = if response.status().is_success() {- x402::PaymentStatus::Settled- } else {- x402::PaymentStatus::Failed- };- let tx_sig = response- .headers()- .get("PAYMENT-RESPONSE")- .and_then(|v| v.to_str().ok())- .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 {}",- response.status()- );- }-- Ok(response)- }-- async fn format_response(&self, response: reqwest::Response) -> anyhow::Result<ToolResult> {- let status = response.status();- let status_code = status.as_u16();-- let response_headers = response.headers().iter();- let headers_text = response_headers- .map(|(k, _)| {- let is_sensitive = k.as_str().to_lowercase().contains("set-cookie");- if is_sensitive {- format!("{}: ***REDACTED***", k.as_str())- } else {- format!("{}: {:?}", k.as_str(), k.as_str())- }- })- .collect::<Vec<_>>()- .join(", ");-- let response_text = match response.text().await {- Ok(text) => self.truncate_response(&text),- Err(e) => format!("[Failed to read response body: {e}]"),- };-- let output = format!(- "Status: {} {}\nResponse Headers: {}\n\nResponse Body:\n{}",- status_code,- status.canonical_reason().unwrap_or("Unknown"),- headers_text,- response_text- );-- if status.is_success() {- Ok(ToolResult::success(output))- } else {- Ok(ToolResult::error(format!("HTTP {}", status_code)))- }- }-- fn truncate_response(&self, text: &str) -> String {- if text.len() > self.max_response_size {- let mut truncated = text- .chars()- .take(self.max_response_size)- .collect::<String>();- truncated.push_str("\n\n... [Response truncated due to size limit] ...");- truncated- } else {- text.to_string()- }- }-}--#[async_trait]-impl Tool for HttpRequestTool {- fn name(&self) -> &str {- "http_request"- }-- fn description(&self) -> &str {- "Make HTTP requests to external APIs. Supports GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS methods. \- Security constraints: allowlist-only domains, no local/private hosts, configurable timeout and response size limits."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "url": {- "type": "string",- "description": "HTTP or HTTPS URL to request"- },- "method": {- "type": "string",- "description": "HTTP method (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)",- "default": "GET"- },- "headers": {- "type": "object",- "description": "Optional HTTP headers as key-value pairs (e.g., {\"Authorization\": \"Bearer token\", \"Content-Type\": \"application/json\"})",- "default": {}- },- "body": {- "type": "string",- "description": "Optional request body (for POST, PUT, PATCH requests)"- }- },- "required": ["url"]- })- }-- /// Rich HTTP semantics (methods, headers, request bodies, and x402 retry)- /// are the same Network-class risk as `curl`: read-only autonomy is blocked- /// in `execute`, and supervised/full tiers route through ApprovalGate.- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.security.gate_decision(CommandClass::Network) == GateDecision::Prompt- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let url = args- .get("url")- .and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;-- let method_str = args.get("method").and_then(|v| v.as_str()).unwrap_or("GET");- let headers_val = args.get("headers").cloned().unwrap_or(json!({}));- let body = args.get("body").and_then(|v| v.as_str());-- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: autonomy is read-only",- ));- }-- if !self.security.record_action() {- return Ok(ToolResult::error("Action blocked: rate limit exceeded"));- }-- // Local-only enforcement (privacy epic S7, #4441): mirror the read-only- // `can_act()` deny above — under LocalOnly, refuse the outbound request- // before URL validation / DNS so nothing (not even a DNS lookup for the- // host) leaves the device. The post-validation `emit_external_transfer`- // below stays the S2 disclosure point for permitted requests.- {- let host = reqwest::Url::parse(url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- if let Some(msg) = crate::security::egress::local_only_tool_block(- &crate::security::egress::EgressDescriptor::network_fetch(host),- ) {- return Ok(ToolResult::error(msg));- }- }-- let url = match self.validate_url(url).await {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e.to_string())),- };-- // Egress spine (privacy epic S2, #4436): an agent-driven HTTP request to- // an allowlisted host leaves the device — disclose the destination and- // everything that rides with it (body + custom headers) before the- // round-trip.- {- let has_headers = headers_val- .as_object()- .map(|h| !h.is_empty())- .unwrap_or(false);- crate::security::egress::emit_external_transfer(network_egress_descriptor(- &url,- body.is_some(),- has_headers,- ));- }-- let method = match self.validate_method(method_str) {- Ok(m) => m,- Err(e) => return Ok(ToolResult::error(e.to_string())),- };-- let request_headers = self.parse_headers(&headers_val);-- let response = match self- .execute_request(&url, method.clone(), request_headers.clone(), body)- .await- {- Ok(r) => r,- Err(e) => return Ok(ToolResult::error(format!("HTTP request failed: {e}"))),- };-- // x402: if the server returns 402 with a PAYMENT-REQUIRED header,- // attempt to pay using the wallet's Solana key and retry. Compiled out- // when the `web3` feature is off — a 402 then passes through unpaid.- #[cfg(feature = "web3")]- let response = if response.status() == reqwest::StatusCode::PAYMENT_REQUIRED- && (response.headers().get("PAYMENT-REQUIRED").is_some()- || response.headers().get("X-PAYMENT-REQUIRED").is_some())- {- match self- .handle_x402_payment(response, &url, method, request_headers, body)- .await- {- Ok(paid_response) => paid_response,- Err(msg) => return Ok(ToolResult::error(msg)),- }- } else {- response- };-- self.format_response(response).await- }-}--#[cfg(test)]-#[path = "http_request_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/network/http_request_tests.rs b/crates/openhuman-core/src/tools/impl/network/http_request_tests.rsdeleted file mode 100644index 5ea7870ef6..0000000000--- a/crates/openhuman-core/src/tools/impl/network/http_request_tests.rs+++ /dev/null@@ -1,283 +0,0 @@-use super::*;-use crate::security::{AutonomyLevel, SecurityPolicy};--fn test_tool(allowed_domains: Vec<&str>) -> HttpRequestTool {- let security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Supervised,- ..SecurityPolicy::default()- });- HttpRequestTool::new(- security,- allowed_domains.into_iter().map(String::from).collect(),- 1_000_000,- 30,- )-}--#[test]-fn zero_limits_fall_back_to_defaults() {- // Stale configs (or a bad write) can pass 0; a 0-second timeout fails- // every request and a 0-byte cap truncates every body. The constructor- // must coerce both to the module defaults — never let 0 reach reqwest.- let security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Supervised,- ..SecurityPolicy::default()- });- let tool = HttpRequestTool::new(security, vec!["example.com".to_string()], 0, 0);- let defaults = crate::config::HttpRequestConfig::default();- assert_eq!(tool.max_response_size, defaults.max_response_size);- assert_eq!(tool.timeout_secs, defaults.timeout_secs);- assert_ne!(tool.timeout_secs, 0);- assert_ne!(tool.max_response_size, 0);-}--#[test]-fn nonzero_limits_are_preserved() {- let security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Supervised,- ..SecurityPolicy::default()- });- let tool = HttpRequestTool::new(security, vec!["example.com".to_string()], 2048, 12);- assert_eq!(tool.max_response_size, 2048);- assert_eq!(tool.timeout_secs, 12);-}--#[test]-fn validate_accepts_valid_methods() {- let tool = test_tool(vec!["example.com"]);- assert!(tool.validate_method("GET").is_ok());- assert!(tool.validate_method("POST").is_ok());- assert!(tool.validate_method("PUT").is_ok());- assert!(tool.validate_method("DELETE").is_ok());- assert!(tool.validate_method("PATCH").is_ok());- assert!(tool.validate_method("HEAD").is_ok());- assert!(tool.validate_method("OPTIONS").is_ok());-}--#[test]-fn validate_rejects_invalid_method() {- let tool = test_tool(vec!["example.com"]);- let err = tool.validate_method("INVALID").unwrap_err().to_string();- assert!(err.contains("Unsupported HTTP method"));-}--#[tokio::test]-async fn validate_url_rejects_disallowed_domain() {- let tool = test_tool(vec!["example.com"]);- let err = tool- .validate_url("https://evil.test/path")- .await- .unwrap_err()- .to_string();- assert!(err.contains("allowed websites"));-}--#[tokio::test]-async fn execute_blocks_readonly_mode() {- let security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::ReadOnly,- ..SecurityPolicy::default()- });- let tool = HttpRequestTool::new(security, vec!["example.com".into()], 1_000_000, 30);- 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 execute_blocks_when_rate_limited() {- let security = Arc::new(SecurityPolicy {- max_actions_per_hour: 0,- ..SecurityPolicy::default()- });- let tool = HttpRequestTool::new(security, vec!["example.com".into()], 1_000_000, 30);- 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 execute_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 tool = HttpRequestTool::new(- Arc::new(SecurityPolicy::default()),- vec!["example.com".into()],- 1_000_000,- 30,- );- let result = tool- .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()- );-}--#[test]-fn truncate_response_within_limit() {- let tool = test_tool(vec!["example.com"]);- let text = "hello world";- assert_eq!(tool.truncate_response(text), "hello world");-}--#[test]-fn truncate_response_over_limit() {- let tool = HttpRequestTool::new(- Arc::new(SecurityPolicy::default()),- vec!["example.com".into()],- 10,- 30,- );- let text = "hello world this is long";- let truncated = tool.truncate_response(text);- assert!(truncated.len() <= 10 + 60);- assert!(truncated.contains("[Response truncated"));-}--#[test]-fn parse_headers_preserves_original_values() {- let tool = test_tool(vec!["example.com"]);- let headers = json!({- "Authorization": "Bearer secret",- "Content-Type": "application/json",- "X-API-Key": "my-key"- });- let parsed = tool.parse_headers(&headers);- assert_eq!(parsed.len(), 3);- assert!(parsed- .iter()- .any(|(k, v)| k == "Authorization" && v == "Bearer secret"));- assert!(parsed- .iter()- .any(|(k, v)| k == "X-API-Key" && v == "my-key"));- assert!(parsed- .iter()- .any(|(k, v)| k == "Content-Type" && v == "application/json"));-}--#[test]-fn redact_headers_for_display_redacts_sensitive() {- let headers = vec![- ("Authorization".into(), "Bearer secret".into()),- ("Content-Type".into(), "application/json".into()),- ("X-API-Key".into(), "my-key".into()),- ("X-Secret-Token".into(), "tok-123".into()),- ];- let redacted = HttpRequestTool::redact_headers_for_display(&headers);- assert_eq!(redacted.len(), 4);- assert!(redacted- .iter()- .any(|(k, v)| k == "Authorization" && v == "***REDACTED***"));- assert!(redacted- .iter()- .any(|(k, v)| k == "X-API-Key" && v == "***REDACTED***"));- assert!(redacted- .iter()- .any(|(k, v)| k == "X-Secret-Token" && v == "***REDACTED***"));- assert!(redacted- .iter()- .any(|(k, v)| k == "Content-Type" && v == "application/json"));-}--#[test]-fn redact_headers_does_not_alter_original() {- let headers = vec![("Authorization".into(), "Bearer real-token".into())];- let _ = HttpRequestTool::redact_headers_for_display(&headers);- assert_eq!(headers[0].1, "Bearer real-token");-}--#[test]-fn redirect_policy_is_none() {- let tool = test_tool(vec!["example.com"]);- assert_eq!(tool.name(), "http_request");-}--#[test]-fn supervised_http_request_is_external_effect_for_approval_gate() {- let tool = test_tool(vec!["example.com"]);- 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 security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::ReadOnly,- ..SecurityPolicy::default()- });- let tool = HttpRequestTool::new(security, vec!["example.com".into()], 1_000_000, 30);- assert!(!tool.external_effect_with_args(&json!({- "url": "https://example.com/api",- "method": "GET"- })));-}--#[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("https://api.example.com/v1/data", 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![crate::security::egress::DataKind::Url]- );-}--#[test]-fn egress_descriptor_adds_tool_arguments_for_body() {- let desc = network_egress_descriptor("https://api.example.com/v1", true, false);- assert!(desc- .data_kinds- .contains(&crate::security::egress::DataKind::ToolArguments));- assert!(!desc- .data_kinds- .contains(&crate::security::egress::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("https://api.example.com/v1", false, true);- assert!(desc- .data_kinds- .contains(&crate::security::egress::DataKind::Metadata));-}--#[test]-fn egress_descriptor_reports_both_body_and_headers() {- let desc = network_egress_descriptor("https://api.example.com/v1", true, true);- let kinds = &desc.data_kinds;- assert!(kinds.contains(&crate::security::egress::DataKind::ToolArguments));- assert!(kinds.contains(&crate::security::egress::DataKind::Metadata));-}--#[test]-fn egress_descriptor_falls_back_to_unknown_host_on_unparseable_url() {- let desc = network_egress_descriptor("not a url", false, false);- assert_eq!(desc.service, "unknown");-}diff --git a/crates/openhuman-core/src/tools/impl/network/mod.rs b/crates/openhuman-core/src/tools/impl/network/mod.rsindex c04248f1a1..9b974fdbba 100644--- a/crates/openhuman-core/src/tools/impl/network/mod.rs+++ b/crates/openhuman-core/src/tools/impl/network/mod.rs@@ -1,12 +1,15 @@-//! Network tools: HTTP request/fetch/curl, GitBooks docs lookup, Gmail-//! unsubscribe, and (under the `mcp` feature) the MCP client/setup tools.-//! `url_guard` is the shared SSRF/allowlist validator. Registration gates are-//! documented in `tools/impl/README.md`.+//! Network tools: GitBooks docs lookup, Gmail unsubscribe, and (under the+//! `mcp` feature) the MCP client/setup tools, plus the host adapter for the+//! tools that live in `tinytools_std::network` (`http_request`, `web_fetch`,+//! `curl`, `pushover`). [`gate`] implements `NetGate` for `SecurityPolicy` and+//! [`host`] supplies the limits, HTML engine and x402 payment hook those tools+//! are handed. `url_guard` (in `tinytools_std`) is the shared SSRF/allowlist+//! validator. Registration gates are documented in `tools/impl/README.md`.-mod curl;+mod gate;mod gitbooks;mod gmail_unsubscribe;-mod http_request;+mod host;// Leaf-gated: the only consumers of these two are the `#[cfg(feature = "mcp")]`// blocks in `tools/ops.rs`, so no stub is needed — nothing names them when the// feature is off. (`gitbooks` is deliberately NOT gated: it dials `McpHttpClient`@@ -16,17 +19,14 @@ mod http_request;mod mcp;#[cfg(feature = "mcp")]mod mcp_server_tools;-mod web_fetch;-pub use curl::CurlTool;pub use gitbooks::{GitbooksGetPageTool, GitbooksSearchTool};pub use gmail_unsubscribe::GmailUnsubscribeTool;-pub use http_request::HttpRequestTool;+pub use host::{http_request_tool, web_fetch_tool};#[cfg(feature = "mcp")]pub use mcp::{McpCallTool, McpListServersTool, McpListToolsTool};#[cfg(feature = "mcp")]pub use mcp_server_tools::{configured_server_tools, ConfiguredMcpServerTool};-pub use web_fetch::WebFetchTool;/// Shared test helper for the network tools' local-only enforcement tests/// (privacy epic S7, #4441). Returns a thread-scoped `LocalOnly` privacydiff --git a/crates/openhuman-core/src/tools/impl/network/web_fetch.rs b/crates/openhuman-core/src/tools/impl/network/web_fetch.rsdeleted file mode 100644index c10c27fecc..0000000000--- a/crates/openhuman-core/src/tools/impl/network/web_fetch.rs+++ /dev/null@@ -1,304 +0,0 @@-//! `web_fetch` — fetch a URL and return its text body.-//!-//! Coding-harness baseline tool (issue #1205). Distinct from-//! `http_request` (full method/header surface) and `curl` (writes to-//! disk). `web_fetch` is the single-purpose "GET and read" primitive-//! the agent reaches for when researching: returns the response body-//! as text, capped, with a tiny preamble (status + final URL).--use crate::config::HttpRequestConfig;-use crate::security::SecurityPolicy;-use async_trait::async_trait;-use serde_json::json;-use std::sync::Arc;-use std::time::Duration;-use tinytools::{PermissionLevel, Tool, ToolResult};-use tinytools_std::url_guard::{normalize_allowed_domains, validate_url_with_dns_check};--pub struct WebFetchTool {- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- max_bytes: usize,- timeout_secs: u64,-}--impl WebFetchTool {- pub fn new(- security: Arc<SecurityPolicy>,- allowed_domains: Vec<String>,- max_bytes: Option<usize>,- timeout_secs: Option<u64>,- ) -> Self {- // Treat both `None` and `Some(0)` as "use default": callers wire these- // from `[http_request]`, and a 0-byte cap truncates every body to- // nothing while a 0-second timeout fails every request instantly.- // Stale-zero configs are repaired on load (migration 5→6); this clamp- // is the always-on guard at the point of use. Pull the fallbacks from- // `HttpRequestConfig::default()` so the tool shares one source with the- // schema + migration (no cross-layer drift). `Some(0)` is a genuine- // misconfiguration, so log it (grep-friendly, no payload); a bare- // `None` is a normal "use default" call and stays quiet.- let defaults = HttpRequestConfig::default();- let max_bytes = match max_bytes {- Some(0) => {- log::warn!(- "[tool.web_fetch] coercing invalid limit field=max_bytes \- from=0 to={} (stale/invalid config — see migration 5→6)",- defaults.max_response_size- );- defaults.max_response_size- }- Some(n) => n,- None => defaults.max_response_size,- };- let timeout_secs = match timeout_secs {- Some(0) => {- log::warn!(- "[tool.web_fetch] coercing invalid limit field=timeout_secs \- from=0 to={} (stale/invalid config — see migration 5→6)",- defaults.timeout_secs- );- defaults.timeout_secs- }- Some(n) => n,- None => defaults.timeout_secs,- };- Self {- security,- allowed_domains: normalize_allowed_domains(allowed_domains),- max_bytes,- timeout_secs,- }- }-}--#[async_trait]-impl Tool for WebFetchTool {- fn name(&self) -> &str {- "web_fetch"- }-- fn description(&self) -> &str {- "GET a URL and read the page. HTML returns as Markdown (links kept, \- scripts dropped); `raw: true` for the body as sent. For POST or \- custom headers use `http_request`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "url": { "type": "string", "description": "Absolute http(s) URL." },- "max_bytes": {- "type": "integer",- "description": "Truncate body at this many bytes (default 1_000_000).",- "minimum": 1- },- "raw": {- "type": "boolean",- "description": "Return the body as sent."- },- // Opts into a caller-steered summary; see `tokenjuice::focus`.- "summary_focus": crate::inference::tokenjuice::focus::summary_focus_property()- },- "required": ["url"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- /// Idempotent GET — safe to fan out across parallel `web_fetch`- /// calls. Targets that throttle aggressively are the user's- /// concern; we don't try to second-guess at the tool layer.- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-- /// How much of a page reaches the model in one result.- ///- /// Extraction does most of the work — after HTML→Markdown a long- /// documentation page is usually a few thousand chars — so this- /// bites only on genuinely large documents. What it no longer does- /// is throw the remainder away: `ToolOutputMiddleware` spills the- /// full extracted page to an artifact and returns the `file_read`- /// call that pages it, which is what this comment used to- /// recommend while the cap itself disabled the affordance.- ///- /// 24k rather than the old 50k because the point of reference- /// moved: 50k was a bound on raw markup, this is clean Markdown.- /// Hermes budgets 15,000 chars of extracted text for the same job;- /// Codex caps every tool result at ~10,000 tokens.- fn max_result_size_chars(&self) -> Option<usize> {- Some(24_000)- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let raw_url = args- .get("url")- .and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("Missing 'url' parameter"))?;- let max_bytes = args- .get("max_bytes")- .and_then(|v| v.as_u64())- .map(|n| (n as usize).max(1))- .unwrap_or(self.max_bytes);- let raw_requested = args.get("raw").and_then(|v| v.as_bool()).unwrap_or(false);-- if self.security.is_rate_limited() {- return Ok(ToolResult::error(- "Rate limit exceeded: too many actions in the last hour",- ));- }- if !self.security.record_action() {- return Ok(ToolResult::error(- "Rate limit exceeded: action budget exhausted",- ));- }-- // Local-only enforcement (privacy epic S7, #4441): refuse the fetch under- // LocalOnly before URL validation / DNS. The post-validation- // `emit_external_transfer` below stays the S2 disclosure point.- {- let host = reqwest::Url::parse(raw_url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- if let Some(msg) = crate::security::egress::local_only_tool_block(- &crate::security::egress::EgressDescriptor::network_fetch(host),- ) {- return Ok(ToolResult::error(msg));- }- }-- let url = match validate_url_with_dns_check(raw_url, &self.allowed_domains).await {- Ok(u) => u.url,- Err(e) => return Ok(ToolResult::error(format!("URL rejected: {e}"))),- };-- // Egress spine (privacy epic S2, #4436): disclose the fetch destination- // before contacting the host.- {- let host = reqwest::Url::parse(&url)- .ok()- .and_then(|u| u.host_str().map(str::to_string))- .unwrap_or_else(|| "unknown".to_string());- crate::security::egress::emit_external_transfer(- crate::security::egress::EgressDescriptor::network_fetch(host),- );- }-- // Disable automatic redirect following: reqwest follows up to 10- // redirects by default, and a redirect target may be on a host- // outside the allowed-domains list. We surface 3xx responses to- // the caller so they can decide whether to refetch the new URL.- let client = match reqwest::Client::builder()- .timeout(Duration::from_secs(self.timeout_secs))- .redirect(reqwest::redirect::Policy::none())- .build()- {- Ok(c) => c,- Err(e) => return Ok(ToolResult::error(format!("Failed to build client: {e}"))),- };-- let resp = match client.get(&url).send().await {- Ok(r) => r,- Err(e) => return Ok(ToolResult::error(format!("Request failed: {e}"))),- };- let status = resp.status();- let final_url = resp.url().to_string();- let location = resp- .headers()- .get(reqwest::header::LOCATION)- .and_then(|v| v.to_str().ok())- .map(str::to_string);- let content_type = resp- .headers()- .get(reqwest::header::CONTENT_TYPE)- .and_then(|v| v.to_str().ok())- .map(str::to_string);- let body = match resp.text().await {- Ok(b) => b,- Err(e) => return Ok(ToolResult::error(format!("Failed to read body: {e}"))),- };-- if let Some(loc) = &location {- if status.is_redirection() {- return Ok(ToolResult::success(format!(- "status={} url={} location={loc}\n[redirect not followed — re-call web_fetch with the location URL if it's an allowed domain]",- status.as_u16(),- final_url- )));- }- }-- let downloaded = body.len();- let (body, byte_capped) = if downloaded > max_bytes {- let cut = crate::util::floor_char_boundary(&body, max_bytes);- (body[..cut].to_string(), true)- } else {- (body, false)- };-- // Markdown by default. A page's prose is a small fraction of its- // bytes; handing the raw document to the model (and to the payload- // summarizer behind it) is how one research turn came to cost- // 1,083,069 input tokens. `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.- let converted = !raw_requested && is_html(&body, content_type.as_deref());- let content = if converted {- tinyjuice::compressors::html::html_to_markdown(&body)- } else {- body- };-- let extracted = content.len();- let mut header = format!("status={} url={final_url}", status.as_u16());- if converted {- header.push_str(" content=markdown");- }- if byte_capped {- header.push_str(&format!(" download_capped_at={max_bytes}B"));- }- if converted && extracted < downloaded {- header.push_str(&format!(" extracted={extracted}B_of_{downloaded}B"));- }- header.push('\n');-- // Full extracted content. Bounding it — the head/tail window, the- // spill to an artifact and the paging handle — belongs to- // `ToolOutputMiddleware`, which applies one rule to every tool.- // Codex enforces exactly this invariant at a single chokepoint- // (`context_manager/history.rs`), which is why a tool there cannot- // leak an unbounded payload however it misbehaves.- Ok(ToolResult::success(format!("{header}{content}")))- }-}--/// Is this HTML? The server's own `Content-Type` is authoritative when it-/// says so; otherwise fall back to TinyJuice's content detection, which-/// already distinguishes HTML from JSON, diffs and code.-fn is_html(body: &str, content_type: Option<&str>) -> bool {- if let Some(ct) = content_type {- let ct = ct.to_ascii_lowercase();- let mime = ct.split(';').next().unwrap_or("").trim().to_string();- // An explicit non-HTML type is a statement, not a guess: a JSON API- // that happens to embed markup must come back verbatim.- if !mime.is_empty() && mime != "text/html" && mime != "application/xhtml+xml" {- return false;- }- if !mime.is_empty() {- return true;- }- }- matches!(- tinyjuice::detect_content_kind(body, &tinyjuice::types::ContentHint::default()),- tinyjuice::types::ContentKind::Html- )-}--#[cfg(test)]-#[path = "web_fetch_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/network/web_fetch_tests.rs b/crates/openhuman-core/src/tools/impl/network/web_fetch_tests.rsdeleted file mode 100644index 8164e79889..0000000000--- a/crates/openhuman-core/src/tools/impl/network/web_fetch_tests.rs+++ /dev/null@@ -1,179 +0,0 @@-use super::*;-use crate::security::{AutonomyLevel, SecurityPolicy};--fn test_security() -> Arc<SecurityPolicy> {- Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Supervised,- workspace_dir: std::env::temp_dir(),- ..SecurityPolicy::default()- })-}--#[test]-fn web_fetch_name_and_schema() {- let tool = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- assert_eq!(tool.name(), "web_fetch");- let schema = tool.parameters_schema();- assert!(schema["properties"]["url"].is_object());- assert!(schema["required"]- .as_array()- .unwrap()- .contains(&json!("url")));-}--#[test]-fn web_fetch_opts_into_an_optional_summary_focus() {- let tool = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- let schema = tool.parameters_schema();- let key = crate::inference::tokenjuice::focus::SUMMARY_FOCUS_ARG;- assert_eq!(schema["properties"][key]["type"], "string");- assert!(!schema["required"].as_array().unwrap().contains(&json!(key)));-}--#[test]-fn zero_and_none_limits_fall_back_to_defaults() {- // Callers wire these from `[http_request]`; a stale `Some(0)` is a- // 0-byte cap (empty bodies) and a 0-second timeout (instant failure).- // Both `None` and `Some(0)` must coerce to the shared schema defaults.- let defaults = crate::config::HttpRequestConfig::default();- let from_zero = WebFetchTool::new(- test_security(),- vec!["example.com".into()],- Some(0),- Some(0),- );- assert_eq!(from_zero.max_bytes, defaults.max_response_size);- assert_eq!(from_zero.timeout_secs, defaults.timeout_secs);- assert_ne!(from_zero.timeout_secs, 0);- assert_ne!(from_zero.max_bytes, 0);-- let from_none = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- assert_eq!(from_none.max_bytes, defaults.max_response_size);- assert_eq!(from_none.timeout_secs, defaults.timeout_secs);-}--#[test]-fn nonzero_limits_are_preserved() {- let tool = WebFetchTool::new(- test_security(),- vec!["example.com".into()],- Some(4096),- Some(15),- );- assert_eq!(tool.max_bytes, 4096);- assert_eq!(tool.timeout_secs, 15);-}--#[tokio::test]-async fn web_fetch_rejects_disallowed_domain() {- let tool = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- let result = tool- .execute(json!({ "url": "https://evil.test/path" }))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("URL rejected"));-}--#[tokio::test]-async fn web_fetch_rejects_invalid_url() {- let tool = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- let result = tool.execute(json!({ "url": "not-a-url" })).await.unwrap();- assert!(result.is_error);-}--#[tokio::test]-async fn web_fetch_blocked_under_local_only_privacy_mode() {- // Privacy epic S7 (#4441): under LocalOnly the fetch is refused with a- // `[policy-blocked]` result before any URL validation / network.- let _mode = super::super::local_only_scope();- let tool = WebFetchTool::new(test_security(), vec!["example.com".into()], None, None);- let result = tool- .execute(json!({ "url": "https://example.com/data" }))- .await- .unwrap();- assert!(result.is_error);- assert!(- result.output().contains("[policy-blocked]"),- "got: {}",- result.output()- );- assert!(- result.output().contains("Local-only"),- "got: {}",- result.output()- );-}--#[test]-fn test_web_fetch_truncation_utf8() {- // Mock body with multi-byte char exactly at budget- let body = "Hello 🦀 World"; // 🦀 is at index 6-9- let max_bytes = 8;- // Should truncate at index 6- let cut = crate::util::floor_char_boundary(body, max_bytes);- assert_eq!(cut, 6);- assert_eq!(&body[..cut], "Hello ");-}--// --- content extraction ------------------------------------------------------#[test]-fn an_explicit_html_content_type_selects_markdown_conversion() {- assert!(is_html("<p>hi</p>", Some("text/html; charset=utf-8")));- assert!(is_html("<p>hi</p>", Some("application/xhtml+xml")));-}--#[test]-fn an_explicit_non_html_content_type_is_taken_at_its_word() {- // A JSON API that happens to quote markup must come back verbatim —- // the server said what it sent, so we don't second-guess it by sniffing.- let body = r##"{"html": "<div><p>one</p><span>two</span><a href="/x">two</a></div>"}"##;- assert!(!is_html(body, Some("application/json")));- assert!(!is_html("<p>x</p>", Some("text/plain")));-}--#[test]-fn a_missing_content_type_falls_back_to_content_detection() {- assert!(is_html(- "<!DOCTYPE html><html><body><p>hi</p></body></html>",- None- ));- assert!(!is_html("# Just a README\n\nSome prose.\n", None));-}--#[test]-fn an_empty_content_type_does_not_veto_detection() {- assert!(is_html(- "<!DOCTYPE html><html><body>x</body></html>",- Some("")- ));-}--#[test]-fn the_schema_offers_the_raw_escape_hatch() {- let tool = WebFetchTool::new(Arc::new(SecurityPolicy::default()), vec![], None, None);- let schema = tool.parameters_schema();- assert!(- schema["properties"].get("raw").is_some(),- "a caller must be able to opt out of conversion: {schema}"- );- assert!(- tool.description().contains("Markdown"),- "the model needs to know what it will get back: {}",- tool.description()- );-}--#[test]-fn the_declared_cap_is_sized_for_extracted_markdown_not_raw_markup() {- let tool = WebFetchTool::new(Arc::new(SecurityPolicy::default()), vec![], None, None);- let cap = tool- .max_result_size_chars()- .expect("web_fetch declares a cap");- assert!(- (8_000..=32_000).contains(&cap),- "cap should sit in the same range as Hermes (15k chars) and Codex \- (~10k tokens) budget for one result, got {cap}"- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rsindex e0b110ec0d..783b768b28 100644--- a/crates/openhuman-core/src/tools/impl/system/mod.rs+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs@@ -10,7 +10,6 @@ mod lsp;mod node_exec;mod npm_exec;mod proxy_config;-mod pushover;mod python_exec;mod retrieve_tool_output;mod schedule;@@ -18,7 +17,6 @@ mod shell;mod tool_stats;mod update_apply;mod update_check;-mod workspace_state;use crate::security::policy::{TrustedAccess, TrustedRoot};use crate::security::SecurityPolicy;@@ -30,7 +28,6 @@ pub use lsp::{lsp_capability_enabled, LspTool, LSP_ENABLED_ENV};pub use node_exec::NodeExecTool;pub use npm_exec::NpmExecTool;pub use proxy_config::ProxyConfigTool;-pub use pushover::PushoverTool;pub use python_exec::PythonExecTool;pub use retrieve_tool_output::RetrieveToolOutputTool;pub use schedule::ScheduleTool;@@ -38,7 +35,6 @@ pub use shell::ShellTool;pub use tool_stats::ToolStatsTool;pub use update_apply::UpdateApplyTool;pub use update_check::UpdateCheckTool;-pub use workspace_state::WorkspaceStateTool;/// Clone `security` and scope it to the run's workspace descriptor, if any.///diff --git a/crates/openhuman-core/src/tools/impl/system/pushover.rs b/crates/openhuman-core/src/tools/impl/system/pushover.rsdeleted file mode 100644index 783db60777..0000000000--- a/crates/openhuman-core/src/tools/impl/system/pushover.rs+++ /dev/null@@ -1,218 +0,0 @@-use crate::security::SecurityPolicy;-use async_trait::async_trait;-use serde_json::json;-use std::path::PathBuf;-use std::sync::Arc;-use tinytools::{Tool, ToolResult};--const PUSHOVER_API_URL: &str = "https://api.pushover.net/1/messages.json";-const PUSHOVER_REQUEST_TIMEOUT_SECS: u64 = 15;--pub struct PushoverTool {- security: Arc<SecurityPolicy>,- workspace_dir: PathBuf,-}--impl PushoverTool {- pub fn new(security: Arc<SecurityPolicy>, workspace_dir: PathBuf) -> Self {- Self {- security,- workspace_dir,- }- }-- fn parse_env_value(raw: &str) -> String {- let raw = raw.trim();-- let unquoted = if raw.len() >= 2- && ((raw.starts_with('"') && raw.ends_with('"'))- || (raw.starts_with('\'') && raw.ends_with('\'')))- {- &raw[1..raw.len() - 1]- } else {- raw- };-- // Keep support for inline comments in unquoted values:- // KEY=value # comment- unquoted.split_once(" #").map_or_else(- || unquoted.trim().to_string(),- |(value, _)| value.trim().to_string(),- )- }-- async fn get_credentials(&self) -> anyhow::Result<(String, String)> {- let env_path = self.workspace_dir.join(".env");- let content = tokio::fs::read_to_string(&env_path)- .await- .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", env_path.display(), e))?;-- let mut token = None;- let mut user_key = None;-- for line in content.lines() {- let line = line.trim();- if line.starts_with('#') || line.is_empty() {- continue;- }- let line = line.strip_prefix("export ").map(str::trim).unwrap_or(line);- if let Some((key, value)) = line.split_once('=') {- let key = key.trim();- let value = Self::parse_env_value(value);-- if key.eq_ignore_ascii_case("PUSHOVER_TOKEN") {- token = Some(value);- } else if key.eq_ignore_ascii_case("PUSHOVER_USER_KEY") {- user_key = Some(value);- }- }- }-- let token = token.ok_or_else(|| anyhow::anyhow!("PUSHOVER_TOKEN not found in .env"))?;- let user_key =- user_key.ok_or_else(|| anyhow::anyhow!("PUSHOVER_USER_KEY not found in .env"))?;-- Ok((token, user_key))- }-}--#[async_trait]-impl Tool for PushoverTool {- fn name(&self) -> &str {- "pushover"- }-- fn description(&self) -> &str {- "Send a Pushover notification to your device. Requires PUSHOVER_TOKEN and PUSHOVER_USER_KEY in .env file."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "message": {- "type": "string",- "description": "The notification message to send"- },- "title": {- "type": "string",- "description": "Optional notification title"- },- "priority": {- "type": "integer",- "description": "Message priority: -2 (lowest/silent), -1 (low/no sound), 0 (normal), 1 (high), 2 (emergency/repeating)"- },- "sound": {- "type": "string",- "description": "Notification sound override (e.g., 'pushover', 'bike', 'bugle', 'cashregister', etc.)"- }- },- "required": ["message"]- })- }-- // Intentionally NOT marked external_effect=true in v1.- //- // `execute()` below already enforces local policy via- // `security.can_act()` (read-only autonomy block) and- // `security.record_action()` (rate limit). The gate runs- // BEFORE `execute()`, so flipping external_effect would prompt- // the user even for calls that the policy will immediately- // reject — a dead-end approval flow. Leaving this tool at the- // trait default (false) means the local policy stays the- // single approval surface until the gate learns to consult- // policy before parking.- //- // Follow-up #1339-v3: thread the SecurityPolicy into the gate- // pre-check so external_effect can stay true here without- // generating ghost approvals.-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: autonomy is read-only",- ));- }-- if !self.security.record_action() {- return Ok(ToolResult::error("Action blocked: rate limit exceeded"));- }-- let message = args- .get("message")- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|v| !v.is_empty())- .ok_or_else(|| anyhow::anyhow!("Missing 'message' parameter"))?- .to_string();-- let title = args.get("title").and_then(|v| v.as_str()).map(String::from);-- let priority = match args.get("priority").and_then(|v| v.as_i64()) {- Some(value) if (-2..=2).contains(&value) => Some(value),- Some(value) => {- return Ok(ToolResult::error(format!(- "Invalid 'priority': {value}. Expected integer in range -2..=2"- )))- }- None => None,- };-- let sound = args.get("sound").and_then(|v| v.as_str()).map(String::from);-- let (token, user_key) = self.get_credentials().await?;-- let mut form = reqwest::multipart::Form::new()- .text("token", token)- .text("user", user_key)- .text("message", message);-- if let Some(title) = title {- form = form.text("title", title);- }-- if let Some(priority) = priority {- form = form.text("priority", priority.to_string());- }-- if let Some(sound) = sound {- form = form.text("sound", sound);- }-- let client = crate::config::build_runtime_proxy_client_with_timeouts(- "tool.pushover",- PUSHOVER_REQUEST_TIMEOUT_SECS,- 10,- );- let response = client.post(PUSHOVER_API_URL).multipart(form).send().await?;-- let status = response.status();- let body = response.text().await.unwrap_or_default();-- if !status.is_success() {- return Ok(ToolResult::error(format!(- "Pushover API returned status {}",- status- )));- }-- let api_status = serde_json::from_str::<serde_json::Value>(&body)- .ok()- .and_then(|json| json.get("status").and_then(|value| value.as_i64()));-- if api_status == Some(1) {- Ok(ToolResult::success(format!(- "Pushover notification sent successfully. Response: {}",- body- )))- } else {- Ok(ToolResult::error(- "Pushover API returned an application-level error",- ))- }- }-}--#[cfg(test)]-#[path = "pushover_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/system/pushover_tests.rs b/crates/openhuman-core/src/tools/impl/system/pushover_tests.rsdeleted file mode 100644index f70fffc94d..0000000000--- a/crates/openhuman-core/src/tools/impl/system/pushover_tests.rs+++ /dev/null@@ -1,214 +0,0 @@-use super::*;-use crate::security::AutonomyLevel;-use std::fs;-use tempfile::TempDir;--fn test_security(level: AutonomyLevel, max_actions_per_hour: u32) -> Arc<SecurityPolicy> {- Arc::new(SecurityPolicy {- autonomy: level,- max_actions_per_hour,- workspace_dir: std::env::temp_dir(),- ..SecurityPolicy::default()- })-}--#[test]-fn pushover_tool_name() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- assert_eq!(tool.name(), "pushover");-}--#[test]-fn pushover_tool_description() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- assert!(!tool.description().is_empty());-}--#[test]-fn pushover_tool_has_parameters_schema() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- let schema = tool.parameters_schema();- assert_eq!(schema["type"], "object");- assert!(schema["properties"].get("message").is_some());-}--#[test]-fn pushover_tool_requires_message() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- let schema = tool.parameters_schema();- let required = schema["required"].as_array().unwrap();- assert!(required.contains(&serde_json::Value::String("message".to_string())));-}--#[tokio::test]-async fn credentials_parsed_from_env_file() {- let tmp = TempDir::new().unwrap();- let env_path = tmp.path().join(".env");- fs::write(- &env_path,- "PUSHOVER_TOKEN=testtoken123\nPUSHOVER_USER_KEY=userkey456\n",- )- .unwrap();-- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_ok());- let (token, user_key) = result.unwrap();- assert_eq!(token, "testtoken123");- assert_eq!(user_key, "userkey456");-}--#[tokio::test]-async fn credentials_fail_without_env_file() {- let tmp = TempDir::new().unwrap();- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_err());-}--#[tokio::test]-async fn credentials_fail_without_token() {- let tmp = TempDir::new().unwrap();- let env_path = tmp.path().join(".env");- fs::write(&env_path, "PUSHOVER_USER_KEY=userkey456\n").unwrap();-- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_err());-}--#[tokio::test]-async fn credentials_fail_without_user_key() {- let tmp = TempDir::new().unwrap();- let env_path = tmp.path().join(".env");- fs::write(&env_path, "PUSHOVER_TOKEN=testtoken123\n").unwrap();-- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_err());-}--#[tokio::test]-async fn credentials_ignore_comments() {- let tmp = TempDir::new().unwrap();- let env_path = tmp.path().join(".env");- fs::write(&env_path, "# This is a comment\nPUSHOVER_TOKEN=realtoken\n# Another comment\nPUSHOVER_USER_KEY=realuser\n").unwrap();-- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_ok());- let (token, user_key) = result.unwrap();- assert_eq!(token, "realtoken");- assert_eq!(user_key, "realuser");-}--#[test]-fn pushover_tool_supports_priority() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- let schema = tool.parameters_schema();- assert!(schema["properties"].get("priority").is_some());-}--#[test]-fn pushover_tool_supports_sound() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );- let schema = tool.parameters_schema();- assert!(schema["properties"].get("sound").is_some());-}--#[tokio::test]-async fn credentials_support_export_and_quoted_values() {- let tmp = TempDir::new().unwrap();- let env_path = tmp.path().join(".env");- fs::write(- &env_path,- "export PUSHOVER_TOKEN=\"quotedtoken\"\nPUSHOVER_USER_KEY='quoteduser'\n",- )- .unwrap();-- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- tmp.path().to_path_buf(),- );- let result = tool.get_credentials().await;-- assert!(result.is_ok());- let (token, user_key) = result.unwrap();- assert_eq!(token, "quotedtoken");- assert_eq!(user_key, "quoteduser");-}--#[tokio::test]-async fn execute_blocks_readonly_mode() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::ReadOnly, 100),- PathBuf::from("/tmp"),- );-- let result = tool.execute(json!({"message": "hello"})).await.unwrap();- assert!(result.is_error);- assert!(result.output().contains("read-only"));-}--#[tokio::test]-async fn execute_blocks_rate_limit() {- let tool = PushoverTool::new(test_security(AutonomyLevel::Full, 0), PathBuf::from("/tmp"));-- let result = tool.execute(json!({"message": "hello"})).await.unwrap();- assert!(result.is_error);- assert!(result.output().contains("rate limit"));-}--#[tokio::test]-async fn execute_rejects_priority_out_of_range() {- let tool = PushoverTool::new(- test_security(AutonomyLevel::Full, 100),- PathBuf::from("/tmp"),- );-- let result = tool- .execute(json!({"message": "hello", "priority": 5}))- .await- .unwrap();-- assert!(result.is_error);- assert!(result.output().contains("-2..=2"));-}diff --git a/crates/openhuman-core/src/tools/impl/system/workspace_state.rs b/crates/openhuman-core/src/tools/impl/system/workspace_state.rsdeleted file mode 100644index e9624bfa88..0000000000--- a/crates/openhuman-core/src/tools/impl/system/workspace_state.rs+++ /dev/null@@ -1,354 +0,0 @@-//! Tool: read_workspace_state — read-only workspace overview for Orchestrator/Planner.--use async_trait::async_trait;-use serde_json::json;-use std::path::PathBuf;-use tinytools::{PermissionLevel, Tool, ToolResult};--/// Returns a summary of the workspace: git status, file tree, recent commits.-pub struct WorkspaceStateTool {- workspace_dir: PathBuf,-}--impl WorkspaceStateTool {- pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }- }-}--#[async_trait]-impl Tool for WorkspaceStateTool {- fn name(&self) -> &str {- "read_workspace_state"- }-- fn description(&self) -> &str {- "Get a read-only overview of the workspace: git status (modified/untracked files), \- recent commits, and top-level directory structure. Useful for understanding the \- current project state before planning tasks."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "include_tree": {- "type": "boolean",- "description": "Include top-level directory tree (default: true).",- "default": true- },- "recent_commits": {- "type": "integer",- "description": "Number of recent commits to show (default: 5).",- "default": 5- }- }- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let include_tree = args- .get("include_tree")- .and_then(|v| v.as_bool())- .unwrap_or(true);- let recent_commits = args- .get("recent_commits")- .and_then(|v| v.as_u64())- .unwrap_or(5) as usize;-- tracing::debug!(- "[workspace_state] dir={}, include_tree={include_tree}, recent_commits={recent_commits}",- self.workspace_dir.display()- );-- let mut output = String::new();- let dir = &self.workspace_dir;-- // Git status- output.push_str("## Git Status\n");- match run_git(dir, &["status", "--porcelain"]).await {- Ok(status) if status.trim().is_empty() => {- output.push_str("Clean working tree.\n");- }- Ok(status) => {- output.push_str(&status);- }- Err(e) => {- output.push_str(&format!("(not a git repo or error: {e})\n"));- }- }-- // Recent commits- output.push_str(&format!("\n## Recent Commits (last {recent_commits})\n"));- let log_arg = format!("-{recent_commits}");- match run_git(dir, &["log", &log_arg, "--oneline", "--no-decorate"]).await {- Ok(log) => output.push_str(&log),- Err(e) => output.push_str(&format!("(error: {e})\n")),- }-- // Directory tree (top-level only)- if include_tree {- output.push_str("\n## Directory Tree (top-level)\n");- match tokio::fs::read_dir(dir).await {- Ok(mut entries) => {- let mut names = Vec::new();- while let Ok(Some(entry)) = entries.next_entry().await {- let name = entry.file_name().to_string_lossy().to_string();- if !name.starts_with('.') {- let suffix = if entry- .file_type()- .await- .map(|ft| ft.is_dir())- .unwrap_or(false)- {- "/"- } else {- ""- };- names.push(format!("{name}{suffix}"));- }- }- names.sort();- for name in &names {- output.push_str(&format!(" {name}\n"));- }- }- Err(e) => output.push_str(&format!("(error reading dir: {e})\n")),- }- }-- tracing::debug!("[workspace_state] output length={}", output.len());- Ok(ToolResult::success(output))- }-}--/// Repository config keys this tool will run `git` under.-///-/// **This is an allowlist, and the direction is the whole point.** Several git-/// config keys name a command that git then executes — `core.fsmonitor` is run-/// by `git status`, `core.sshCommand` by anything that reaches a remote,-/// `diff.external` by a diff, `core.pager` and `core.editor` by the commands-/// that use them, and the `filter.*.process` / `*.clean` / `*.smudge` and-/// `diff.*.textconv` families by content operations. Enumerating *those* and-/// clearing them is the obvious fix and it is the wrong shape: the list is only-/// correct until git adds a key, and a denylist that has gone stale reads as-/// protection while providing none.-///-/// An allowlist ages the other way. A key nobody here has heard of is refused,-/// so a new git release makes this tool fail closed and loud rather than-/// silently regain the hole.-///-/// The entries are `section.key`, lowercased, with any subsection elided —-/// `remote.origin.url` is checked as `remote.url`. That is what git's own-/// `--list` output normalises to for our purposes, and it means a repository-/// with fifty remotes needs no extra entries.-const ALLOWED_REPO_CONFIG: &[&str] = &[- // What `git init` and `git clone` write, and nothing else.- "core.repositoryformatversion",- "core.filemode",- "core.bare",- "core.logallrefupdates",- "core.ignorecase",- "core.precomposeunicode",- "core.symlinks",- "core.worktree",- "remote.url",- "remote.fetch",- "remote.pushurl",- "remote.mirror",- "branch.remote",- "branch.merge",- "branch.rebase",- "submodule.active",- "submodule.url",- "user.name",- "user.email",- "pull.rebase",- "push.default",- "init.defaultbranch",- // Inert settings ordinary repositories carry that the first draft refused,- // making the tool useless on a large class of real workspaces. Each is a- // value git *interprets*; none names a program git runs.- "core.autocrlf",- "core.eol",- "core.untrackedcache",- "core.longpaths",- "core.fscache",- "core.hidedotfiles",- "core.sparsecheckout",- "core.sparsecheckoutcone",- "commit.gpgsign",- "tag.gpgsign",- "remote.tagopt",- "remote.prune",- "remote.partialclonefilter",- "remote.promisor",- "branch.vscodemerge",- "gc.auto",- "fetch.prune",- // SHA-256 repositories and worktree-scoped config. Only these two- // `extensions.*` keys — the namespace as a whole is where git puts- // repository-format switches, and a blanket allow would admit whatever it- // adds next.- "extensions.objectformat",- "extensions.worktreeconfig",- // `filter.<driver>.required` is a boolean. The driver's actual programs —- // `clean`, `smudge`, `process` — are NOT here and must not be; see the LFS- // note on `NEUTRALISED_CONFIG`.- "filter.required",- "lfs.repositoryformatversion",-];--/// Command-valued keys cleared on the command line as a second layer.-///-/// Command-line `-c` outranks every config file, so this genuinely neutralises-/// these keys even when a repository sets them. It is a denylist and therefore-/// cannot be the guarantee — [`ALLOWED_REPO_CONFIG`] is — but it costs nothing-/// and it means a key that slips past the allowlist check still does not run.-/// `core.hooksPath` is deliberately absent: there is no portable value that-/// means "nowhere", and `git status` / `git log` run no hooks anyway. An-/// unrecognised `core.hookspath` is refused by [`ALLOWED_REPO_CONFIG`], which-/// is the layer that is supposed to catch it.-///-/// ## Two keys that look inert and are not-///-/// **`credential.helper` is command-valued.** A value beginning `!` is run as a-/// shell command, so it belongs nowhere near [`ALLOWED_REPO_CONFIG`] despite-/// reading like a mere preference. It is refused, and a repository that sets it-/// gets the refusal.-///-/// **A `git lfs install` clone is refused, deliberately.** `filter.lfs.clean`,-/// `.smudge` and `.process` each name a program, so an LFS working copy cannot-/// be read by this tool. That is the fail-closed answer and it is the intended-/// one — the alternative is running whatever a `.git/config` in an-/// agent-writable directory nominates as a filter driver. Only-/// `filter.<driver>.required`, a boolean, is allowed.-const NEUTRALISED_CONFIG: &[&str] = &[- "core.fsmonitor=",- "core.sshCommand=",- "core.pager=cat",- "core.editor=false",- "diff.external=",- "sequence.editor=false",- "uploadpack.packObjectsHook=",-];--/// A path git will read as an empty config file.-///-/// `GIT_CONFIG_GLOBAL` must name something readable-and-empty rather than be-/// unset — unsetting it lets git fall back to `~/.gitconfig`, which is the-/// thing being suppressed. `/dev/null` is not a path on Windows; `NUL` is.-const NULL_CONFIG_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };--/// Build a `git` invocation with the ambient environment taken away.-///-/// `GIT_CONFIG_NOSYSTEM` and `GIT_CONFIG_GLOBAL` close the system and global-/// config files. Note what they do *not* close: the repository's own-/// `.git/config`, which is the file an agent-writable workspace actually lets-/// an attacker author. That one is handled by [`repo_config_is_inert`]; these-/// two are here because they are free and they close two real vectors.-fn hardened_git(dir: &std::path::Path) -> tokio::process::Command {- let mut cmd = tokio::process::Command::new("git");- cmd.env("GIT_CONFIG_NOSYSTEM", "1")- .env("GIT_CONFIG_GLOBAL", NULL_CONFIG_PATH)- // `git` consults these before it reads any config file.- .env_remove("GIT_EXTERNAL_DIFF")- .env_remove("GIT_PAGER")- .env_remove("GIT_EDITOR")- .env_remove("GIT_SSH")- .env_remove("GIT_SSH_COMMAND")- .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")- .env("GIT_TERMINAL_PROMPT", "0")- .current_dir(dir);- for kv in NEUTRALISED_CONFIG {- cmd.arg("-c").arg(kv);- }- cmd-}--/// Normalise a `git config --list` key to the `section.key` form-/// [`ALLOWED_REPO_CONFIG`] uses, dropping any subsection.-///-/// `remote.origin.url` → `remote.url`; `core.filemode` → `core.filemode`. A-/// subsection may itself contain dots (`includeIf.gitdir:~/x.y/.path`), so the-/// first and last components are the reliable ones.-fn normalise_config_key(key: &str) -> String {- let key = key.to_ascii_lowercase();- match (key.find('.'), key.rfind('.')) {- (Some(first), Some(last)) if first != last => {- format!("{}.{}", &key[..first], &key[last + 1..])- }- _ => key,- }-}--/// Is the repository at `dir` configured only in ways that cannot make `git`-/// run something?-///-/// Returns the offending key when it is not. Reading the config is itself done-/// through [`hardened_git`], and `git config --list` neither consults-/// `core.fsmonitor` nor spawns a pager when its output is captured, so this-/// inspection step does not have the property it is checking for.-async fn repo_config_is_inert(dir: &std::path::Path) -> anyhow::Result<Option<String>> {- let output = hardened_git(dir)- .args(["config", "--list", "--local", "--null"])- .output()- .await?;-- // A directory that is not a repository has no local config to distrust.- // `git status` will report that in its own words a moment later.- if !output.status.success() {- return Ok(None);- }-- let listing = String::from_utf8_lossy(&output.stdout);- for entry in listing.split('\0').filter(|e| !e.is_empty()) {- // `--null` separates entries with NUL and key from value with LF.- let key = entry.split('\n').next().unwrap_or(entry);- if !ALLOWED_REPO_CONFIG.contains(&normalise_config_key(key).as_str()) {- return Ok(Some(key.to_string()));- }- }- Ok(None)-}--async fn run_git(dir: &std::path::Path, args: &[&str]) -> anyhow::Result<String> {- if let Some(key) = repo_config_is_inert(dir).await? {- // The refusal is otherwise only visible folded into the tool's own- // output, which is not greppable when an operator is asking why a- // workspace stopped reporting. Correlation fields: the directory and- // the key that caused it.- tracing::debug!(- "[workspace_state] refusing to run git: dir={}, disallowed_config_key={key}",- dir.display()- );- anyhow::bail!(- "refusing to run git in {}: its repository config sets `{key}`, which is \- not on the allowlist of configuration this tool will run under. \- Several git config keys name a command git then executes, and this \- directory is agent-writable, so unrecognised configuration is treated \- as untrusted rather than honoured.",- dir.display()- )- }-- let output = hardened_git(dir).args(args).output().await?;-- if output.status.success() {- Ok(String::from_utf8_lossy(&output.stdout).to_string())- } else {- anyhow::bail!(- "git {} failed: {}",- args.join(" "),- String::from_utf8_lossy(&output.stderr)- )- }-}--#[cfg(test)]-#[path = "workspace_state_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/system/workspace_state_tests.rs b/crates/openhuman-core/src/tools/impl/system/workspace_state_tests.rsdeleted file mode 100644index 53f3c408f4..0000000000--- a/crates/openhuman-core/src/tools/impl/system/workspace_state_tests.rs+++ /dev/null@@ -1,251 +0,0 @@-use super::*;-use serde_json::json;-use tempfile::TempDir;--fn make_tool(dir: &TempDir) -> WorkspaceStateTool {- WorkspaceStateTool::new(dir.path().to_path_buf())-}--#[test]-fn name_is_correct() {- let tmp = TempDir::new().unwrap();- assert_eq!(make_tool(&tmp).name(), "read_workspace_state");-}--#[test]-fn description_is_non_empty() {- let tmp = TempDir::new().unwrap();- assert!(!make_tool(&tmp).description().is_empty());-}--#[test]-fn schema_is_object_type() {- let tmp = TempDir::new().unwrap();- let schema = make_tool(&tmp).parameters_schema();- assert_eq!(schema["type"], "object");-}--#[test]-fn permission_level_is_read_only() {- let tmp = TempDir::new().unwrap();- assert_eq!(- make_tool(&tmp).permission_level(),- PermissionLevel::ReadOnly- );-}--#[tokio::test]-async fn output_contains_git_status_section() {- let tmp = TempDir::new().unwrap();- let result = make_tool(&tmp).execute(json!({})).await.unwrap();- assert!(!result.is_error);- assert!(result.output().contains("Git Status"));-}--#[tokio::test]-async fn include_tree_false_omits_directory_tree() {- let tmp = TempDir::new().unwrap();- let result = make_tool(&tmp)- .execute(json!({"include_tree": false}))- .await- .unwrap();- assert!(!result.is_error);- assert!(!result.output().contains("Directory Tree"));-}--/// Write a `core.fsmonitor` hook into `dir`'s repository config that-/// creates a marker file when git runs it, and return the marker's path.-///-/// `git status` invokes `core.fsmonitor`, and the value is read from the-/// repository's own `.git/config` — a file inside the workspace, which is-/// where `file_write` puts things. The hook exits non-zero so git falls-/// back to a normal scan and `status` still succeeds; the point of the test-/// is whether the command ran at all, not what it returned.-fn plant_fsmonitor_hook(dir: &TempDir) -> std::path::PathBuf {- let hook = dir.path().join("hook.sh");- let marker = dir.path().join("COMMAND_RAN");- std::fs::write(- &hook,- format!("#!/bin/sh\ntouch {:?}\nexit 1\n", marker.to_string_lossy()),- )- .unwrap();- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();- }- // Written with `git config` rather than by appending to the file:- // appending only lands in `[core]` while `[core]` happens to be the- // last section, which is true of a fresh `git init` and is not a- // property worth depending on.- let ok = std::process::Command::new("git")- .args(["config", "core.fsmonitor"])- .arg(&hook)- .current_dir(dir.path())- .status()- .unwrap()- .success();- assert!(ok, "failed to plant the hook in the repository config");- marker-}--fn git_init(dir: &TempDir) {- // `.status().unwrap()` only unwraps the *spawn*: a non-zero exit would- // pass silently here and surface later as a confusing assertion about- // status output. Match `plant_fsmonitor_hook`, which already checks.- let ok = std::process::Command::new("git")- .args(["init", "-q", "."])- .current_dir(dir.path())- .status()- .unwrap()- .success();- assert!(ok, "git init failed in the test workspace");-}--/// Set a repository config key with `git config`, asserting it took.-fn set_config(dir: &TempDir, key: &str, value: &str) {- let ok = std::process::Command::new("git")- .args(["config", key, value])- .current_dir(dir.path())- .status()- .unwrap()- .success();- assert!(ok, "failed to set {key} in the test workspace");-}--/// Issue #459. The workspace this tool reads is the same directory the-/// agent's own file tools write to, so its `.git/config` is attacker--/// controlled input. `core.fsmonitor` names a command that `git status`-/// executes.-///-/// Revert either layer of the fix in `run_git` and this test fails by-/// finding the marker — verified, not assumed.-#[cfg(unix)]-#[tokio::test]-async fn repository_config_naming_a_command_does_not_get_to_run_it() {- let tmp = TempDir::new().unwrap();- git_init(&tmp);- let marker = plant_fsmonitor_hook(&tmp);-- let result = make_tool(&tmp).execute(json!({})).await.unwrap();-- assert!(- !marker.exists(),- "`git status` executed the command named by the workspace's own \- repository config — this tool is a code-execution primitive"- );- assert!(- result.output().contains("fsmonitor"),- "the refusal should name the key that caused it, got: {}",- result.output()- );-}--/// The allowlist has to leave an ordinary repository working, or the fix is-/// just a different way of breaking the tool.-#[cfg(unix)]-#[tokio::test]-async fn an_ordinary_repository_still_reports_status_and_log() {- let tmp = TempDir::new().unwrap();- git_init(&tmp);- std::fs::write(tmp.path().join("tracked.txt"), "hi").unwrap();-- let result = make_tool(&tmp).execute(json!({})).await.unwrap();- let out = result.output();-- assert!(- out.contains("tracked.txt"),- "a plain `git init` workspace must still report status, got: {out}"- );- assert!(- !out.contains("not on the allowlist"),- "`git init`'s own config must not trip the allowlist, got: {out}"- );-}--/// The first draft of the allowlist refused any repository carrying an-/// ordinary setting like `core.autocrlf`, which is most of them on Windows-/// and many elsewhere — the tool would have reported nothing useful for a-/// large class of real workspaces. Raised by CodeRabbit on the PR.-#[cfg(unix)]-#[tokio::test]-async fn an_inert_setting_an_ordinary_repository_carries_is_allowed() {- let tmp = TempDir::new().unwrap();- git_init(&tmp);- set_config(&tmp, "core.autocrlf", "input");- set_config(&tmp, "gc.auto", "0");- set_config(&tmp, "remote.origin.prune", "true");- std::fs::write(tmp.path().join("tracked.txt"), "hi").unwrap();-- let out = make_tool(&tmp).execute(json!({})).await.unwrap().output();-- assert!(- out.contains("tracked.txt"),- "an ordinary repository must still report status, got: {out}"- );- assert!(!out.contains("not on the allowlist"), "got: {out}");-}--/// The other half of the same question, and the answer is the opposite one.-/// `filter.lfs.clean` names a program, so an LFS working copy is refused —-/// fail-closed, and **intended** rather than an oversight. Pinned so that-/// widening the allowlist for ergonomics cannot quietly admit it.-#[cfg(unix)]-#[tokio::test]-async fn an_lfs_clone_is_refused_because_its_filter_names_a_program() {- let tmp = TempDir::new().unwrap();- git_init(&tmp);- // What `git lfs install` writes. `required` is inert and allowed; the- // three programs are not.- set_config(&tmp, "filter.lfs.required", "true");- set_config(&tmp, "filter.lfs.clean", "git-lfs clean -- %f");-- let out = make_tool(&tmp).execute(json!({})).await.unwrap().output();-- assert!(- out.contains("filter.lfs.clean"),- "the refusal must name the key that caused it, got: {out}"- );-}--/// `credential.helper` reads like a preference and is command-valued: a-/// value beginning `!` is run as a shell command. CodeRabbit's review-/// listed it among the inert keys to allow; it is not one, and allowlisting-/// it would have reopened the hole this PR closes.-#[cfg(unix)]-#[tokio::test]-async fn credential_helper_is_refused_despite_looking_like_a_preference() {- let tmp = TempDir::new().unwrap();- git_init(&tmp);- set_config(&tmp, "credential.helper", "!echo pwned");-- let out = make_tool(&tmp).execute(json!({})).await.unwrap().output();-- assert!(- out.contains("credential.helper"),- "a command-valued key must be refused however inert it reads, got: {out}"- );-}--#[test]-fn a_subsection_is_elided_so_one_entry_covers_every_remote() {- assert_eq!(normalise_config_key("remote.origin.url"), "remote.url");- assert_eq!(normalise_config_key("remote.a.b.c.url"), "remote.url");- assert_eq!(normalise_config_key("core.fileMode"), "core.filemode");- assert_eq!(normalise_config_key("core.fsmonitor"), "core.fsmonitor");-}--#[tokio::test]-async fn lists_non_hidden_files_in_tree() {- let tmp = TempDir::new().unwrap();- std::fs::write(tmp.path().join("readme.txt"), "hi").unwrap();- std::fs::write(tmp.path().join(".hidden"), "skip").unwrap();- let result = make_tool(&tmp)- .execute(json!({"include_tree": true, "recent_commits": 0}))- .await- .unwrap();- assert!(!result.is_error);- let out = result.output();- assert!(out.contains("readme.txt"));- assert!(!out.contains(".hidden"));-}diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex 85be1dba19..ea42190ee3 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -17,6 +17,8 @@ use tinytools_std::filesystem::{GlobTool, GrepTool, ListFilesTool, ReadDiffTool, RunLinterTool, RunTestsTool,UpdateMemoryMdTool,};+use tinytools_std::filesystem::{ImageInfoTool, WorkspaceStateTool};+use tinytools_std::network::{CurlTool, PushoverTool};pub(crate) use super::capability::tool_capability;@@ -710,7 +712,7 @@ pub fn all_tools_with_runtime(// + `security` still gate which hosts are reachable; there is no// enable flag because every session needs basic HTTP as a baseline// capability.- tools.push(Box::new(HttpRequestTool::new(+ tools.push(Box::new(http_request_tool(security.clone(),http_config.allowed_domains.clone(),http_config.max_response_size,@@ -728,7 +730,7 @@ pub fn all_tools_with_runtime(// GET-and-read primitive that reuses the same allowed-domains gate// as `http_request`. Use this for docs/READMEs; reach for// `http_request` only when you need richer HTTP semantics.- tools.push(Box::new(WebFetchTool::new(+ tools.push(Box::new(web_fetch_tool(security.clone(),http_config.allowed_domains.clone(),Some(http_config.max_response_size),