Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: remove unused files and consolidate test modules

Steven Enamakel62949439730c
diff --git a/crates/openhuman-core/src/agent/file_state/agent_context.rs b/crates/openhuman-core/src/agent/file_state/agent_context.rs
deleted file mode 100644
index 8c3eb314e6..0000000000
--- a/crates/openhuman-core/src/agent/file_state/agent_context.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-//! Task-local carrier for the currently-executing agent's identity so
-//! file tools can attribute reads/writes without widening the `Tool` trait.
-//!
-//! Follows the same pattern as `sandbox_context.rs`. Set by the agent
-//! harness around tool execution; tools read via [`current_file_state_agent_id`].
-
-tokio::task_local! {
- static FILE_STATE_AGENT_ID: String;
-}
-
-/// Returns the current agent's identity for file-state tracking, if set.
-///
-/// Returns `None` outside an agent turn (CLI, JSON-RPC direct, unit tests).
-pub fn current_file_state_agent_id() -> Option<String> {
- FILE_STATE_AGENT_ID.try_with(|id| id.clone()).ok()
-}
-
-/// Run `future` with `agent_id` installed as the file-state identity.
-pub async fn with_file_state_agent_id<F, R>(agent_id: String, future: F) -> R
-where
- F: std::future::Future<Output = R>,
-{
- FILE_STATE_AGENT_ID.scope(agent_id, future).await
-}
-
-#[cfg(test)]
-#[path = "agent_context_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/file_state/agent_context_tests.rs b/crates/openhuman-core/src/agent/file_state/agent_context_tests.rs
deleted file mode 100644
index e50aeab469..0000000000
--- a/crates/openhuman-core/src/agent/file_state/agent_context_tests.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn returns_none_outside_scope() {
- assert_eq!(current_file_state_agent_id(), None);
-}
-
-#[tokio::test]
-async fn installs_and_reads_agent_id() {
- let observed =
- with_file_state_agent_id("agent-1".into(), async { current_file_state_agent_id() }).await;
- assert_eq!(observed, Some("agent-1".to_string()));
-}
-
-#[tokio::test]
-async fn does_not_leak_across_scopes() {
- with_file_state_agent_id("agent-1".into(), async {
- assert_eq!(current_file_state_agent_id(), Some("agent-1".to_string()));
- })
- .await;
- assert_eq!(current_file_state_agent_id(), None);
-}
-
-#[tokio::test]
-async fn nested_scope_overrides_outer() {
- with_file_state_agent_id("parent".into(), async {
- assert_eq!(current_file_state_agent_id(), Some("parent".to_string()));
- with_file_state_agent_id("child".into(), async {
- assert_eq!(current_file_state_agent_id(), Some("child".to_string()));
- })
- .await;
- assert_eq!(current_file_state_agent_id(), Some("parent".to_string()));
- })
- .await;
-}
diff --git a/crates/openhuman-core/src/agent/file_state/mod.rs b/crates/openhuman-core/src/agent/file_state/mod.rs
index b069a4eae4..6fa7bbe58a 100644
--- a/crates/openhuman-core/src/agent/file_state/mod.rs
+++ b/crates/openhuman-core/src/agent/file_state/mod.rs
@@ -1,21 +1,27 @@
//! Process-wide file state coordinator for cross-agent staleness detection.
//!
-//! Parallel subagents and worker threads share a workspace. Without
-//! coordination one worker can read a file, a sibling can edit it, and
-//! the first worker can later write based on stale content. This module
-//! tracks per-agent read stamps and per-path write stamps so that write
-//! tools can detect the conflict and return a model-facing error
-//! requiring the agent to re-read.
-//!
-//! Disable with `OPENHUMAN_FILE_STATE_GUARD=0` (or `false`).
-
-mod agent_context;
-mod ops;
-mod types;
+//! The mechanism lives in [`tinytools_std::file_state`]; this module keeps only
+//! the host decision of whether the guard is on. Disable with
+//! `OPENHUMAN_FILE_STATE_GUARD=0` (or `false`, `off`, `no`).
-pub use agent_context::{current_file_state_agent_id, with_file_state_agent_id};
-pub use ops::{
- acquire_path_lock, check_partial_read, check_stale_read, init_global, parent_stale_files,
- record_read, record_write, try_global,
+pub use tinytools_std::file_state::{
+ acquire_path_lock, check_partial_read, check_stale_read, current_file_state_agent_id,
+ parent_stale_files, record_read, record_write, try_global, with_file_state_agent_id,
+ FileStateCoordinator, ReadStamp,
};
-pub use types::{FileStateCoordinator, ReadStamp};
+
+/// Whether `OPENHUMAN_FILE_STATE_GUARD` disables the guard.
+fn guard_enabled() -> bool {
+ !std::env::var("OPENHUMAN_FILE_STATE_GUARD")
+ .map(|v| matches!(v.as_str(), "0" | "false" | "off" | "no"))
+ .unwrap_or(false)
+}
+
+/// Initialise the process-global coordinator unless the environment disables it.
+pub fn init_global() {
+ let enabled = guard_enabled();
+ if !enabled {
+ log::debug!("[file_state] guard disabled via OPENHUMAN_FILE_STATE_GUARD");
+ }
+ tinytools_std::file_state::init_global(enabled);
+}
diff --git a/crates/openhuman-core/src/agent/file_state/ops.rs b/crates/openhuman-core/src/agent/file_state/ops.rs
deleted file mode 100644
index 85daeb44c6..0000000000
--- a/crates/openhuman-core/src/agent/file_state/ops.rs
+++ /dev/null
@@ -1,181 +0,0 @@
-//! Operational API for the file state coordinator.
-
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, OnceLock};
-use std::time::{Instant, SystemTime};
-use tokio::sync::{Mutex, OwnedMutexGuard};
-
-use super::types::{FileStateCoordinator, ReadStamp, WriteStamp};
-
-// ── Singleton ────────────────────────────────────────────────────────────
-
-static GLOBAL: OnceLock<Arc<FileStateCoordinator>> = OnceLock::new();
-
-/// Returns `true` when the guard is disabled via env var.
-fn is_disabled() -> bool {
- static DISABLED: OnceLock<bool> = OnceLock::new();
- *DISABLED.get_or_init(|| {
- std::env::var("OPENHUMAN_FILE_STATE_GUARD")
- .map(|v| matches!(v.as_str(), "0" | "false" | "off" | "no"))
- .unwrap_or(false)
- })
-}
-
-/// Initialise the process-global coordinator. Safe to call multiple times;
-/// only the first call wins.
-pub fn init_global() {
- if is_disabled() {
- tracing::debug!("[file_state] guard disabled via OPENHUMAN_FILE_STATE_GUARD");
- return;
- }
- let _ = GLOBAL.set(Arc::new(FileStateCoordinator::new()));
- tracing::debug!("[file_state] coordinator initialised");
-}
-
-/// Returns the global coordinator, or `None` when disabled / not yet initialised.
-pub fn try_global() -> Option<Arc<FileStateCoordinator>> {
- if is_disabled() {
- return None;
- }
- GLOBAL.get().cloned()
-}
-
-// ── Read tracking ────────────────────────────────────────────────────────
-
-/// Record that `agent_id` read `resolved_path` at the given mtime.
-pub fn record_read(agent_id: &str, resolved_path: PathBuf, mtime: SystemTime, partial: bool) {
- let Some(coord) = try_global() else { return };
- tracing::trace!(
- agent = agent_id,
- path = %resolved_path.display(),
- partial,
- "[file_state] record_read"
- );
- coord.reads.write().insert(
- (agent_id.to_string(), resolved_path),
- ReadStamp {
- mtime,
- timestamp: Instant::now(),
- partial,
- },
- );
-}
-
-// ── Write tracking ───────────────────────────────────────────────────────
-
-/// Record that `agent_id` wrote `resolved_path`.
-pub fn record_write(agent_id: &str, resolved_path: PathBuf) {
- let Some(coord) = try_global() else { return };
- tracing::trace!(
- agent = agent_id,
- path = %resolved_path.display(),
- "[file_state] record_write"
- );
- let now = Instant::now();
- coord.writes.write().insert(
- resolved_path.clone(),
- WriteStamp {
- writer: agent_id.to_string(),
- timestamp: now,
- },
- );
- // Also update this agent's own read stamp so its own subsequent
- // writes don't trigger self-staleness.
- coord.reads.write().insert(
- (agent_id.to_string(), resolved_path),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: now,
- partial: false,
- },
- );
-}
-
-// ── Staleness checks ─────────────────────────────────────────────────────
-
-/// Check whether `agent_id`'s view of `resolved_path` is stale because
-/// another agent wrote to it after this agent's last read. Returns an
-/// error message when stale, `None` when safe.
-pub fn check_stale_read(agent_id: &str, resolved_path: &PathBuf) -> Option<String> {
- let coord = try_global()?;
- let reads = coord.reads.read();
- let writes = coord.writes.read();
- let read_key = (agent_id.to_string(), resolved_path.clone());
- let read_stamp = reads.get(&read_key)?;
- let ws = writes.get(resolved_path)?;
- if ws.writer != agent_id && ws.timestamp > read_stamp.timestamp {
- let display_path = resolved_path.display();
- Some(format!(
- "Stale read: file '{display_path}' was modified by agent '{}' after your last read. \
- Re-read the file before editing.",
- ws.writer
- ))
- } else {
- None
- }
-}
-
-/// Check whether `agent_id`'s last read of `resolved_path` was partial.
-/// Returns an error message when partial, `None` when safe.
-pub fn check_partial_read(agent_id: &str, resolved_path: &Path) -> Option<String> {
- let coord = try_global()?;
- let reads = coord.reads.read();
- let read_key = (agent_id.to_string(), resolved_path.to_path_buf());
- let read_stamp = reads.get(&read_key)?;
- if read_stamp.partial {
- let display_path = resolved_path.display();
- Some(format!(
- "Partial read: your last read of '{display_path}' was partial (paginated). \
- Perform a full read before overwriting."
- ))
- } else {
- None
- }
-}
-
-// ── Path locking ─────────────────────────────────────────────────────────
-
-/// Acquire an async lock on `resolved_path` for a read-modify-write
-/// section. Returns an `OwnedMutexGuard` that releases when dropped.
-/// Returns `None` when the coordinator is disabled.
-pub async fn acquire_path_lock(resolved_path: &Path) -> Option<OwnedMutexGuard<()>> {
- let coord = try_global()?;
- let mutex = {
- let mut locks = coord.path_locks.write();
- locks
- .entry(resolved_path.to_path_buf())
- .or_insert_with(|| Arc::new(Mutex::new(())))
- .clone()
- };
- Some(mutex.lock_owned().await)
-}
-
-// ── Parent reminder ──────────────────────────────────────────────────────
-
-/// Return resolved paths that `parent_agent_id` had previously read but
-/// were subsequently written by any agent in `child_agent_ids`.
-pub fn parent_stale_files(parent_agent_id: &str, child_agent_ids: &[String]) -> Vec<PathBuf> {
- let Some(coord) = try_global() else {
- return Vec::new();
- };
- let reads = coord.reads.read();
- let writes = coord.writes.read();
- let mut stale = Vec::new();
- for ((agent_id, path), read_stamp) in reads.iter() {
- if agent_id != parent_agent_id {
- continue;
- }
- if let Some(ws) = writes.get(path) {
- if child_agent_ids.contains(&ws.writer) && ws.timestamp > read_stamp.timestamp {
- stale.push(path.clone());
- }
- }
- }
- stale.sort();
- stale.dedup();
- stale
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/file_state/ops_tests.rs b/crates/openhuman-core/src/agent/file_state/ops_tests.rs
deleted file mode 100644
index 726ace6938..0000000000
--- a/crates/openhuman-core/src/agent/file_state/ops_tests.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-use super::*;
-use std::time::Duration;
-
-fn fresh_coordinator() -> Arc<FileStateCoordinator> {
- Arc::new(FileStateCoordinator::new())
-}
-
-#[test]
-fn record_and_check_no_staleness() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/a.txt");
- coord.reads.write().insert(
- ("agent-a".to_string(), path.clone()),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: Instant::now(),
- partial: false,
- },
- );
- let reads = coord.reads.read();
- let rs = reads.get(&("agent-a".to_string(), path.clone())).unwrap();
- assert!(!rs.partial);
- assert!(coord.writes.read().get(&path).is_none());
-}
-
-#[test]
-fn detect_sibling_write_staleness() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/b.txt");
- let read_time = Instant::now();
- coord.reads.write().insert(
- ("agent-a".to_string(), path.clone()),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: read_time,
- partial: false,
- },
- );
- std::thread::sleep(Duration::from_millis(5));
- coord.writes.write().insert(
- path.clone(),
- WriteStamp {
- writer: "agent-b".to_string(),
- timestamp: Instant::now(),
- },
- );
- let stale = coord.stale_reads_for_parent("agent-a");
- assert_eq!(stale, vec![path]);
-}
-
-#[test]
-fn own_write_does_not_trigger_staleness() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/c.txt");
- let now = Instant::now();
- coord.reads.write().insert(
- ("agent-a".to_string(), path.clone()),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: now,
- partial: false,
- },
- );
- std::thread::sleep(Duration::from_millis(5));
- coord.writes.write().insert(
- path.clone(),
- WriteStamp {
- writer: "agent-a".to_string(),
- timestamp: Instant::now(),
- },
- );
- let stale = coord.stale_reads_for_parent("agent-a");
- assert!(stale.is_empty());
-}
-
-#[test]
-fn partial_read_detected() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/d.txt");
- coord.reads.write().insert(
- ("agent-a".to_string(), path.clone()),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: Instant::now(),
- partial: true,
- },
- );
- let reads = coord.reads.read();
- let rs = reads.get(&("agent-a".to_string(), path.clone())).unwrap();
- assert!(rs.partial);
-}
-
-#[test]
-fn parent_stale_files_detects_child_writes() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/e.txt");
- let parent_read_time = Instant::now();
- coord.reads.write().insert(
- ("parent".to_string(), path.clone()),
- ReadStamp {
- mtime: SystemTime::now(),
- timestamp: parent_read_time,
- partial: false,
- },
- );
- std::thread::sleep(Duration::from_millis(5));
- coord.writes.write().insert(
- path.clone(),
- WriteStamp {
- writer: "child-1".to_string(),
- timestamp: Instant::now(),
- },
- );
- let stale = coord.stale_reads_for_parent("parent");
- assert_eq!(stale, vec![path]);
-}
-
-#[test]
-fn paths_written_by_collects_correctly() {
- let coord = fresh_coordinator();
- let p1 = PathBuf::from("/tmp/test/f1.txt");
- let p2 = PathBuf::from("/tmp/test/f2.txt");
- coord.writes.write().insert(
- p1.clone(),
- WriteStamp {
- writer: "child-1".to_string(),
- timestamp: Instant::now(),
- },
- );
- coord.writes.write().insert(
- p2.clone(),
- WriteStamp {
- writer: "child-2".to_string(),
- timestamp: Instant::now(),
- },
- );
- let result = coord.paths_written_by(&["child-1".to_string()]);
- assert_eq!(result.len(), 1);
- assert!(result.contains_key("child-1"));
- assert_eq!(result["child-1"], vec![p1]);
-}
-
-#[tokio::test]
-async fn path_lock_serialises_access() {
- let coord = fresh_coordinator();
- let path = PathBuf::from("/tmp/test/lock.txt");
- let mutex = {
- let mut locks = coord.path_locks.write();
- locks
- .entry(path.clone())
- .or_insert_with(|| Arc::new(Mutex::new(())))
- .clone()
- };
-
- let guard = mutex.lock().await;
- assert!(mutex.try_lock().is_err());
- drop(guard);
- assert!(mutex.try_lock().is_ok());
-}
diff --git a/crates/openhuman-core/src/agent/harness/credentials.rs b/crates/openhuman-core/src/agent/harness/credentials.rs
index ab7aab5474..b7df5d0c4a 100644
--- a/crates/openhuman-core/src/agent/harness/credentials.rs
+++ b/crates/openhuman-core/src/agent/harness/credentials.rs
@@ -1,86 +1,4 @@
-use regex::Regex;
-use std::sync::LazyLock;
+//! Credential scrubbing for tool output; the rules live in
+//! [`tinyinference_core::sanitize::scrub_credentials`].
-/// Key/value credential shapes: `token: "…"`, `api_key=…`, `bearer: …`, etc.
-static SENSITIVE_KV_REGEX: LazyLock<Regex> = LazyLock::new(|| {
- Regex::new(r#"(?i)(token|api[_-]?key|password|secret|user[_-]?key|bearer|credential)["']?\s*[:=]\s*(?:"([^"]{8,})"|'([^']{8,})'|([a-zA-Z0-9_\-\.]{8,}))"#).unwrap()
-});
-
-/// Bare AWS access-key IDs — `AKIA…`/`ASIA…` followed by 16 base32 chars — which
-/// appear naked in env dumps and config reads with no surrounding key name.
-static AWS_ACCESS_KEY_REGEX: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"\b((?:AKIA|ASIA)[0-9A-Z]{16})\b").unwrap());
-
-/// Bare OpenAI-style secret keys — `sk-…` (incl. `sk-proj-…`) with a long token
-/// body. Not necessarily attached to a `key:` label in raw API responses.
-static OPENAI_KEY_REGEX: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"\b(sk-[A-Za-z0-9_\-]{16,})\b").unwrap());
-
-/// Space-separated bearer tokens as they appear in HTTP auth headers
-/// (`Authorization: Bearer <token>`) — the KV regex only catches `bearer:`/`=`.
-static BEARER_SPACE_REGEX: LazyLock<Regex> =
- LazyLock::new(|| Regex::new(r"(?i)\b(Bearer)\s+([A-Za-z0-9_\-\.=+/]{16,})").unwrap());
-
-/// Preserve the first 4 chars of `val` for context, returning the redacted
-/// prefix (empty when the value is too short to safely reveal any of it).
-fn redact_prefix(val: &str) -> &str {
- if val.chars().count() > 4 {
- match val.char_indices().nth(4) {
- Some((idx, _)) => &val[..idx],
- None => val,
- }
- } else {
- ""
- }
-}
-
-/// Scrub credentials from tool output to prevent accidental exfiltration.
-/// Replaces known credential patterns with a redacted placeholder while preserving
-/// a small prefix for context.
-///
-/// Covers labelled key/value pairs plus bare secrets that show up unlabelled in
-/// env dumps, config reads and API responses: AWS access-key IDs (`AKIA…`/
-/// `ASIA…`), OpenAI-style `sk-…` keys, and space-separated `Bearer <token>`
-/// auth headers.
-pub(crate) fn scrub_credentials(input: &str) -> String {
- let stage_kv = SENSITIVE_KV_REGEX.replace_all(input, |caps: &regex::Captures| {
- let full_match = &caps[0];
- let value = caps
- .get(2)
- .or(caps.get(3))
- .or(caps.get(4))
- .expect("sensitive key-value match has a value");
- // Replace only the value span. Rebuilding the key from captures used
- // to add a second opening quote to JSON (`""token": ...`), making
- // tool results impossible to parse after redaction.
- let start = value.start() - caps.get(0).expect("full match").start();
- let end = value.end() - caps.get(0).expect("full match").start();
- format!(
- "{}{}*[REDACTED]{}",
- &full_match[..start],
- redact_prefix(value.as_str()),
- &full_match[end..]
- )
- });
-
- // Bare AWS access-key IDs: keep the 4-char `AKIA`/`ASIA` prefix for context.
- let stage_aws = AWS_ACCESS_KEY_REGEX.replace_all(&stage_kv, |caps: &regex::Captures| {
- format!("{}*[REDACTED]", redact_prefix(&caps[1]))
- });
-
- // Bare `sk-…` keys: keep the `sk-` scheme, redact the secret body.
- let stage_openai = OPENAI_KEY_REGEX.replace_all(&stage_aws, |_caps: &regex::Captures| {
- "sk-*[REDACTED]".to_string()
- });
-
- // Space-separated `Bearer <token>`: keep the scheme word, redact the token.
- BEARER_SPACE_REGEX
- .replace_all(&stage_openai, |caps: &regex::Captures| {
- format!("{} *[REDACTED]", &caps[1])
- })
- .to_string()
-}
-
-#[cfg(test)]
-#[path = "credentials_tests.rs"]
-mod tests;
+pub(crate) use tinyinference_core::sanitize::scrub_credentials;
diff --git a/crates/openhuman-core/src/agent/harness/credentials_tests.rs b/crates/openhuman-core/src/agent/harness/credentials_tests.rs
deleted file mode 100644
index 8ec2c12923..0000000000
--- a/crates/openhuman-core/src/agent/harness/credentials_tests.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-use super::*;
-
-#[test]
-fn test_scrub_credentials_utf8() {
- // Regex requires at least 8 chars for the value
- // The [a-zA-Z0-9_\-\.]{8,} part of the regex does NOT match emoji
- // So we must use quotes to hit the "([^"]{8,})" part
- let input = "api_key: \"🦀🦀🦀🦀🦀🦀🦀🦀\"";
- let output = scrub_credentials(input);
- // Should preserve 4 crabs and then redact
- assert!(output.contains("🦀🦀🦀🦀*[REDACTED]"));
-}
-
-#[test]
-fn test_scrub_credentials_short_val() {
- let input = "api_key: 12345678";
- let output = scrub_credentials(input);
- assert!(output.contains("api_key: 1234*[REDACTED]"));
-}
-
-#[test]
-fn scrubbed_json_keeps_its_quoted_key_and_parses() {
- let input = r#"{"token":"example-secret-value","status":"ready"}"#;
- let output = scrub_credentials(input);
- let parsed: serde_json::Value = serde_json::from_str(&output).expect("valid JSON after scrub");
- assert_eq!(parsed["status"], "ready");
- assert!(!output.contains("example-secret-value"));
- assert!(output.contains("*[REDACTED]"));
-}
-
-// #4453: bare, unlabelled secrets that show up in env dumps / API responses.
-
-#[test]
-fn scrubs_bare_aws_access_key() {
- let out = scrub_credentials("config dump AKIAIOSFODNN7EXAMPLE trailing text");
- assert!(
- !out.contains("AKIAIOSFODNN7EXAMPLE"),
- "bare AWS access key must be redacted: {out}"
- );
- assert!(
- out.contains("[REDACTED]"),
- "redaction marker present: {out}"
- );
-}
-
-#[test]
-fn scrubs_bare_openai_key() {
- let out = scrub_credentials("response body sk-abcdefghij1234567890ABCDEFGHIJ end");
- assert!(
- !out.contains("abcdefghij1234567890ABCDEFGHIJ"),
- "openai secret body must be redacted: {out}"
- );
- assert!(
- out.contains("sk-"),
- "the sk- scheme is kept for context: {out}"
- );
- assert!(
- out.contains("[REDACTED]"),
- "redaction marker present: {out}"
- );
-}
-
-#[test]
-fn scrubs_space_separated_bearer_token() {
- let out = scrub_credentials("Authorization: Bearer abcDEF1234567890ghijklmnop done");
- assert!(
- !out.contains("abcDEF1234567890ghijklmnop"),
- "space-separated bearer token must be redacted: {out}"
- );
- assert!(
- out.contains("Bearer"),
- "the scheme word is kept for context: {out}"
- );
- assert!(
- out.contains("[REDACTED]"),
- "redaction marker present: {out}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/required_output.rs b/crates/openhuman-core/src/agent/harness/required_output.rs
index d3f1e933f4..476103a7a3 100644
--- a/crates/openhuman-core/src/agent/harness/required_output.rs
+++ b/crates/openhuman-core/src/agent/harness/required_output.rs
@@ -1,101 +1,6 @@
-//! Required structured-output validation & repair (issue #4117).
-//!
-//! Some agent contracts mandate a JSON block — e.g. a `thoughts` block like
-//! `{"thoughts": "…", "next_action": "…"}` — on **every** turn, because
-//! downstream parsing/routing depends on it. Models frequently omit the block
-//! entirely, leaving those consumers with nothing.
-//!
-//! This module supplies the pure primitives the turn engine uses to guarantee a
-//! well-formed block on every accepted turn:
-//!
-//! * [`output_satisfies_contract`] — validate presence + shape of the block,
-//! * [`repair_instruction`] — the corrective re-prompt that asks the model to
-//! re-emit its reply with the block, and
-//! * [`synthesize_block`] — a minimal, schema-valid block used as a deterministic
-//! fallback when the re-prompt also omits it.
-//!
-//! The orchestration that ties these together (validate → re-prompt → synthesize)
-//! lives on the session in `session::turn::session_io` so it can drive the extra
-//! provider call and reconcile with streaming; keeping the logic here pure keeps
-//! it unit-testable without a provider.
+//! Required structured-output validation & repair (issue #4117); the pure
+//! primitives live in [`tinyagents_harness::config`].
-use tinyagents_harness::config::RequiredOutput;
-
-/// Whether `text` satisfies `contract`: it contains a JSON object carrying every
-/// required key with a non-null value, in the expected leading position. An
-/// inert contract (no non-blank keys) is treated as always satisfied so
-/// enforcement is a no-op.
-pub(crate) fn output_satisfies_contract(text: &str, contract: &RequiredOutput) -> bool {
- if !contract.is_active() {
- return true;
- }
- find_required_block(text, contract).is_some()
-}
-
-/// The required block when it appears in the expected **leading position** —
-/// the *first* JSON value in `text` must be an object carrying every required
-/// key with a non-null value — else `None`.
-///
-/// Issue #4117 mandates the block in a predictable position so downstream
-/// parsing/routing can rely on it. Prose before the block is fine (prose is not
-/// JSON, so the block is still the first extracted value), but a block buried
-/// after *another* JSON object is rejected and gets repaired rather than
-/// silently accepted. Reuses the harness JSON extractor so fenced, inline, and
-/// whole-object replies are all recognised.
-pub(crate) fn find_required_block(
- text: &str,
- contract: &RequiredOutput,
-) -> Option<serde_json::Value> {
- let keys = contract.all_keys();
- if keys.is_empty() {
- return None;
- }
- let first = tinytools_agent::extract_json_values(text)
- .into_iter()
- .next()?;
- let obj = first.as_object()?;
- let has_all = keys
- .iter()
- .all(|key| obj.get(key).is_some_and(|v| !v.is_null()));
- if has_all {
- Some(first)
- } else {
- None
- }
-}
-
-/// A minimal, schema-valid block synthesised when the model omits the block and
-/// a corrective re-prompt fails to recover it. Every required key maps to an
-/// empty string so downstream parsing always has a well-formed object to
-/// consume. Returns `"{}"` only for an inert contract (which enforcement never
-/// reaches).
-pub(crate) fn synthesize_block(contract: &RequiredOutput) -> String {
- let mut obj = serde_json::Map::new();
- for key in contract.all_keys() {
- obj.insert(key, serde_json::Value::String(String::new()));
- }
- serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_else(|_| "{}".to_string())
-}
-
-/// The corrective instruction that re-prompts the model to re-emit its reply
-/// with the required block. Mirrors the iteration-cap checkpoint re-prompt: a
-/// self-contained user turn appended after the omitting reply.
-///
-/// The model is asked to lead with the JSON object so the repaired reply
-/// satisfies the leading-position rule directly, whether the caller keeps the
-/// re-prompt as the whole reply (the non-streamed *replace* path) or appends it
-/// after prose that was already streamed (the *append* path); see
-/// `OpenHumanSessionHost::enforce_required_output`.
-pub(crate) fn repair_instruction(contract: &RequiredOutput) -> String {
- let keys = contract.all_keys().join("\", \"");
- format!(
- "Your previous reply omitted the required JSON `{}` block that every turn must include. \
-Reply again, leading with a single valid JSON object containing the keys \"{}\" — all present \
-and non-null — then continue with your answer. Do not call any tools.",
- contract.block_key, keys
- )
-}
-
-#[cfg(test)]
-#[path = "required_output_tests.rs"]
-mod tests;
+pub(crate) use tinyagents_harness::config::{
+ output_satisfies_contract, repair_instruction, synthesize_block,
+};
diff --git a/crates/openhuman-core/src/agent/harness/required_output_tests.rs b/crates/openhuman-core/src/agent/harness/required_output_tests.rs
deleted file mode 100644
index c9c42b9aeb..0000000000
--- a/crates/openhuman-core/src/agent/harness/required_output_tests.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-use super::*;
-
-fn thoughts_contract() -> RequiredOutput {
- RequiredOutput {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }
-}
-
-#[test]
-fn present_well_formed_block_satisfies_contract() {
- let contract = thoughts_contract();
- let text = "Sure! {\"thoughts\": \"planning\", \"next_action\": \"call tool\"}";
- assert!(output_satisfies_contract(text, &contract));
- assert!(find_required_block(text, &contract).is_some());
-}
-
-#[test]
-fn prose_only_reply_fails_validation() {
- let contract = thoughts_contract();
- assert!(!output_satisfies_contract(
- "Sure, I'll handle that.",
- &contract
- ));
-}
-
-#[test]
-fn block_missing_a_required_sibling_key_fails() {
- let contract = thoughts_contract();
- // Has `thoughts` but not `next_action`.
- let text = "{\"thoughts\": \"planning\"}";
- assert!(!output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn null_valued_required_key_fails() {
- let contract = RequiredOutput::new("thoughts");
- assert!(!output_satisfies_contract(
- "{\"thoughts\": null}",
- &contract
- ));
-}
-
-#[test]
-fn synthesized_block_satisfies_its_own_contract() {
- let contract = thoughts_contract();
- let synthesized = synthesize_block(&contract);
- assert!(
- output_satisfies_contract(&synthesized, &contract),
- "synthesized fallback must satisfy the contract it was built from: {synthesized}"
- );
-}
-
-#[test]
-fn leading_block_after_prose_is_accepted() {
- let contract = thoughts_contract();
- // Prose before the block is fine — prose is not JSON, so the block is
- // still the first extracted value.
- let text = "Here is my plan.\n{\"thoughts\": \"x\", \"next_action\": \"y\"}";
- assert!(output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn synthesized_block_prepended_to_prose_leads_correctly() {
- // The non-streamed *replace* fallback prepends a synthesized block to the
- // original prose; the block must be the first JSON value so the reply
- // validates.
- let contract = thoughts_contract();
- let repaired = format!("{}\n\n{}", synthesize_block(&contract), "Working on it.");
- assert!(output_satisfies_contract(&repaired, &contract));
-}
-
-#[test]
-fn block_buried_after_another_json_object_is_rejected() {
- let contract = thoughts_contract();
- // A different JSON object leads; the required block is second → rejected
- // so it gets repaired rather than silently accepted (issue #4117).
- let text = "{\"foo\": 1}\n{\"thoughts\": \"x\", \"next_action\": \"y\"}";
- assert!(!output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn blank_block_key_makes_contract_inert() {
- // A blank block key is inert even when sibling keys are listed — the
- // contract's defining key can never be enforced, so enforcement is
- // skipped instead of accepting a block missing that key.
- let contract = RequiredOutput {
- block_key: " ".into(),
- required_keys: vec!["next_action".into()],
- };
- assert!(!contract.is_active());
- assert!(output_satisfies_contract(
- "{\"next_action\": \"y\"}",
- &contract
- ));
-}
-
-#[test]
-fn inert_contract_is_always_satisfied() {
- let contract = RequiredOutput::default();
- assert!(!contract.is_active());
- assert!(output_satisfies_contract("no block here", &contract));
- assert!(find_required_block("no block here", &contract).is_none());
-}
-
-#[test]
-fn all_keys_trims_and_dedupes() {
- let contract = RequiredOutput {
- block_key: " thoughts ".into(),
- required_keys: vec![
- "thoughts".into(),
- " next_action ".into(),
- "next_action".into(),
- ],
- };
- // block_key trimmed; duplicate `thoughts` and repeated `next_action`
- // collapse to a single occurrence each, order-preserving.
- assert_eq!(contract.all_keys(), vec!["thoughts", "next_action"]);
-}
-
-#[test]
-fn repair_instruction_names_every_required_key() {
- let contract = thoughts_contract();
- let instruction = repair_instruction(&contract);
- assert!(instruction.contains("thoughts"));
- assert!(instruction.contains("next_action"));
-}
diff --git a/crates/openhuman-core/src/agent/pformat_tests.rs b/crates/openhuman-core/src/agent/pformat_tests.rs
deleted file mode 100644
index efc80d921d..0000000000
--- a/crates/openhuman-core/src/agent/pformat_tests.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-use async_trait::async_trait;
-use tinytools::{Tool, ToolResult};
-use tinytools_agent::{build_registry, parse_call, render_signature_from_schema};
-
-struct StubTool(&'static str);
-
-#[async_trait]
-impl Tool for StubTool {
- fn name(&self) -> &str {
- self.0
- }
-
- fn description(&self) -> &str {
- "stub tool"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({
- "type": "object",
- "properties": {
- "value": { "type": "string" },
- "count": { "type": "integer" }
- }
- })
- }
-
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::success("ok"))
- }
-}
-
-#[test]
-fn build_registry_keys_on_the_tools_own_names() {
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(StubTool("echo")), Box::new(StubTool("shell"))];
- let reg = build_registry(
- tools
- .iter()
- .map(|tool| (tool.name(), tool.parameters_schema())),
- );
- assert!(reg.contains_key("echo"));
- assert!(reg.contains_key("shell"));
- assert_eq!(reg.len(), 2);
-}
-
-#[test]
-fn a_tool_absent_from_the_registry_cannot_be_called() {
- // The safety boundary: the parser must not invent argument names for a
- // tool it does not know, or a model could tunnel arbitrary JSON through
- // by guessing a name. This adapter is what decides what is "known".
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(StubTool("echo"))];
- let reg = build_registry(
- tools
- .iter()
- .map(|tool| (tool.name(), tool.parameters_schema())),
- );
- assert!(parse_call("shell[rm -rf /]", &reg).is_none());
-}
-
-#[test]
-fn a_registered_tool_parses_positionally_through_the_adapter() {
- // End-to-end through the adapter: schema comes from the Tool impl, and
- // arguments come back named and coerced.
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(StubTool("echo"))];
- let reg = build_registry(
- tools
- .iter()
- .map(|tool| (tool.name(), tool.parameters_schema())),
- );
- let (name, args) = parse_call("echo[0|3|1|hi]", &reg).expect("known tool parses");
- assert_eq!(name, "echo");
- // Schema properties are ordered alphabetically: count, value.
- assert_eq!(args["count"], 3);
- assert_eq!(args["value"], "hi");
-}
-
-#[test]
-fn signature_rendering_agrees_between_the_tool_and_schema_forms() {
- // The signature goes into the system prompt; if these two disagreed the
- // catalogue would advertise a different argument order than the parser
- // reconstructs.
- let tool = StubTool("echo");
- let from_tool = render_signature_from_schema(tool.name(), &tool.parameters_schema());
- let from_schema = render_signature_from_schema("echo", &tool.parameters_schema());
- assert_eq!(from_tool, from_schema);
- assert_eq!(from_tool, "echo[0|<count>|1|<value>]");
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/summarize_tests.rs b/crates/openhuman-core/src/agent/tinyagents/summarize_tests.rs
deleted file mode 100644
index 02c1bb10dd..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/summarize_tests.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-use super::*;
-
-#[test]
-fn policy_is_context_window_aware_at_the_configured_threshold() {
- let policy = summarization_policy(200_000);
- assert_eq!(policy.context_window, Some(200_000));
- assert_eq!(policy.threshold_fraction, SUMMARIZE_THRESHOLD_FRACTION);
- assert_eq!(policy.keep_last, SUMMARIZE_KEEP_LAST);
-}
-
-#[test]
-fn threshold_fraction_leaves_headroom_below_the_window() {
- // The policy must trigger *before* the window is full, so the summary
- // call itself has room — 90% by default.
- assert!(SUMMARIZE_THRESHOLD_FRACTION > 0.0 && SUMMARIZE_THRESHOLD_FRACTION < 1.0);
- let policy = summarization_policy(100_000);
- // 90% of 100k = 90k tokens is the effective trigger point.
- let effective = (policy.context_window.unwrap() as f64 * policy.threshold_fraction) as u64;
- assert_eq!(effective, 90_000);
-}
diff --git a/crates/openhuman-core/src/threads/title.rs b/crates/openhuman-core/src/threads/title.rs
index a7e9e226db..0c60b89011 100644
--- a/crates/openhuman-core/src/threads/title.rs
+++ b/crates/openhuman-core/src/threads/title.rs
@@ -1,241 +1,6 @@
-//! Pure helpers for generating and validating conversation thread titles.
-//!
-//! Extracted from `threads::ops` so the parsing / sanitisation rules can be
-//! unit-tested without pulling in `Config`, provider runtime, or RPC wiring.
+//! Pure helpers for generating and validating conversation thread titles; the
+//! implementation lives in [`tinyagents_harness::title`].
-use std::hash::{Hash, Hasher};
-
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::ModelRequest;
+pub use tinyagents_harness::title::*;
pub const THREAD_TITLE_LOG_PREFIX: &str = "[threads:title]";
-pub const THREAD_TITLE_SYSTEM_PROMPT: &str = "You name chat threads from the first user message and the assistant reply. Return only the name: at most 3 words, like Fix session handoff or Gmail OAuth retry. Lead with the verb or the subject and drop filler words. No quotes. No markdown. No punctuation.";
-
-/// Words a title carries at most. Three is the whole point of the shape: a
-/// thread list is scanned, not read, and a fourth word is always the one that
-/// pushes the specific words off the end of a narrow row.
-pub const THREAD_TITLE_MAX_WORDS: usize = 3;
-/// Hard character ceiling on a title, so one very long word cannot widen a row.
-pub const THREAD_TITLE_MAX_CHARS: usize = 48;
-
-/// Filler a title is better off without.
-///
-/// Prompts open with conversational scaffolding ("okay so can you please…"),
-/// and taking the first three words verbatim would spend the whole title on it.
-/// Only words that never identify a thread on their own are listed; a filtered
-/// title that comes out empty falls back to the unfiltered words, so a message
-/// made entirely of these still gets a name.
-const FILLER_WORDS: &[&str] = &[
- "a", "about", "an", "and", "are", "as", "at", "be", "but", "by", "can", "could", "do", "does",
- "for", "from", "hey", "hi", "how", "i", "if", "in", "into", "is", "it", "its", "just", "let",
- "lets", "like", "me", "my", "of", "ok", "okay", "on", "or", "our", "please", "so", "thanks",
- "that", "the", "their", "then", "there", "these", "they", "this", "to", "uh", "um", "us",
- "was", "we", "well", "what", "when", "which", "will", "with", "would", "you", "your",
-];
-
-/// Stable 16-hex-char fingerprint of a title — safe for structured logs
-/// where we want to correlate events without leaking the raw title text.
-pub fn title_log_fingerprint(title: &str) -> String {
- let mut hasher = std::collections::hash_map::DefaultHasher::new();
- title.hash(&mut hasher);
- format!("{:016x}", hasher.finish())
-}
-
-/// Returns `true` when the title matches the auto-generated placeholder
-/// shape used by `thread_create_new` (`"Chat Mon 1 1:23 AM"` / `...PM"`).
-///
-/// Only placeholder titles are eligible for replacement by the LLM-generated
-/// title; user-renamed threads are left untouched.
-pub fn is_auto_generated_thread_title(title: &str) -> bool {
- let trimmed = title.trim();
- let bytes = trimmed.as_bytes();
- if bytes.len() < 16 || !trimmed.starts_with("Chat ") {
- return false;
- }
-
- let month_end = 8;
- if bytes.len() <= month_end || !bytes[5..month_end].iter().all(|b| b.is_ascii_alphabetic()) {
- return false;
- }
- if bytes.get(month_end) != Some(&b' ') {
- return false;
- }
-
- let mut idx = month_end + 1;
- let day_start = idx;
- while idx < bytes.len() && bytes[idx].is_ascii_digit() {
- idx += 1;
- }
- if idx == day_start || idx - day_start > 2 {
- return false;
- }
- if bytes.get(idx) != Some(&b' ') {
- return false;
- }
- idx += 1;
-
- let hour_start = idx;
- while idx < bytes.len() && bytes[idx].is_ascii_digit() {
- idx += 1;
- }
- if idx == hour_start || idx - hour_start > 2 {
- return false;
- }
- if bytes.get(idx) != Some(&b':') {
- return false;
- }
- idx += 1;
-
- if idx + 2 >= bytes.len()
- || !bytes[idx].is_ascii_digit()
- || !bytes[idx + 1].is_ascii_digit()
- || bytes[idx + 2] != b' '
- {
- return false;
- }
- idx += 3;
-
- matches!(&trimmed[idx..], "AM" | "PM")
-}
-
-/// Collapses any run of whitespace (including newlines/tabs) into single
-/// ASCII spaces and trims the result.
-pub fn collapse_whitespace(input: &str) -> String {
- input.split_whitespace().collect::<Vec<_>>().join(" ")
-}
-
-/// Reduces any text to the thread-title shape: at most
-/// [`THREAD_TITLE_MAX_WORDS`] words, e.g. `Fix session handoff`.
-///
-/// This is the shape enforcer, not a request: the model is asked for a short
-/// name in [`THREAD_TITLE_SYSTEM_PROMPT`], but a title that reaches storage as
-/// a whole sentence because one completion ignored the instruction is exactly
-/// the bug the shape is meant to remove, so every path runs through here.
-///
-/// Rules applied (in order):
-/// - split on anything that is not alphanumeric (punctuation, quotes, markdown,
-/// and whitespace all become word breaks)
-/// - drop [`FILLER_WORDS`], unless that would leave nothing
-/// - keep the first [`THREAD_TITLE_MAX_WORDS`] words, and stop early rather
-/// than exceed [`THREAD_TITLE_MAX_CHARS`]
-///
-/// A word's own spelling is left alone — `OAuth` and `Gmail` read wrong
-/// lowercased, and the model is the only thing here that knows which is which.
-///
-/// Returns `None` when no word survives.
-pub fn shorten_title(text: &str) -> Option<String> {
- let words: Vec<&str> = text
- .split(|c: char| !c.is_alphanumeric())
- .filter(|word| !word.is_empty())
- .collect();
- if words.is_empty() {
- return None;
- }
- let meaningful: Vec<&str> = words
- .iter()
- .copied()
- .filter(|word| !FILLER_WORDS.contains(&word.to_lowercase().as_str()))
- .collect();
- // All-filler input ("can you please") still names its thread, badly-but-
- // stably, rather than leaving the placeholder title in place.
- let source = if meaningful.is_empty() {
- words
- } else {
- meaningful
- };
-
- let mut title = String::new();
- for word in source.into_iter().take(THREAD_TITLE_MAX_WORDS) {
- let separator = usize::from(!title.is_empty());
- let room = THREAD_TITLE_MAX_CHARS.saturating_sub(title.chars().count() + separator);
- if room == 0 {
- break;
- }
- if !title.is_empty() {
- title.push(' ');
- }
- // A single word longer than the ceiling is truncated rather than
- // dropped: dropping it can empty an otherwise usable title.
- title.extend(word.chars().take(room));
- }
- (!title.is_empty()).then_some(title)
-}
-
-/// Sanitises a raw LLM title completion into a stored thread title.
-///
-/// Takes the first non-empty line — a chatty model that adds a second line of
-/// commentary should not have it folded into the name — and shortens it with
-/// [`shorten_title`], which absorbs the quote/markdown/punctuation stripping
-/// the older sentence-shaped title needed done by hand.
-///
-/// Returns `None` if the result is empty.
-pub fn sanitize_generated_title(raw: &str) -> Option<String> {
- let line = raw
- .lines()
- .find(|line| !line.trim().is_empty())
- .unwrap_or(raw);
- shorten_title(line)
-}
-
-/// Derives a stable display title directly from the first useful user message.
-///
-/// This is the no-provider fallback used while a conversation only has user
-/// context, or when model-based title generation is unavailable. It keeps the
-/// title meaningful without repeatedly renaming the thread later.
-pub fn title_from_user_message(message: &str) -> Option<String> {
- let collapsed = collapse_whitespace(message);
- if collapsed.is_empty() {
- return None;
- }
-
- // Only the first sentence describes the ask; what follows is context the
- // title has no room for anyway.
- let first_sentence = collapsed
- .split(['.', '!', '?', '\n'])
- .find(|part| !part.trim().is_empty())
- .unwrap_or(&collapsed);
- shorten_title(first_sentence)
-}
-
-/// Builds the user-visible prompt passed to the title-generation model.
-pub fn build_title_prompt(user_message: &str, assistant_message: &str) -> String {
- format!(
- "First user message:\n{user_message}\n\nAssistant reply:\n{assistant_message}\n\nReturn the best thread name."
- )
-}
-
-/// Builds the whole title-generation request.
-///
-/// # It deliberately sets no model
-///
-/// The caller has already resolved the model by building the provider for the
-/// `summarization` role, and the resolved model is the one that should
-/// dispatch. `ModelRequest::model` is a *per-request override* that the
-/// managed backend resolves verbatim, so anything set here replaces that
-/// correct model on the wire.
-///
-/// This used to override it with `"hint:summarize"`, which no lookup table in
-/// the tree defines — every hint-alias table spells the alias `summarization`.
-/// The string matched nothing, survived translation unchanged, and reached the
-/// backend as a literal model id, which answered
-/// `400 Model 'hint:summarize' is not available` on every call. Title
-/// generation then fell back to a keyword title for four months without
-/// anything escalating (#5637).
-///
-/// Leaving `model` unset is also the only form that is correct for **every**
-/// provider. `create_chat_model` resolves the `summarization` role to the
-/// managed backend, a Claude Agent SDK / Claude Code model, a local runtime,
-/// or a BYOK cloud slug; pinning any concrete tier id here would be wrong for
-/// the four non-managed branches. Unset means each provider uses its own
-/// construction-time default.
-pub fn build_title_request(user_message: &str, assistant_message: &str) -> ModelRequest {
- ModelRequest::new(vec![
- Message::system(THREAD_TITLE_SYSTEM_PROMPT),
- Message::user(build_title_prompt(user_message, assistant_message)),
- ])
- .with_temperature(0.2)
-}
-
-#[cfg(test)]
-#[path = "title_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/threads/title_tests.rs b/crates/openhuman-core/src/threads/title_tests.rs
deleted file mode 100644
index f70235cdcc..0000000000
--- a/crates/openhuman-core/src/threads/title_tests.rs
+++ /dev/null
@@ -1,256 +0,0 @@
-use super::*;
-
-// ── title_log_fingerprint ─────────────────────────────────────
-
-#[test]
-fn fingerprint_is_stable_for_same_input() {
- assert_eq!(
- title_log_fingerprint("hello"),
- title_log_fingerprint("hello")
- );
-}
-
-#[test]
-fn fingerprint_differs_for_different_input() {
- assert_ne!(
- title_log_fingerprint("hello"),
- title_log_fingerprint("world")
- );
-}
-
-#[test]
-fn fingerprint_is_sixteen_hex_chars() {
- let fp = title_log_fingerprint("anything");
- assert_eq!(fp.len(), 16);
- // Lowercase hex specifically, so grep-friendly debug logs stay
- // consistent (folded in from the former threads/ops_tests copy).
- assert!(
- fp.chars()
- .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
- "fingerprint must be lowercase hex, got: {fp}"
- );
-}
-
-// ── is_auto_generated_thread_title ────────────────────────────
-
-#[test]
-fn accepts_canonical_placeholder() {
- assert!(is_auto_generated_thread_title("Chat Jan 1 1:23 AM"));
- assert!(is_auto_generated_thread_title("Chat Dec 31 11:59 PM"));
-}
-
-#[test]
-fn accepts_single_digit_day_and_hour() {
- assert!(is_auto_generated_thread_title("Chat Mar 5 9:07 AM"));
-}
-
-#[test]
-fn accepts_two_digit_day_and_hour() {
- assert!(is_auto_generated_thread_title("Chat Feb 28 10:45 PM"));
-}
-
-#[test]
-fn tolerates_surrounding_whitespace() {
- assert!(is_auto_generated_thread_title(" Chat Jan 1 1:23 AM "));
-}
-
-#[test]
-fn rejects_empty_and_short_titles() {
- assert!(!is_auto_generated_thread_title(""));
- assert!(!is_auto_generated_thread_title("Chat"));
- assert!(!is_auto_generated_thread_title("Chat Jan 1"));
-}
-
-#[test]
-fn rejects_non_chat_prefix() {
- assert!(!is_auto_generated_thread_title("Thread Jan 1 1:23 AM"));
- assert!(!is_auto_generated_thread_title("chat Jan 1 1:23 AM")); // case matters
-}
-
-#[test]
-fn rejects_numeric_month() {
- assert!(!is_auto_generated_thread_title("Chat 01 1 1:23 AM"));
-}
-
-#[test]
-fn rejects_missing_am_pm() {
- assert!(!is_auto_generated_thread_title("Chat Jan 1 1:23"));
- assert!(!is_auto_generated_thread_title("Chat Jan 1 1:23 XM"));
-}
-
-#[test]
-fn rejects_user_renamed_titles() {
- assert!(!is_auto_generated_thread_title("Planning the launch party"));
- assert!(!is_auto_generated_thread_title(
- "Chat with Alice about deploys"
- ));
-}
-
-#[test]
-fn rejects_malformed_minutes() {
- // Minutes must be exactly two digits followed by a space.
- assert!(!is_auto_generated_thread_title("Chat Jan 1 1:2 AM"));
- assert!(!is_auto_generated_thread_title("Chat Jan 1 1:234 AM"));
-}
-
-// ── collapse_whitespace ────────────────────────────────────────
-
-#[test]
-fn collapse_whitespace_normalises_runs() {
- assert_eq!(collapse_whitespace(" hello world "), "hello world");
-}
-
-#[test]
-fn collapse_whitespace_handles_tabs_and_newlines() {
- assert_eq!(collapse_whitespace("a\tb\nc d"), "a b c d");
-}
-
-#[test]
-fn collapse_whitespace_empty_returns_empty() {
- assert_eq!(collapse_whitespace(""), "");
- assert_eq!(collapse_whitespace(" "), "");
-}
-
-// ── shorten_title ─────────────────────────────────────────────
-
-#[test]
-fn shorten_keeps_at_most_three_words() {
- assert_eq!(
- shorten_title("Fix session handoff flow and pointer").unwrap(),
- "Fix session handoff"
- );
- assert_eq!(shorten_title("Launch Plan").unwrap(), "Launch Plan");
-}
-
-#[test]
-fn shorten_leaves_a_words_own_spelling_alone() {
- // Lowercasing would turn these into something nobody would type.
- assert_eq!(
- shorten_title("Gmail OAuth retry loop").unwrap(),
- "Gmail OAuth retry"
- );
-}
-
-#[test]
-fn shorten_drops_leading_filler() {
- assert_eq!(
- shorten_title("okay so can you please fix the session handoff").unwrap(),
- "fix session handoff"
- );
-}
-
-#[test]
-fn shorten_falls_back_to_filler_when_that_is_all_there_is() {
- assert_eq!(shorten_title("can you please").unwrap(), "can you please");
-}
-
-#[test]
-fn shorten_treats_punctuation_and_markdown_as_word_breaks() {
- assert_eq!(
- shorten_title("**Debugging deploys:** retry").unwrap(),
- "Debugging deploys retry"
- );
- assert_eq!(
- shorten_title("\"gmail/oauth retry\"").unwrap(),
- "gmail oauth retry"
- );
-}
-
-#[test]
-fn shorten_bounds_total_length() {
- let long = format!("{} {} {}", "a".repeat(30), "b".repeat(30), "c".repeat(30));
- let out = shorten_title(&long).unwrap();
- assert!(out.chars().count() <= THREAD_TITLE_MAX_CHARS);
- // A word that does not fit whole is truncated, never dropped.
- assert!(out.starts_with(&"a".repeat(30)));
-}
-
-#[test]
-fn shorten_counts_chars_not_bytes() {
- // Each ✨ is 3 bytes in UTF-8, and is not alphanumeric — a title made
- // only of them has no word to keep.
- assert!(shorten_title(&"✨".repeat(90)).is_none());
- let out = shorten_title(&"é".repeat(90)).unwrap();
- assert_eq!(out.chars().count(), THREAD_TITLE_MAX_CHARS);
-}
-
-#[test]
-fn shorten_returns_none_without_a_word() {
- assert!(shorten_title("").is_none());
- assert!(shorten_title(" \n\t ").is_none());
- assert!(shorten_title("///").is_none());
-}
-
-// ── sanitize_generated_title ──────────────────────────────────
-
-#[test]
-fn sanitize_shortens_a_sentence_shaped_completion() {
- assert_eq!(
- sanitize_generated_title("\"Planning the launch party\"").unwrap(),
- "Planning launch party"
- );
- // "are"/"we" are filler, so a question collapses to its one real word.
- assert_eq!(sanitize_generated_title("Where are we?").unwrap(), "Where");
-}
-
-#[test]
-fn sanitize_passes_an_already_short_completion_through() {
- assert_eq!(
- sanitize_generated_title("Fix session handoff").unwrap(),
- "Fix session handoff"
- );
-}
-
-#[test]
-fn sanitize_picks_first_nonempty_line() {
- let raw = "\n\n First real line \nsecond line\n";
- assert_eq!(sanitize_generated_title(raw).unwrap(), "First real line");
-}
-
-#[test]
-fn sanitize_returns_none_for_empty_or_whitespace() {
- assert!(sanitize_generated_title("").is_none());
- assert!(sanitize_generated_title(" \n\t ").is_none());
- assert!(sanitize_generated_title("\"\"").is_none());
-}
-
-#[test]
-fn sanitize_bounds_length() {
- let long = "a".repeat(200);
- let out = sanitize_generated_title(&long).unwrap();
- assert_eq!(out.chars().count(), THREAD_TITLE_MAX_CHARS);
-}
-
-// ── title_from_user_message ──────────────────────────────────
-
-#[test]
-fn title_from_user_message_uses_first_specific_words() {
- assert_eq!(
- title_from_user_message("Can you retrieve my latest 5 emails and summarize them?").unwrap(),
- "retrieve latest 5"
- );
-}
-
-#[test]
-fn title_from_user_message_removes_command_prefix_and_punctuation() {
- assert_eq!(
- title_from_user_message("/briefing Morning update, please. Then check email").unwrap(),
- "briefing Morning update"
- );
-}
-
-#[test]
-fn title_from_user_message_returns_none_for_empty_context() {
- assert!(title_from_user_message(" \n\t ").is_none());
- assert!(title_from_user_message("///").is_none());
-}
-
-// ── build_title_prompt ────────────────────────────────────────
-
-#[test]
-fn prompt_contains_both_messages_and_instruction() {
- let prompt = build_title_prompt("hello", "hi there");
- assert!(prompt.contains("First user message:\nhello"));
- assert!(prompt.contains("Assistant reply:\nhi there"));
- assert!(prompt.contains("Return the best thread name"));
-}
diff --git a/crates/openhuman-core/src/tools/impl/network/url_guard.rs b/crates/openhuman-core/src/tools/impl/network/url_guard.rs
index d00ea65861..ece3ad144d 100644
--- a/crates/openhuman-core/src/tools/impl/network/url_guard.rs
+++ b/crates/openhuman-core/src/tools/impl/network/url_guard.rs
@@ -1,366 +1,8 @@
-//! Shared URL validation + SSRF guards for outbound network tools.
-//!
-//! Used by `http_request`, `curl`, and any future tool that takes a
-//! user-supplied URL. Two allowlist modes:
-//!
-//! - **Open allowlist** (`allowed_domains` is empty): any public non-private
-//! host is permitted. All SSRF guards still apply (loopback / RFC1918 /
-//! link-local / multicast / documentation / shared-address /
-//! IPv4-mapped IPv6, `localhost` / `*.localhost` / `*.local`).
-//! - **Strict allowlist** (`allowed_domains` is non-empty): only the listed
-//! domains and their subdomains are permitted.
-//!
-//! Both modes enforce: http(s) only, no whitespace, no userinfo, no IPv6 hosts.
-//!
-//! **Alternate IP notations** (octal, hex, decimal): Rust's `IpAddr::parse`
-//! rejects them so they are treated as plain hostnames. In strict-allowlist
-//! mode they are rejected by the domain check. In open-allowlist mode they
-//! pass `validate_url` but are caught by `validate_url_with_dns_check`
-//! because they fail real-world DNS resolution.
-//!
-//! ## DNS Rebinding Protection
-//!
-//! Hostname validation alone is insufficient: an attacker can register a
-//! domain that alternates DNS responses between a public IP (passing the
-//! allowlist) and a private IP (e.g. 127.0.0.1). To close this gap,
-//! callers should use [`validate_url_with_dns_check`] which resolves the
-//! hostname and re-validates the resolved IPs before the request is made.
-
-use std::future::Future;
-use std::net::{IpAddr, ToSocketAddrs};
-
-/// Validate a URL against the allowlist + SSRF rules. Returns the
-/// original URL on success.
-pub fn validate_url(raw_url: &str, allowed_domains: &[String]) -> anyhow::Result<String> {
- let url = raw_url.trim();
-
- if url.is_empty() {
- anyhow::bail!("URL cannot be empty");
- }
-
- if url.chars().any(char::is_whitespace) {
- anyhow::bail!("URL cannot contain whitespace");
- }
-
- if !url.starts_with("http://") && !url.starts_with("https://") {
- anyhow::bail!("Only http:// and https:// URLs are allowed");
- }
-
- let host = extract_host(url)?;
-
- if is_private_or_local_host(&host) {
- log::debug!(
- "[url_guard] ssrf block: host={host} mode={}",
- if allowed_domains.is_empty() {
- "open"
- } else {
- "strict"
- }
- );
- anyhow::bail!("Blocked local/private host: {host}");
- }
-
- // Empty allowed_domains = open mode: any public non-private host is
- // permitted (same as ["*"]). This ensures the http_request tool works
- // out of the box regardless of whether the user configured an explicit
- // domain list, and keeps web-fetch consistent across routing paths.
- // A non-empty list = strict mode: only listed domains pass. (#2700)
- if !allowed_domains.is_empty() && !host_matches_allowlist(&host, allowed_domains) {
- log::debug!(
- "[url_guard] strict-allowlist rejection: host={host} allowed={:?}",
- allowed_domains
- );
- anyhow::bail!(
- "I'm not allowed to open '{host}' — it isn't in your allowed websites. \
- Add it (or turn on \"Allow all sites\") under \
- Settings → Advanced → Search engine → Allowed websites, then ask me again."
- );
- }
-
- log::debug!(
- "[url_guard] validate_url ok: host={host} mode={}",
- if allowed_domains.is_empty() {
- "open"
- } else {
- "strict"
- }
- );
-
- Ok(url.to_string())
-}
-
-/// Like [`validate_url`] but also resolves the hostname via DNS and
-/// verifies that none of the resolved IPs are private/local. This
-/// defends against DNS rebinding attacks where an attacker's domain
-/// initially resolves to a public IP (passing the allowlist) and then
-/// flips to 127.0.0.1 at request time.
-///
-/// Callers should use this function instead of `validate_url` in all
-/// paths that make outbound HTTP requests.
-pub(crate) async fn validate_url_with_dns_check(
- raw_url: &str,
- allowed_domains: &[String],
-) -> anyhow::Result<String> {
- validate_url_with_dns_check_with_resolver(raw_url, allowed_domains, resolve_host_ips).await
-}
-
-async fn validate_url_with_dns_check_with_resolver<F, Fut>(
- raw_url: &str,
- allowed_domains: &[String],
- resolver: F,
-) -> anyhow::Result<String>
-where
- F: FnOnce(String, u16) -> Fut,
- Fut: Future<Output = anyhow::Result<Vec<IpAddr>>>,
-{
- let url = validate_url(raw_url, allowed_domains)?;
-
- let host = extract_host(&url)?;
-
- // If the host is already a valid IP literal, `is_private_or_local_host`
- // has already checked it above. We only need DNS resolution for hostnames.
- if host.parse::<std::net::IpAddr>().is_ok() {
- return Ok(url);
- }
-
- let port = extract_port(&url)?;
- log::debug!("[url_guard] resolving DNS for host={host} port={port}");
- let addrs = resolver(host.clone(), port).await?;
-
- if addrs.is_empty() {
- anyhow::bail!("DNS resolution returned no addresses for '{host}'");
- }
-
- log::debug!("[url_guard] DNS resolved host={host} addrs={}", addrs.len());
-
- for addr in &addrs {
- let ip_str = addr.to_string();
- if is_private_or_local_host(&ip_str) {
- log::debug!("[url_guard] DNS rebinding blocked host={host} resolved_ip={ip_str}");
- anyhow::bail!(
- "DNS rebinding blocked: '{host}' resolved to private/local address {ip_str}"
- );
- }
- }
-
- Ok(url)
-}
-
-async fn resolve_host_ips(host: String, port: u16) -> anyhow::Result<Vec<IpAddr>> {
- let log_host = host.clone();
- tokio::task::spawn_blocking(move || {
- (host.as_str(), port)
- .to_socket_addrs()
- .map_err(|e| {
- log::debug!("[url_guard] DNS resolution failed host={host} port={port} error={e}");
- anyhow::anyhow!("DNS resolution failed for '{host}': {e}")
- })
- .map(|iter| iter.map(|addr| addr.ip()).collect())
- })
- .await
- .map_err(|e| {
- log::debug!("[url_guard] DNS resolution task failed host={log_host} port={port} error={e}");
- anyhow::anyhow!("DNS resolution task failed for '{log_host}': {e}")
- })?
-}
-
-pub fn normalize_allowed_domains(domains: Vec<String>) -> Vec<String> {
- if domains.is_empty() {
- return Vec::new();
- }
- let mut normalized = domains
- .into_iter()
- .filter_map(|d| normalize_domain(&d))
- .collect::<Vec<_>>();
- normalized.sort_unstable();
- normalized.dedup();
- if normalized.is_empty() {
- // All entries were malformed (whitespace-only, scheme-only, etc.) and
- // filtered out. Returning empty would silently enter open mode; instead
- // return a sentinel that keeps the tool in strict mode and rejects every
- // URL — fail-closed on misconfiguration. (#2738)
- log::warn!(
- "[url_guard] all configured allowed_domains entries are invalid — \
- treating as misconfigured allowlist (fail-closed)"
- );
- return vec!["<misconfigured-allowlist>".to_string()];
- }
- normalized
-}
-
-pub fn normalize_domain(raw: &str) -> Option<String> {
- let mut d = raw.trim().to_lowercase();
- if d.is_empty() {
- return None;
- }
-
- if let Some(stripped) = d.strip_prefix("https://") {
- d = stripped.to_string();
- } else if let Some(stripped) = d.strip_prefix("http://") {
- d = stripped.to_string();
- }
-
- if let Some((host, _)) = d.split_once('/') {
- d = host.to_string();
- }
-
- d = d.trim_start_matches('.').trim_end_matches('.').to_string();
-
- if let Some((host, _)) = d.split_once(':') {
- d = host.to_string();
- }
-
- if d.is_empty() || d.chars().any(char::is_whitespace) {
- return None;
- }
-
- Some(d)
-}
-
-pub fn extract_host(url: &str) -> anyhow::Result<String> {
- let rest = url
- .strip_prefix("http://")
- .or_else(|| url.strip_prefix("https://"))
- .ok_or_else(|| anyhow::anyhow!("Only http:// and https:// URLs are allowed"))?;
-
- let authority = rest
- .split(['/', '?', '#'])
- .next()
- .ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
-
- if authority.is_empty() {
- anyhow::bail!("URL must include a host");
- }
-
- if authority.contains('@') {
- anyhow::bail!("URL userinfo is not allowed");
- }
-
- if authority.starts_with('[') {
- anyhow::bail!("IPv6 hosts are not supported in http_request");
- }
-
- let host = authority
- .split(':')
- .next()
- .unwrap_or_default()
- .trim()
- .trim_end_matches('.')
- .to_lowercase();
-
- if host.is_empty() {
- anyhow::bail!("URL must include a valid host");
- }
-
- Ok(host)
-}
-
-pub fn extract_port(url: &str) -> anyhow::Result<u16> {
- let is_http = url.starts_with("http://");
- let rest = url
- .strip_prefix("http://")
- .or_else(|| url.strip_prefix("https://"))
- .ok_or_else(|| anyhow::anyhow!("Only http:// and https:// URLs are allowed"))?;
-
- let authority = rest
- .split(['/', '?', '#'])
- .next()
- .ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
-
- if authority.starts_with('[') {
- anyhow::bail!("IPv6 hosts are not supported in http_request");
- }
-
- if let Some((_, port)) = authority.rsplit_once(':') {
- if port.is_empty() || !port.chars().all(|ch| ch.is_ascii_digit()) {
- anyhow::bail!("URL port must be numeric");
- }
- return port
- .parse::<u16>()
- .map_err(|_| anyhow::anyhow!("URL port is out of range"));
- }
-
- Ok(if is_http { 80 } else { 443 })
-}
-
-pub fn host_matches_allowlist(host: &str, allowed_domains: &[String]) -> bool {
- allowed_domains.iter().any(|domain| {
- // `"*"` is the explicit allow-all wildcard (the "Allow all sites"
- // toggle), mirroring the browser tool. Local/private hosts are still
- // rejected upstream by `is_private_or_local_host`, so a wildcard only
- // opens *public* hosts, never the loopback/RFC1918 SSRF surface.
- domain == "*"
- || host == domain
- || host
- .strip_suffix(domain)
- .is_some_and(|prefix| prefix.ends_with('.'))
- })
-}
-
-pub fn is_private_or_local_host(host: &str) -> bool {
- let unbracketed = host
- .strip_prefix('[')
- .and_then(|h| h.strip_suffix(']'))
- .unwrap_or(host);
- let bare = unbracketed.strip_suffix('.').unwrap_or(unbracketed);
-
- let lower = bare.to_ascii_lowercase();
-
- let has_local_tld = lower
- .rsplit('.')
- .next()
- .is_some_and(|label| label == "local");
-
- if lower == "localhost" || lower.ends_with(".localhost") || has_local_tld {
- return true;
- }
-
- if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
- return match ip {
- std::net::IpAddr::V4(v4) => is_non_global_v4(v4),
- std::net::IpAddr::V6(v6) => is_non_global_v6(v6),
- };
- }
-
- false
-}
-
-pub fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
- let [a, b, c, _] = v4.octets();
- v4.is_loopback()
- || v4.is_private()
- || v4.is_link_local()
- || v4.is_unspecified()
- || v4.is_broadcast()
- || v4.is_multicast()
- || (a == 100 && (64..=127).contains(&b))
- || a >= 240
- || (a == 192 && b == 0 && c == 0)
- || (a == 192 && b == 88 && c == 99)
- || (a == 198 && b == 51 && c == 100)
- || (a == 203 && b == 0 && c == 113)
- || (a == 198 && (18..=19).contains(&b))
- // 0.0.0.0/8 — "this network" (RFC 1122 §3.2.1.3). `is_unspecified()` only
- // covers 0.0.0.0 itself, but the whole /8 routes to the local host on
- // Linux. Carried over from the `ops_install` copy this replaces.
- || a == 0
-}
-
-pub fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
- let segs = v6.segments();
- v6.is_loopback()
- || v6.is_unspecified()
- || v6.is_multicast()
- || (segs[0] & 0xfe00) == 0xfc00
- || (segs[0] & 0xffc0) == 0xfe80
- || (segs[0] == 0x2001 && segs[1] == 0x0db8)
- || (segs[0] == 0x0100 && segs[1] == 0 && segs[2] == 0 && segs[3] <= 1)
- || (segs[0] == 0x2001 && segs[1] == 0x0002 && segs[2] == 0)
- || (segs[0] & 0xfff0) == 0x3ff0
- || segs[0] == 0x5f00
- || v6.to_ipv4_mapped().is_some_and(is_non_global_v4)
-}
-
-#[cfg(test)]
-#[path = "url_guard_tests.rs"]
-mod tests;
+//! Shared URL validation + SSRF guards for outbound network tools; the
+//! implementation lives in [`tinytools_std::url_guard`].
+
+pub use tinytools_std::url_guard::{
+ extract_host, extract_port, host_matches_allowlist, is_non_global_v4, is_non_global_v6,
+ is_private_or_local_host, normalize_allowed_domains, normalize_domain, validate_url,
+ validate_url_with_dns_check,
+};
diff --git a/crates/openhuman-core/src/tools/impl/network/url_guard_tests.rs b/crates/openhuman-core/src/tools/impl/network/url_guard_tests.rs
deleted file mode 100644
index 5fe0a8f584..0000000000
--- a/crates/openhuman-core/src/tools/impl/network/url_guard_tests.rs
+++ /dev/null
@@ -1,581 +0,0 @@
-use super::*;
-
-#[test]
-fn normalize_domain_strips_scheme_path_and_case() {
- let got = normalize_domain(" HTTPS://Docs.Example.com/path ").unwrap();
- assert_eq!(got, "docs.example.com");
-}
-
-#[test]
-fn normalize_allowed_domains_deduplicates() {
- let got = normalize_allowed_domains(vec![
- "example.com".into(),
- "EXAMPLE.COM".into(),
- "https://example.com/".into(),
- ]);
- assert_eq!(got, vec!["example.com".to_string()]);
-}
-
-#[test]
-fn validate_accepts_exact_domain() {
- let allow = vec!["example.com".to_string()];
- let got = validate_url("https://example.com/docs", &allow).unwrap();
- assert_eq!(got, "https://example.com/docs");
-}
-
-#[test]
-fn validate_accepts_http() {
- let allow = vec!["example.com".to_string()];
- assert!(validate_url("http://example.com", &allow).is_ok());
-}
-
-#[test]
-fn validate_accepts_subdomain() {
- let allow = vec!["example.com".to_string()];
- assert!(validate_url("https://api.example.com/v1", &allow).is_ok());
-}
-
-#[test]
-fn validate_rejects_allowlist_miss() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("https://google.com", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("allowed websites"));
-}
-
-#[test]
-fn validate_wildcard_allows_any_public_host() {
- let allow = vec!["*".to_string()];
- assert!(validate_url("https://example.com/docs", &allow).is_ok());
- assert!(validate_url("https://www.cnbc.com/markets", &allow).is_ok());
- assert!(validate_url("https://sub.deep.example.org", &allow).is_ok());
-}
-
-#[test]
-fn validate_wildcard_still_blocks_local_and_private() {
- // "Allow all sites" must NOT defeat the SSRF guard.
- let allow = vec!["*".to_string()];
- assert!(validate_url("https://localhost:8080", &allow)
- .unwrap_err()
- .to_string()
- .contains("local/private"));
- assert!(validate_url("https://192.168.1.5", &allow)
- .unwrap_err()
- .to_string()
- .contains("local/private"));
-}
-
-#[test]
-fn validate_rejects_localhost() {
- let allow = vec!["localhost".to_string()];
- let err = validate_url("https://localhost:8080", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"));
-}
-
-#[test]
-fn validate_rejects_private_ipv4() {
- let allow = vec!["192.168.1.5".to_string()];
- let err = validate_url("https://192.168.1.5", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"));
-}
-
-#[test]
-fn validate_rejects_whitespace() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("https://example.com/hello world", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("whitespace"));
-}
-
-#[test]
-fn validate_rejects_userinfo() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("https://[email protected]", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("userinfo"));
-}
-
-// Empty allowed_domains = open mode: any public host is permitted.
-// This keeps web-fetch working when no domain list is configured and
-// makes behaviour consistent between default and external-LLM routing.
-// (#2700)
-#[test]
-fn validate_empty_allowlist_allows_public_host() {
- assert!(validate_url("https://example.com", &[]).is_ok());
- assert!(validate_url("https://www.cnbc.com/markets", &[]).is_ok());
-}
-
-#[test]
-fn validate_empty_allowlist_still_blocks_private_hosts() {
- let err = validate_url("https://192.168.1.5", &[])
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"));
-
- let err = validate_url("https://localhost", &[])
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"));
-}
-
-// ── normalize_allowed_domains: fail-closed on malformed-only input ──
-
-#[test]
-fn normalize_all_invalid_entries_stays_fail_closed() {
- // A non-empty list that fully normalizes to nothing must NOT produce
- // an empty slice (which would silently enter open mode). (#2738)
- let got = normalize_allowed_domains(vec![" ".into(), "https://".into()]);
- assert!(
- !got.is_empty(),
- "normalized result must be non-empty to stay in strict mode"
- );
- // The sentinel must not match any real public host.
- assert!(
- !host_matches_allowlist("example.com", &got),
- "sentinel must not grant access to real hosts"
- );
- assert!(
- !host_matches_allowlist("api.example.com", &got),
- "sentinel must not grant access to subdomains"
- );
-}
-
-#[test]
-fn normalize_empty_input_stays_empty_for_open_mode() {
- // Explicitly empty input should return empty (open mode is intentional).
- assert!(normalize_allowed_domains(vec![]).is_empty());
-}
-
-#[tokio::test]
-async fn dns_check_with_empty_allowlist_allows_public_resolved_host() {
- // Open mode (empty allowlist) must still pass DNS check for public IPs.
- let got = validate_url_with_dns_check_with_resolver(
- "https://example.com",
- &[],
- |host, port| async move {
- assert_eq!(host, "example.com");
- assert_eq!(port, 443);
- Ok(vec!["93.184.216.34".parse().unwrap()])
- },
- )
- .await
- .unwrap();
- assert_eq!(got, "https://example.com");
-}
-
-#[tokio::test]
-async fn dns_check_with_empty_allowlist_blocks_private_resolved_ip() {
- // Even in open mode, DNS rebinding to a private IP must be blocked.
- let err = validate_url_with_dns_check_with_resolver("https://example.com", &[], |_, _| async {
- Ok(vec!["10.0.0.1".parse().unwrap()])
- })
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("DNS rebinding blocked"));
-}
-
-#[tokio::test]
-async fn dns_check_resolver_failure_is_a_refusal_not_a_pass_through() {
- // A resolver error (NXDOMAIN, network down, timeout) must refuse the
- // fetch, not fall back to treating the host as unresolved-and-therefore-
- // allowed.
- let err = validate_url_with_dns_check_with_resolver(
- "https://this-host-does-not-exist.invalid",
- &[],
- |host, _port| async move { anyhow::bail!("DNS resolution failed for '{host}': NXDOMAIN") },
- )
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("DNS resolution failed"));
-}
-
-#[tokio::test]
-async fn dns_check_resolver_returning_no_addresses_is_a_refusal() {
- // A resolver that answers with zero addresses (some stub resolvers do
- // this instead of erroring) must not be treated as "no IPs to check,
- // therefore allowed".
- let err = validate_url_with_dns_check_with_resolver("https://example.com", &[], |_, _| async {
- Ok(Vec::new())
- })
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("DNS resolution returned no addresses"));
-}
-
-#[test]
-fn validate_rejects_ftp_scheme() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("ftp://example.com", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("http://") || err.contains("https://"));
-}
-
-#[test]
-fn validate_rejects_empty_url() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("", &allow).unwrap_err().to_string();
- assert!(err.contains("empty"));
-}
-
-#[test]
-fn validate_rejects_ipv6_host() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url("http://[::1]:8080/path", &allow)
- .unwrap_err()
- .to_string();
- assert!(err.contains("IPv6"));
-}
-
-#[test]
-fn blocks_multicast_ipv4() {
- assert!(is_private_or_local_host("224.0.0.1"));
- assert!(is_private_or_local_host("239.255.255.255"));
-}
-
-#[test]
-fn blocks_broadcast() {
- assert!(is_private_or_local_host("255.255.255.255"));
-}
-
-#[test]
-fn blocks_reserved_ipv4() {
- assert!(is_private_or_local_host("240.0.0.1"));
- assert!(is_private_or_local_host("250.1.2.3"));
-}
-
-#[test]
-fn blocks_documentation_ranges() {
- // TEST-NET-1 is globally routable in this policy; only TEST-NET-2 and
- // TEST-NET-3 are classified as non-global here.
- assert!(!is_private_or_local_host("192.0.2.1"));
- assert!(is_private_or_local_host("198.51.100.1"));
- assert!(is_private_or_local_host("203.0.113.1"));
-}
-
-#[test]
-fn blocks_benchmarking_range() {
- assert!(is_private_or_local_host("198.18.0.1"));
- assert!(is_private_or_local_host("198.19.255.255"));
-}
-
-#[test]
-fn blocks_ipv6_localhost() {
- assert!(is_private_or_local_host("::1"));
- assert!(is_private_or_local_host("[::1]"));
-}
-
-#[test]
-fn blocks_ipv6_multicast() {
- assert!(is_private_or_local_host("ff02::1"));
-}
-
-#[test]
-fn blocks_ipv6_link_local() {
- assert!(is_private_or_local_host("fe80::1"));
-}
-
-#[test]
-fn blocks_ipv6_unique_local() {
- assert!(is_private_or_local_host("fd00::1"));
-}
-
-#[test]
-fn blocks_ipv4_mapped_ipv6() {
- assert!(is_private_or_local_host("::ffff:127.0.0.1"));
- assert!(is_private_or_local_host("::ffff:192.168.1.1"));
- assert!(is_private_or_local_host("::ffff:10.0.0.1"));
-}
-
-#[test]
-fn allows_public_ipv4() {
- assert!(!is_private_or_local_host("8.8.8.8"));
- assert!(!is_private_or_local_host("1.1.1.1"));
- assert!(!is_private_or_local_host("93.184.216.34"));
-}
-
-#[test]
-fn blocks_ipv6_documentation_range() {
- assert!(is_private_or_local_host("2001:db8::1"));
-}
-
-#[test]
-fn allows_public_ipv6() {
- assert!(!is_private_or_local_host("2607:f8b0:4004:800::200e"));
-}
-
-#[test]
-fn blocks_shared_address_space() {
- assert!(is_private_or_local_host("100.64.0.1"));
- assert!(is_private_or_local_host("100.127.255.255"));
- assert!(!is_private_or_local_host("100.63.0.1"));
- assert!(!is_private_or_local_host("100.128.0.1"));
-}
-
-#[test]
-fn ssrf_blocks_loopback_127_range() {
- assert!(is_private_or_local_host("127.0.0.1"));
- assert!(is_private_or_local_host("127.0.0.2"));
- assert!(is_private_or_local_host("127.255.255.255"));
-}
-
-#[test]
-fn ssrf_blocks_rfc1918_10_range() {
- assert!(is_private_or_local_host("10.0.0.1"));
- assert!(is_private_or_local_host("10.255.255.255"));
-}
-
-#[test]
-fn ssrf_blocks_rfc1918_172_range() {
- assert!(is_private_or_local_host("172.16.0.1"));
- assert!(is_private_or_local_host("172.31.255.255"));
-}
-
-#[test]
-fn ssrf_blocks_unspecified_address() {
- assert!(is_private_or_local_host("0.0.0.0"));
-}
-
-#[test]
-fn ssrf_blocks_dot_localhost_subdomain() {
- assert!(is_private_or_local_host("evil.localhost"));
- assert!(is_private_or_local_host("a.b.localhost"));
-}
-
-#[test]
-fn ssrf_blocks_dot_local_tld() {
- assert!(is_private_or_local_host("service.local"));
-}
-
-#[test]
-fn ssrf_ipv6_unspecified() {
- assert!(is_private_or_local_host("::"));
-}
-
-// ── Defense-in-depth: alternate IP notations rejected by allowlist
-//
-// Rust's IpAddr::parse() rejects octal, hex, decimal, and
-// zero-padded notations. They fall through as hostnames and get
-// rejected by the allowlist instead. These tests pin that
-// behaviour so a parser change can't silently re-open SSRF.
-
-#[test]
-fn ssrf_octal_loopback_not_parsed_as_ip() {
- assert!(!is_private_or_local_host("0177.0.0.1"));
-}
-
-#[test]
-fn ssrf_hex_loopback_not_parsed_as_ip() {
- assert!(!is_private_or_local_host("0x7f000001"));
-}
-
-#[test]
-fn ssrf_decimal_loopback_not_parsed_as_ip() {
- assert!(!is_private_or_local_host("2130706433"));
-}
-
-#[test]
-fn ssrf_zero_padded_loopback_not_parsed_as_ip() {
- assert!(!is_private_or_local_host("127.000.000.001"));
-}
-
-#[test]
-fn ssrf_alternate_notations_rejected_by_validate_url() {
- let allow = vec!["example.com".to_string()];
- for notation in [
- "http://0177.0.0.1",
- "http://0x7f000001",
- "http://2130706433",
- "http://127.000.000.001",
- ] {
- let err = validate_url(notation, &allow).unwrap_err().to_string();
- assert!(
- err.contains("allowed websites"),
- "Expected allowlist rejection for {notation}, got: {err}"
- );
- }
-}
-
-// ── DNS rebinding protection ─────────────────────────────────
-
-#[tokio::test]
-async fn dns_check_blocks_localhost_resolution() {
- // "localhost" resolves to 127.0.0.1 on most systems. Even if
- // someone adds it to the allowlist, the DNS check should block it.
- let allow = vec!["localhost".to_string()];
- // validate_url itself already blocks "localhost" via the hostname check,
- // but validate_url_with_dns_check should also catch it.
- let err = validate_url_with_dns_check("https://localhost", &allow)
- .await
- .unwrap_err()
- .to_string();
- assert!(
- err.contains("local/private") || err.contains("rebinding"),
- "Expected SSRF block for localhost, got: {err}"
- );
-}
-
-#[tokio::test]
-async fn dns_check_passes_for_public_resolved_ip() {
- let allow = vec!["example.com".to_string()];
- let got = validate_url_with_dns_check_with_resolver(
- "https://example.com",
- &allow,
- |host, port| async move {
- assert_eq!(host, "example.com");
- assert_eq!(port, 443);
- Ok(vec!["93.184.216.34".parse().unwrap()])
- },
- )
- .await
- .unwrap();
- assert_eq!(got, "https://example.com");
-}
-
-#[tokio::test]
-async fn dns_check_blocks_private_resolved_ip() {
- let allow = vec!["example.com".to_string()];
- let err =
- validate_url_with_dns_check_with_resolver("https://example.com", &allow, |_, _| async {
- Ok(vec!["127.0.0.1".parse().unwrap()])
- })
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("DNS rebinding blocked"));
-}
-
-#[tokio::test]
-async fn dns_check_uses_explicit_port_for_resolution() {
- let allow = vec!["api.example.com".to_string()];
- let got = validate_url_with_dns_check_with_resolver(
- "http://api.example.com:8080/status",
- &allow,
- |host, port| async move {
- assert_eq!(host, "api.example.com");
- assert_eq!(port, 8080);
- Ok(vec!["93.184.216.34".parse().unwrap()])
- },
- )
- .await
- .unwrap();
- assert_eq!(got, "http://api.example.com:8080/status");
-}
-
-#[tokio::test]
-async fn dns_check_returns_resolver_failure() {
- let allow = vec!["example.com".to_string()];
- let err = validate_url_with_dns_check_with_resolver(
- "https://example.com",
- &allow,
- |host, _| async move {
- anyhow::bail!("DNS resolution failed for '{host}': resolver unavailable")
- },
- )
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("DNS resolution failed"));
-}
-
-#[tokio::test]
-async fn dns_check_rejects_ip_literal_private() {
- let allow = vec!["10.0.0.1".to_string()];
- let err = validate_url_with_dns_check("https://10.0.0.1", &allow)
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"));
-}
-
-#[test]
-fn wildcard_allows_any_host() {
- let any = vec!["*".to_string()];
- assert!(host_matches_allowlist("docs.rs", &any));
- assert!(host_matches_allowlist("api.github.com", &any));
- assert!(host_matches_allowlist("whatever.example.org", &any));
-}
-
-#[tokio::test]
-async fn wildcard_still_blocks_private_hosts() {
- // `*` opens public hosts only — SSRF block on private/local hosts stays.
- let any = vec!["*".to_string()];
- let err = validate_url_with_dns_check("https://127.0.0.1", &any)
- .await
- .unwrap_err()
- .to_string();
- assert!(err.contains("local/private"), "got: {err}");
-}
-
-#[test]
-fn exported_ssrf_predicates_classify_non_global_ips_accurately() {
- use std::net::{Ipv4Addr, Ipv6Addr};
-
- // IPv4 Non-global checks
- assert!(is_non_global_v4(Ipv4Addr::new(127, 0, 0, 1)));
- assert!(is_non_global_v4(Ipv4Addr::new(10, 0, 0, 1)));
- assert!(is_non_global_v4(Ipv4Addr::new(172, 16, 0, 1)));
- assert!(is_non_global_v4(Ipv4Addr::new(192, 168, 1, 1)));
- assert!(is_non_global_v4(Ipv4Addr::new(169, 254, 1, 1)));
- assert!(is_non_global_v4(Ipv4Addr::new(100, 64, 0, 1))); // CGNAT
- assert!(is_non_global_v4(Ipv4Addr::new(240, 0, 0, 1))); // Class E
- assert!(!is_non_global_v4(Ipv4Addr::new(192, 0, 2, 1))); // TEST-NET-1 is globally routable in this policy
- assert!(is_non_global_v4(Ipv4Addr::new(198, 51, 100, 1))); // TEST-NET-2
- assert!(is_non_global_v4(Ipv4Addr::new(203, 0, 113, 1))); // TEST-NET-3
- assert!(is_non_global_v4(Ipv4Addr::new(192, 88, 99, 1))); // 6to4 anycast
- assert!(is_non_global_v4(Ipv4Addr::new(0, 0, 0, 0))); // 0.0.0.0/8
- assert!(is_non_global_v4(Ipv4Addr::new(0, 1, 2, 3))); // 0.0.0.0/8
-
- // IPv4 Global public IPs
- assert!(!is_non_global_v4(Ipv4Addr::new(8, 8, 8, 8)));
- assert!(!is_non_global_v4(Ipv4Addr::new(1, 1, 1, 1)));
- assert!(!is_non_global_v4(Ipv4Addr::new(140, 82, 121, 4)));
- // Non-TEST-NET IPs in adjacent /24 blocks should not be classified as non-global
- assert!(!is_non_global_v4(Ipv4Addr::new(198, 51, 1, 1)));
- assert!(!is_non_global_v4(Ipv4Addr::new(203, 0, 1, 1)));
- assert!(!is_non_global_v4(Ipv4Addr::new(192, 88, 98, 1)));
-
- // IPv6 Non-global checks
- assert!(is_non_global_v6(Ipv6Addr::LOCALHOST));
- assert!(is_non_global_v6(Ipv6Addr::UNSPECIFIED));
- assert!(is_non_global_v6("fc00::1".parse().unwrap()));
- assert!(is_non_global_v6("fe80::1".parse().unwrap()));
- assert!(is_non_global_v6("2001:db8::1".parse().unwrap()));
- assert!(is_non_global_v6("100::1".parse().unwrap()));
- assert!(is_non_global_v6("100:0:0:1::1".parse().unwrap()));
- assert!(is_non_global_v6("2001:2::1".parse().unwrap()));
- assert!(is_non_global_v6("3fff::1".parse().unwrap()));
- assert!(is_non_global_v6("5f00::1".parse().unwrap()));
-
- // IPv6 Global public IPs
- assert!(!is_non_global_v6("2606:4700:4700::1111".parse().unwrap()));
- assert!(!is_non_global_v6("101::1".parse().unwrap()));
- assert!(!is_non_global_v6("100:0:0:2::1".parse().unwrap()));
- assert!(!is_non_global_v6("2001:3::1".parse().unwrap()));
- assert!(!is_non_global_v6("4000::1".parse().unwrap()));
- assert!(!is_non_global_v6("5f01::1".parse().unwrap()));
-
- // Host helper checks (including ASCII case-insensitivity and trailing dot)
- assert!(is_private_or_local_host("localhost"));
- assert!(is_private_or_local_host("LOCALHOST"));
- assert!(is_private_or_local_host("localhost."));
- assert!(is_private_or_local_host("my-service.localhost"));
- assert!(is_private_or_local_host("MY-SERVICE.LOCALHOST"));
- assert!(is_private_or_local_host("device.local"));
- assert!(is_private_or_local_host("DEVICE.LOCAL"));
- assert!(is_private_or_local_host("device.local."));
- assert!(is_private_or_local_host("127.0.0.1"));
- assert!(is_private_or_local_host("[::1]"));
- assert!(!is_private_or_local_host("github.com"));
- assert!(!is_private_or_local_host("api.openai.com"));
-}
diff --git a/crates/openhuman-core/src/tools/impl/system/command_output.rs b/crates/openhuman-core/src/tools/impl/system/command_output.rs
index c8ebb2a5bc..7361b3bcc9 100644
--- a/crates/openhuman-core/src/tools/impl/system/command_output.rs
+++ b/crates/openhuman-core/src/tools/impl/system/command_output.rs
@@ -1,96 +1,4 @@
-//! Shared output formatting for the shell-family command tools (`shell`,
-//! `node_exec`, `npm_exec`).
-//!
-//! # Why this exists (code_executor no-progress loop, #4095)
-//!
-//! Each shell-family tool previously formatted a FAILED command as
-//! `if stderr.is_empty() { stdout } else { stderr }` with no exit code. That
-//! lost the two signals the agent most needs to recover:
-//!
-//! 1. **stdout was dropped whenever stderr was non-empty.** Compilers, test
-//! runners and linters routinely write diagnostics to stdout; the model
-//! saw only stderr and lost half the failure context.
-//! 2. **the exit code was never surfaced.** The model could not tell a `127`
-//! (command / dependency not found) or a `126` (permission denied — often a
-//! sandbox restriction) from a generic `1`, so it could not recognise an
-//! un-retryable wall and re-ran the identical command. The harness
-//! repeated-failure circuit breaker (`RepeatedToolFailureMiddleware`, see
-//! `crates/openhuman-core/src/agent/tinyagents/middleware.rs`) still bounds that loop, but
-//! only after a few wasted iterations and with a generic halt message,
-//! because the root-cause signal had already been thrown away.
-//!
-//! This module surfaces the exit code AND both streams on failure, and appends a
-//! short hint for the well-known dependency/sandbox exit codes so the agent can
-//! adapt (install/declare the dependency, request escalation, or report the
-//! blocker) instead of retrying blindly. The success path is intentionally left
-//! as raw stdout so existing callers that parse a command's output (e.g. `pwd`)
-//! keep working unchanged.
+//! Shared failure rendering for the shell-family command tools; the
+//! implementation lives in [`tinytools_std::command_output`].
-use tinytools::ToolResult;
-
-/// Hint appended after the exit code for the exit statuses that almost always
-/// mean "this exact command cannot succeed on retry here". Empty for every other
-/// code so an ordinary application failure is never editorialised.
-fn exit_code_hint(code: i32) -> &'static str {
- match code {
- 127 => {
- " — command not found: a required executable or dependency is \
- missing or not on PATH. Install/declare it, use an available \
- alternative, or report the blocker — do NOT re-run the same command"
- }
- 126 => {
- " — permission denied or not executable: often a sandbox \
- restriction. This will not succeed on retry — report the blocker \
- or request escalation instead of repeating the command"
- }
- _ => "",
- }
-}
-
-/// Render a finished command's exit status + captured streams into the text the
-/// model sees on FAILURE. Never drops a non-empty stream; always states the exit
-/// code (or that the process was terminated by a signal).
-pub(crate) fn render_command_failure(exit_code: Option<i32>, stdout: &str, stderr: &str) -> String {
- let mut out = match exit_code {
- Some(code) => format!("Command failed (exit code {code}{})", exit_code_hint(code)),
- None => "Command failed (terminated by a signal — no exit code)".to_string(),
- };
- let stdout = stdout.trim_end();
- let stderr = stderr.trim_end();
- if !stdout.is_empty() {
- out.push_str("\n[stdout]\n");
- out.push_str(stdout);
- }
- if !stderr.is_empty() {
- out.push_str("\n[stderr]\n");
- out.push_str(stderr);
- }
- if stdout.is_empty() && stderr.is_empty() {
- out.push_str("\n(no output was captured on stdout or stderr)");
- }
- out
-}
-
-/// A `ToolResult::error` carrying [`render_command_failure`]. The single failure
-/// constructor shared by every shell-family tool, on both the native and the
-/// sandboxed execution path, so the surfaced shape can't drift between them.
-pub(crate) fn command_failure(exit_code: Option<i32>, stdout: &str, stderr: &str) -> ToolResult {
- ToolResult::error(render_command_failure(exit_code, stdout, stderr))
-}
-
-/// Normalise a sandbox backend's `exit_code` into the `Option<i32>` the
-/// formatter expects. The sandbox layer uses `-1` as its sentinel for
-/// "terminated / no real exit code" (see `sandbox::types::SandboxExecResult`);
-/// map any negative value to `None` so it renders as a signal termination rather
-/// than the literal `exit code -1`.
-pub(crate) fn sandbox_exit_code(code: i32) -> Option<i32> {
- if code < 0 {
- None
- } else {
- Some(code)
- }
-}
-
-#[cfg(test)]
-#[path = "command_output_tests.rs"]
-mod tests;
+pub(crate) use tinytools_std::command_output::{command_failure, sandbox_exit_code};
diff --git a/crates/openhuman-core/src/tools/impl/system/command_output_tests.rs b/crates/openhuman-core/src/tools/impl/system/command_output_tests.rs
deleted file mode 100644
index 3803978f58..0000000000
--- a/crates/openhuman-core/src/tools/impl/system/command_output_tests.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-use super::*;
-
-#[test]
-fn failure_surfaces_exit_code_and_both_streams() {
- let rendered = render_command_failure(Some(7), "the-stdout-line", "the-stderr-line");
- assert!(
- rendered.contains("exit code 7"),
- "exit code missing: {rendered}"
- );
- assert!(
- rendered.contains("the-stdout-line"),
- "stdout dropped on failure: {rendered}"
- );
- assert!(
- rendered.contains("the-stderr-line"),
- "stderr dropped on failure: {rendered}"
- );
-}
-
-#[test]
-fn failure_keeps_stdout_even_when_stderr_present() {
- // The exact regression: the old `if stderr.is_empty() { stdout } else
- // { stderr }` formatting threw stdout away whenever stderr existed.
- let rendered = render_command_failure(Some(1), "diagnostic-on-stdout", "error-on-stderr");
- assert!(rendered.contains("diagnostic-on-stdout"));
- assert!(rendered.contains("error-on-stderr"));
-}
-
-#[test]
-fn exit_127_hints_missing_command_or_dependency() {
- let rendered = render_command_failure(Some(127), "", "pytest: command not found");
- assert!(rendered.contains("exit code 127"));
- assert!(
- rendered.to_lowercase().contains("command not found"),
- "127 should hint at a missing command/dependency: {rendered}"
- );
-}
-
-#[test]
-fn exit_126_hints_permission_or_sandbox() {
- let rendered = render_command_failure(Some(126), "", "permission denied");
- assert!(rendered.contains("exit code 126"));
- assert!(
- rendered.to_lowercase().contains("sandbox")
- || rendered.to_lowercase().contains("permission denied"),
- "126 should hint at a permission/sandbox wall: {rendered}"
- );
-}
-
-#[test]
-fn ordinary_failure_code_gets_no_hint() {
- let rendered = render_command_failure(Some(1), "", "boom");
- // No editorialising for a generic application failure.
- assert!(rendered.contains("exit code 1"));
- assert!(!rendered.contains("command not found"));
- assert!(!rendered.contains("sandbox"));
-}
-
-#[test]
-fn signal_termination_has_no_exit_code() {
- let rendered = render_command_failure(None, "", "");
- assert!(rendered.contains("terminated by a signal"));
- assert!(rendered.contains("no output was captured"));
-}
-
-#[test]
-fn sandbox_negative_exit_code_maps_to_signal() {
- assert_eq!(sandbox_exit_code(-1), None);
- assert_eq!(sandbox_exit_code(0), Some(0));
- assert_eq!(sandbox_exit_code(7), Some(7));
-}
diff --git a/crates/openhuman-core/src/tools/impl/system/detect_tools.rs b/crates/openhuman-core/src/tools/impl/system/detect_tools.rs
index b251e5adc3..05b4d4b13f 100644
--- a/crates/openhuman-core/src/tools/impl/system/detect_tools.rs
+++ b/crates/openhuman-core/src/tools/impl/system/detect_tools.rs
@@ -1,149 +1,5 @@
-//! Tool: detect_tools — report which developer toolchains are installed on PATH.
-//!
-//! Lets the agent ground its plans in what the host actually has rather than
-//! assuming. Read-only: it only scans `$PATH` for executables (no subprocesses,
-//! no writes), so it is safe in every access mode.
+//! `detect_tools` and PATH probing; the implementation lives in
+//! [`tinytools_std::detect_tools`].
-use async_trait::async_trait;
-use serde_json::json;
-use std::path::PathBuf;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// Common developer tools probed when the caller doesn't specify a list.
-const DEFAULT_CANDIDATES: &[&str] = &[
- "node", "npm", "npx", "pnpm", "yarn", "bun", "deno", "python3", "python", "pip3", "pip", "uv",
- "pipx", "cargo", "rustc", "go", "gcc", "cc", "clang", "make", "git", "gh", "docker", "podman",
- "kubectl", "rg", "jq", "fd", "curl", "wget",
-];
-
-pub struct DetectToolsTool;
-
-impl DetectToolsTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for DetectToolsTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Locate `name` on `$PATH`, honoring `PATHEXT` on Windows. Returns the first
-/// matching executable path, or `None` if not found.
-pub(crate) fn find_on_path(name: &str) -> Option<PathBuf> {
- let path = std::env::var_os("PATH")?;
- let exts: Vec<String> = if cfg!(windows) {
- std::env::var("PATHEXT")
- .unwrap_or_else(|_| ".EXE;.CMD;.BAT".to_string())
- .split(';')
- .map(|s| s.to_string())
- .collect()
- } else {
- vec![String::new()]
- };
- for dir in std::env::split_paths(&path) {
- for ext in &exts {
- let candidate = dir.join(format!("{name}{ext}"));
- if candidate.is_file() {
- // On Unix a plain `is_file()` can match a non-executable file and
- // falsely report the tool as available; require the exec bit.
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- let is_exec = std::fs::metadata(&candidate)
- .map(|m| m.permissions().mode() & 0o111 != 0)
- .unwrap_or(false);
- if is_exec {
- return Some(candidate);
- }
- }
- #[cfg(not(unix))]
- {
- return Some(candidate);
- }
- }
- }
- }
- None
-}
-
-#[async_trait]
-impl Tool for DetectToolsTool {
- fn name(&self) -> &str {
- "detect_tools"
- }
-
- fn description(&self) -> &str {
- "Detect which developer tools / language runtimes are installed on the host PATH \
- (e.g. node, python3, cargo, docker, git, rg). Use this before assuming a tool \
- exists or before proposing to install one. Read-only — scans PATH only."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "tools": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Optional list of tool names to probe. If omitted, a default \
- catalog of common developer tools is probed."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let requested: Vec<String> = args
- .get("tools")
- .and_then(|v| v.as_array())
- .map(|a| {
- a.iter()
- .filter_map(|x| x.as_str().map(str::to_string))
- .collect()
- })
- .unwrap_or_default();
- let candidates: Vec<String> = if requested.is_empty() {
- DEFAULT_CANDIDATES
- .iter()
- .map(|s| (*s).to_string())
- .collect()
- } else {
- requested
- };
-
- let mut available = Vec::new();
- let mut missing = Vec::new();
- for name in &candidates {
- match find_on_path(name) {
- Some(p) => available.push(json!({
- "name": name,
- "path": p.to_string_lossy(),
- })),
- None => missing.push(name.clone()),
- }
- }
-
- tracing::debug!(
- probed = candidates.len(),
- available = available.len(),
- "[detect_tools] PATH scan complete"
- );
- let payload = json!({
- "available": available,
- "missing": missing,
- "probed": candidates.len(),
- });
- Ok(ToolResult::success(serde_json::to_string_pretty(&payload)?))
- }
-}
-
-#[cfg(test)]
-#[path = "detect_tools_tests.rs"]
-mod tests;
+pub(crate) use tinytools_std::detect_tools::find_on_path;
+pub use tinytools_std::detect_tools::DetectToolsTool;
diff --git a/crates/openhuman-core/src/tools/impl/system/detect_tools_tests.rs b/crates/openhuman-core/src/tools/impl/system/detect_tools_tests.rs
deleted file mode 100644
index b91c381da0..0000000000
--- a/crates/openhuman-core/src/tools/impl/system/detect_tools_tests.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use super::*;
-
-#[test]
-fn name_and_permission() {
- let tool = DetectToolsTool::new();
- assert_eq!(tool.name(), "detect_tools");
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
-}
-
-#[tokio::test]
-async fn missing_tool_reported_missing() {
- let tool = DetectToolsTool::new();
- let result = tool
- .execute(json!({ "tools": ["definitely_not_a_real_binary_xyz_123"] }))
- .await
- .unwrap();
- assert!(!result.is_error);
- let payload: serde_json::Value = serde_json::from_str(&result.output()).unwrap();
- assert_eq!(payload["probed"], 1);
- assert_eq!(payload["available"].as_array().unwrap().len(), 0);
- assert_eq!(
- payload["missing"].as_array().unwrap()[0],
- "definitely_not_a_real_binary_xyz_123"
- );
-}
-
-#[tokio::test]
-async fn available_plus_missing_equals_probed() {
- let tool = DetectToolsTool::new();
- let result = tool
- .execute(json!({ "tools": ["sh", "definitely_not_a_real_binary_xyz_123"] }))
- .await
- .unwrap();
- let payload: serde_json::Value = serde_json::from_str(&result.output()).unwrap();
- let avail = payload["available"].as_array().unwrap().len();
- let miss = payload["missing"].as_array().unwrap().len();
- assert_eq!(avail + miss, 2);
-}