The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(tools): remove unused tool status module
Steven Enamakelf100cc21535c
diff --git a/crates/openhuman-core/src/tools/mod.rs b/crates/openhuman-core/src/tools/mod.rsindex 57db15f8f4..91ddc52b50 100644--- a/crates/openhuman-core/src/tools/mod.rs+++ b/crates/openhuman-core/src/tools/mod.rs@@ -8,7 +8,6 @@ pub mod registry;pub mod rules;pub(crate) mod schema_cache;mod schemas;-pub mod status;pub mod timeout;pub mod toolpacks;pub(crate) mod user_filter;diff --git a/crates/openhuman-core/src/tools/status/mod.rs b/crates/openhuman-core/src/tools/status/mod.rsdeleted file mode 100644index 3d8665eadd..0000000000--- a/crates/openhuman-core/src/tools/status/mod.rs+++ /dev/null@@ -1,23 +0,0 @@-//! Tool-call lifecycle state and human-readable failure classification.-//!-//! Foundation for the "Visible tool status, failure diagnosis, and safe-//! recovery flows" epic (#4254). This module owns the shared vocabulary that-//! later phases (status panel, bounded retry, in-app diagnostics) build on:-//!-//! - [`ToolLifecycleState`] — where a call is (queued/running/…/needs-input).-//! - [`ToolFailureClass`] / [`FailureCategory`] — what kind of failure it was.-//! - [`ClassifiedFailure`] — a class plus plain-language cause + next action.-//! - [`classify`] — the pure heuristic mapping raw tool error text → the above.-//!-//! It owns no agent tools, no persistence, and no event subscribers; it is a-//! pure data + logic module consumed by the agent tool executor and surfaced-//! over the `tool` event-bus domain.--mod ops;-mod types;--pub use ops::{classify, describe, tool_execution_error};-pub use types::{- ClassifiedFailure, FailureCategory, ToolFailureClass, ToolLifecycleState, MODULE_FAULT_MARKER,- NOT_FOUND_MARKER, TASK_FAILED_MARKER, UNSUPPORTED_MARKER,-};diff --git a/crates/openhuman-core/src/tools/status/ops.rs b/crates/openhuman-core/src/tools/status/ops.rsdeleted file mode 100644index 3d14c3f962..0000000000--- a/crates/openhuman-core/src/tools/status/ops.rs+++ /dev/null@@ -1,402 +0,0 @@-//! Pure failure classification: raw tool error text → [`ClassifiedFailure`].-//!-//! This is deliberately a heuristic, keyword-driven mapping over the error-//! string the executor already produces (`agent_tool_exec` collapses a tool-//! outcome to a message + `success` flag). It touches no global state and does-//! no I/O, so every branch is unit-testable and stays cheap to call on the hot-//! tool-execution path.-//!-//! Precedence matters: the first matching class wins, so the checks are ordered-//! most-specific → least-specific. Anything unmatched falls through to-//! [`ToolFailureClass::Unknown`] (treated as recoverable so a later retry phase-//! can give it one bounded attempt rather than surfacing a dead end).--use super::types::{ClassifiedFailure, ToolFailureClass};--/// Classify a failed tool call into a user-facing [`ClassifiedFailure`].-///-/// * `error_text` — the raw error/output message from the tool. Matched-/// case-insensitively; never surfaced verbatim to the user.-/// * `timed_out` — set by the executor when the failure was a deadline stop-/// (the message alone is not always reliable), which short-circuits to-/// [`ToolFailureClass::Timeout`].-pub fn classify(error_text: &str, timed_out: bool) -> ClassifiedFailure {- let class = classify_class(error_text, timed_out);- describe(class)-}--/// The prefix the agent tool adapter puts on an error a tool returned as `Err`.-/// [`tool_execution_error`] is its only producer, so the classifier and the-/// adapter cannot drift apart.-const TOOL_EXECUTION_ERROR_PREFIX: &str = "Error executing ";--/// Render a tool's `Err` the way the agent tool adapter reports it to the model.-pub fn tool_execution_error(tool: &str, error: impl std::fmt::Display) -> String {- format!("{TOOL_EXECUTION_ERROR_PREFIX}{tool}: {error}")-}--/// Does `text` (already lowercased) open with `marker`, either bare or right-/// behind the adapter's own [`tool_execution_error`] wrapper? Those are the only-/// places a producer puts a marker; the same characters anywhere else came from-/// text nobody vouched for (#6277).-fn opens_with_marker(text: &str, marker: &str) -> bool {- let text = text.trim_start();- if text.starts_with(marker) {- return true;- }- let prefix = TOOL_EXECUTION_ERROR_PREFIX.to_ascii_lowercase();- text.strip_prefix(prefix.as_str())- .and_then(|rest| rest.split_once(": "))- .is_some_and(|(tool, rest)| !tool.contains(char::is_whitespace) && rest.starts_with(marker))-}--/// The class-only half of [`classify`], split out so the ordering heuristics can-/// be tested independently of the copy.-fn classify_class(error_text: &str, timed_out: bool) -> ToolFailureClass {- let text = error_text.to_lowercase();-- // -1. Structural result shapes a producer owns, ahead of every marker and- // keyword scan. Each carries a payload that is data, not a verdict:- // the harness's schema-validation answer echoes the whole parameter- // schema (a shell schema describing `timeout` read as "took too- // long"), a command's exit report carries the program's own stdout and- // stderr (stderr mentioning `ollama` read as "couldn't reach the AI- // model"), and an unknown-tool answer echoes the attempted arguments.- // The `timed_out` flag is not consulted here: the only live caller- // derives it by sniffing the same text.- if let Some(class) = structural_class(&text) {- tracing::debug!(- ?class,- "[tool_status::classify] matched structural result shape"- );- return class;- }-- // 0. Structured policy markers win over *every* heuristic, including the- // `timed out` sniff below (#4459). Both markers are emitted upstream by- // the security/approval gate and survive the `Error: …` wrapping, so a- // marker hit is authoritative — a TTL-expiry deny reason literally- // contains "timed out", and must classify as an expired approval, never- // an execution Timeout that promises an auto-retry.- //- // `POLICY_BLOCKED_MARKER` — a hard, cross-turn block: the action is- // refused by the user's safety/autonomy policy (BlockedByPolicy).- if text.contains(crate::security::POLICY_BLOCKED_MARKER) {- tracing::debug!("[tool_status::classify] matched POLICY_BLOCKED_MARKER -> BlockedByPolicy");- return ToolFailureClass::BlockedByPolicy;- }- // `POLICY_DENIED_MARKER` — a this-turn denial: the user answered "no" at- // the approval prompt, the prompt's channel dropped, the origin was- // unlabelled, or the prompt's TTL expired. All are- // non-retryable refusals (UserDeclined), split only by copy: a TTL- // expiry reads "approval expired", an explicit refusal reads "declined".- if text.contains(crate::security::POLICY_DENIED_MARKER) {- if contains_any(&text, &["timed out", "timeout", "expired"]) {- tracing::debug!(- "[tool_status::classify] matched POLICY_DENIED_MARKER + expiry phrase -> ApprovalExpired"- );- return ToolFailureClass::ApprovalExpired;- }- tracing::debug!("[tool_status::classify] matched POLICY_DENIED_MARKER -> Denied");- return ToolFailureClass::Denied;- }- // `NOT_FOUND_MARKER` / `UNSUPPORTED_MARKER` — the producer knew the call- // named something that is not there, or asked for something the target- // can never do (#6277). Ahead of every heuristic for the same reason as- // the policy markers: a catalog entry id or a skill description can- // contain any of the words sniffed below. Unlike the policy markers they- // count only where a producer puts them (`opens_with_marker`): a shell's- // stderr, an upstream body or an interpolated id that merely contains- // the marker text must not turn a failure permanent.- if opens_with_marker(&text, super::types::NOT_FOUND_MARKER) {- tracing::debug!("[tool_status::classify] matched NOT_FOUND_MARKER -> NotFound");- return ToolFailureClass::NotFound;- }- if opens_with_marker(&text, super::types::UNSUPPORTED_MARKER) {- tracing::debug!("[tool_status::classify] matched UNSUPPORTED_MARKER -> Unsupported");- return ToolFailureClass::Unsupported;- }-- // 1. Timeout — the executor's explicit signal wins over any text sniffing.- if timed_out || contains_any(&text, &["timed out", "timeout", "deadline exceeded"]) {- return ToolFailureClass::Timeout;- }-- // 2. Blocked by policy — the OpenHuman security/autonomy gate or a forbidden- // path. Checked *before* credentials so the OpenHuman-specific- // `forbidden path` marker wins over the bare `forbidden` that a plain- // external 403 body carries (routed to credentials below). Reserved for- // OpenHuman policy phrasing only — a hard policy block is tagged upstream- // with `POLICY_BLOCKED_MARKER` and already short-circuited above (step 0);- // this heuristic only catches un-marked policy phrasing. Bare HTTP- // `403`/`Forbidden` is an external authz failure, not our gate.- // `channel allows` is the tail of the tool-policy PermissionDenied render.- // (The old `"policy denied"` needle was dead — no producer emits that- // phrasing; the deny family uses `POLICY_DENIED_MARKER`, handled above.)- if contains_any(- &text,- &[- "blocked by policy",- "security policy",- "channel allows",- "not allowed by",- "forbidden path",- "autonomy",- ],- ) {- return ToolFailureClass::BlockedByPolicy;- }-- // 3. Bad credentials — auth-token problems and external authz failures- // (401/403). A bare HTTP 403/Forbidden or an `insufficient scopes` body- // means the connected account lacks the grant, so the user should- // reconnect / re-authorize — not toggle OpenHuman's Agent-access policy.- // Numeric codes go through `contains_code` so `401`/`403` never match- // inside a longer digit run (a port, byte count, or `14033`).- if contains_any(- &text,- &[- "unauthorized",- "invalid api key",- "invalid_api_key",- "authentication failed",- "invalid credentials",- "bad credentials",- "token expired",- "invalid_grant",- "not signed in",- "sign in again",- "forbidden",- "insufficient authentication scopes",- "insufficient scopes",- "insufficient_scope",- ],- ) || contains_code(&text, "401")- || contains_code(&text, "403")- {- return ToolFailureClass::BadCredentials;- }-- // 4. Missing OS/tool permission — access denied at the filesystem/OS layer.- if contains_any(- &text,- &[- "permission denied",- "os error 13",- "eacces",- "operation not permitted",- "access is denied",- "not permitted",- ],- ) {- return ToolFailureClass::MissingPermission;- }-- // 5. Missing app/command — the thing we tried to invoke isn't there.- if contains_any(- &text,- &[- "command not found",- "not installed",- "no such application",- "could not find application",- "executable not found",- "is not recognized as",- "no such file or directory (os error 2)",- ],- ) {- return ToolFailureClass::MissingApp;- }-- // 6. Model / provider connectivity — before generic service errors so a- // provider outage is named specifically.- if contains_any(- &text,- &[- "provider error",- "could not reach the model",- "could not reach model",- "ollama",- "llm provider",- "inference failed",- "model endpoint",- "no route to host",- ],- ) {- return ToolFailureClass::ModelConnection;- }-- // 7. Service unavailable — generic transient upstream/network failure.- if contains_any(- &text,- &[- "connection refused",- "econnrefused",- "service unavailable",- "temporarily unavailable",- "could not connect",- "connection reset",- "network is unreachable",- ],- ) || contains_code(&text, "502")- || contains_code(&text, "503")- || contains_code(&text, "504")- {- return ToolFailureClass::ServiceUnavailable;- }-- ToolFailureClass::Unknown-}--/// Prefix of the harness's answer to a schema-invalid call-/// (`tinyagents` `agent_loop/tools.rs`: "invalid arguments for tool `X`:-/// {detail}; expected schema: {…}").-const INVALID_ARGUMENTS_PREFIX: &str = "invalid arguments for tool `";--/// Prefix of the harness's answer to a call naming a tool the agent does not-/// have (`tinyagents` `agent_loop/unknown_tool.rs`: "unknown tool `X`-/// (arguments: {…}): …").-const UNKNOWN_TOOL_PREFIX: &str = "unknown tool `";--/// Prefix of `tinytools::render_command_failure`, the one renderer every-/// shell-family tool uses for a command that ran and did not exit 0-/// ("Command failed (exit code N…)" / "Command failed (terminated by a-/// signal…)"), lowercased.-const COMMAND_FAILED_PREFIX: &str = "command failed (";--/// Classify `text` (already lowercased) from a result shape its producer owns,-/// or `None` when it opens with none of them. Only the opening of the text is-/// read, never the echoed schema, arguments or program output behind it.-fn structural_class(text: &str) -> Option<ToolFailureClass> {- if opens_with_marker(text, INVALID_ARGUMENTS_PREFIX) {- return Some(ToolFailureClass::InvalidArguments);- }- if opens_with_marker(text, UNKNOWN_TOOL_PREFIX) {- return Some(ToolFailureClass::NotFound);- }- if opens_with_marker(text, COMMAND_FAILED_PREFIX) {- // The exit line is the renderer's own; 127 and 126 are the shell's- // codes for a missing program and a non-executable one, which the- // user can act on. Every other code is the program's verdict.- let exit_line = text.trim_start().lines().next().unwrap_or_default();- let code = exit_line- .split_once("exit code ")- .map(|(_, rest)| {- rest.chars()- .take_while(char::is_ascii_digit)- .collect::<String>()- })- .unwrap_or_default();- return Some(match code.as_str() {- "127" => ToolFailureClass::MissingApp,- "126" => ToolFailureClass::MissingPermission,- _ => ToolFailureClass::CommandFailed,- });- }- None-}--/// Attach the category + plain-language copy for a known class. Use this at the-/// call sites that already know the class for certain (e.g. the policy gate,-/// which knows a refusal is [`ToolFailureClass::BlockedByPolicy`]) rather than-/// round-tripping a synthetic message through [`classify`]. The copy is the-/// user-facing English source string; the UI localizes by class, so keep these-/// stable and jargon-free.-pub fn describe(class: ToolFailureClass) -> ClassifiedFailure {- let category = class.category();- let (cause_plain, next_action) = match class {- ToolFailureClass::MissingPermission => (- "OpenHuman doesn't have permission to do this yet.",- "Grant the permission it needs, then try again.",- ),- ToolFailureClass::MissingApp => (- "The app or program needed for this action isn't available.",- "Install or open the app, then try again.",- ),- ToolFailureClass::ServiceUnavailable => (- "A service OpenHuman needs is temporarily unavailable.",- "OpenHuman will try again shortly — no action needed.",- ),- ToolFailureClass::BadCredentials => (- "The saved sign-in details are missing or no longer valid.",- "Sign in again or update the credentials, then try again.",- ),- ToolFailureClass::BlockedByPolicy => (- "This action is blocked by your safety settings.",- "Allow it in Settings → Agent access if you want it to run.",- ),- ToolFailureClass::ModelConnection => (- "OpenHuman couldn't reach the AI model.",- "Check your connection or model settings; OpenHuman will retry.",- ),- ToolFailureClass::Timeout => (- "The action took too long and was stopped.",- "OpenHuman will try again, or you can retry it manually.",- ),- ToolFailureClass::Denied => (- "You declined this action.",- "Nothing to do — it was not run. Ask again if you change your mind.",- ),- ToolFailureClass::ApprovalExpired => (- "The approval request expired before anyone responded.",- "Ask again to run it — OpenHuman won't retry it on its own.",- ),- ToolFailureClass::NotFound => (- "What this action asked for doesn't exist or isn't available here.",- "No action needed. The assistant can look up the right name and try again.",- ),- ToolFailureClass::Unsupported => (- "OpenHuman can't do this automatically yet.",- "Do it manually, or ask for a different option.",- ),- ToolFailureClass::InvalidArguments => (- "The assistant called this action with details it doesn't accept.",- "No action needed. The assistant can fix the request and try again.",- ),- ToolFailureClass::CommandFailed => (- "The command ran but reported an error.",- "No action needed. The assistant can read the output and adjust.",- ),- ToolFailureClass::Unknown => (- "Something went wrong with this action.",- "Try again; if it keeps failing, run diagnostics from Settings.",- ),- };- ClassifiedFailure {- class,- category,- cause_plain: cause_plain.to_string(),- next_action: next_action.to_string(),- recoverable: category.is_recoverable(),- }-}--/// Case-insensitive: does `haystack` (already lowercased) contain any needle?-fn contains_any(haystack: &str, needles: &[&str]) -> bool {- needles.iter().any(|n| haystack.contains(n))-}--/// Does `haystack` contain `code` (an all-ASCII-digit HTTP status like `"403"`)-/// as a standalone number — i.e. not embedded in a longer digit run? Guards the-/// numeric needles against false positives such as `403` inside `14033`, a port,-/// a byte count, or a timestamp. Matches when the char on each side of the hit-/// is a non-digit (or a string boundary).-fn contains_code(haystack: &str, code: &str) -> bool {- let bytes = haystack.as_bytes();- let mut from = 0;- while let Some(rel) = haystack[from..].find(code) {- let start = from + rel;- let end = start + code.len();- let left_ok = start == 0 || !bytes[start - 1].is_ascii_digit();- let right_ok = end >= bytes.len() || !bytes[end].is_ascii_digit();- if left_ok && right_ok {- return true;- }- from = start + 1;- }- false-}--#[cfg(test)]-#[path = "ops_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/status/ops_tests.rs b/crates/openhuman-core/src/tools/status/ops_tests.rsdeleted file mode 100644index d8e136d760..0000000000--- a/crates/openhuman-core/src/tools/status/ops_tests.rs+++ /dev/null@@ -1,405 +0,0 @@-use super::*;--fn class_of(text: &str) -> ToolFailureClass {- classify(text, false).class-}--#[test]-fn timeout_flag_wins_regardless_of_text() {- assert_eq!(- classify("anything at all", true).class,- ToolFailureClass::Timeout- );-}--#[test]-fn timeout_detected_from_text() {- assert_eq!(- class_of("tool 'shell' timed out after 120 seconds"),- ToolFailureClass::Timeout- );-}--#[test]-fn missing_permission_from_os_error() {- assert_eq!(- class_of("Error executing file_write: Permission denied (os error 13)"),- ToolFailureClass::MissingPermission- );- assert_eq!(- class_of("EACCES: operation not permitted"),- ToolFailureClass::MissingPermission- );-}--#[test]-fn missing_app_from_command_not_found() {- assert_eq!(- class_of("bash: gh: command not found"),- ToolFailureClass::MissingApp- );- assert_eq!(- class_of("ffmpeg is not installed on this system"),- ToolFailureClass::MissingApp- );-}--#[test]-fn service_unavailable_from_connection_errors() {- assert_eq!(- class_of("connection refused (ECONNREFUSED)"),- ToolFailureClass::ServiceUnavailable- );- assert_eq!(- class_of("upstream returned 503 Service Unavailable"),- ToolFailureClass::ServiceUnavailable- );-}--#[test]-fn bad_credentials_from_auth_errors() {- assert_eq!(- class_of("HTTP 401 Unauthorized"),- ToolFailureClass::BadCredentials- );- assert_eq!(- class_of("invalid api key provided"),- ToolFailureClass::BadCredentials- );- assert_eq!(- class_of("auth token expired, please sign in again"),- ToolFailureClass::BadCredentials- );-}--#[test]-fn blocked_by_policy_from_gate_and_forbidden() {- assert_eq!(- class_of("Permission denied for tool 'shell': requires Execute, channel allows ReadOnly"),- ToolFailureClass::BlockedByPolicy- );- assert_eq!(- class_of("blocked by policy: destructive command"),- ToolFailureClass::BlockedByPolicy- );- // OpenHuman's own path guard stays policy...- assert_eq!(- class_of("write rejected: forbidden path outside action_dir"),- ToolFailureClass::BlockedByPolicy- );-}--#[test]-fn external_403_is_credentials_not_policy() {- // A bare external authz failure must route to credentials (reconnect /- // grant scopes), NOT OpenHuman's Agent-access policy.- assert_eq!(- class_of("HTTP 403 Forbidden"),- ToolFailureClass::BadCredentials- );- assert_eq!(- class_of("Gmail API error: 403 insufficient authentication scopes"),- ToolFailureClass::BadCredentials- );- assert_eq!(- class_of("401 Unauthorized"),- ToolFailureClass::BadCredentials- );-}--#[test]-fn policy_denied_marker_is_denied_and_not_recoverable() {- use crate::security::POLICY_DENIED_MARKER;- let text = format!("{POLICY_DENIED_MARKER} you declined this shell action");- assert_eq!(class_of(&text), ToolFailureClass::Denied);- // UserDeclined family — never eligible for an auto-retry (#4459).- assert!(!classify(&text, false).recoverable);-}--#[test]-fn policy_denied_ttl_expiry_is_approval_expired_not_timeout() {- use crate::security::POLICY_DENIED_MARKER;- // A TTL-expiry deny reason literally contains "timed out" — the policy- // marker must win over the timeout sniff so it classifies as an expired- // approval, NOT an execution Timeout that promises an auto-retry (#4459).- let text = format!("{POLICY_DENIED_MARKER} Approval for 'shell' timed out after 600s");- assert_eq!(class_of(&text), ToolFailureClass::ApprovalExpired);- assert_ne!(class_of(&text), ToolFailureClass::Timeout);- assert!(!classify(&text, false).recoverable);-}--#[test]-fn numeric_status_codes_need_word_boundaries() {- // `403`/`503` embedded in a longer digit run must NOT trip the code- // needles — these fall through to Unknown.- assert_eq!(- class_of("processed 14033 records before aborting"),- ToolFailureClass::Unknown- );- assert_eq!(- class_of("listening on port 15032 failed unexpectedly"),- ToolFailureClass::Unknown- );- // ...but a standalone 503 is still a service outage.- assert_eq!(- class_of("upstream returned 503"),- ToolFailureClass::ServiceUnavailable- );-}--#[test]-fn model_connection_from_provider_errors() {- assert_eq!(- class_of("Provider error (retryable=true): boom"),- ToolFailureClass::ModelConnection- );- assert_eq!(- class_of("could not reach the model endpoint"),- ToolFailureClass::ModelConnection- );- assert_eq!(- class_of("ollama daemon not responding"),- ToolFailureClass::ModelConnection- );-}--#[test]-fn unknown_when_nothing_matches() {- assert_eq!(- class_of("some totally novel failure mode"),- ToolFailureClass::Unknown- );-}--#[test]-fn credentials_precedence_over_service_when_both_present() {- // A 401 that also mentions a connection should read as credentials, not- // a transient service blip — the ordering guarantees this.- assert_eq!(- class_of("could not connect: 401 unauthorized"),- ToolFailureClass::BadCredentials- );-}--#[test]-fn every_class_produces_nonempty_user_copy() {- for class in [- ToolFailureClass::MissingPermission,- ToolFailureClass::MissingApp,- ToolFailureClass::ServiceUnavailable,- ToolFailureClass::BadCredentials,- ToolFailureClass::BlockedByPolicy,- ToolFailureClass::ModelConnection,- ToolFailureClass::Timeout,- ToolFailureClass::Denied,- ToolFailureClass::ApprovalExpired,- ToolFailureClass::NotFound,- ToolFailureClass::Unsupported,- ToolFailureClass::Unknown,- ] {- let f = describe(class);- assert!(!f.cause_plain.is_empty(), "empty cause for {class:?}");- assert!(!f.next_action.is_empty(), "empty next_action for {class:?}");- assert_eq!(f.recoverable, f.category.is_recoverable());- }-}--// #6277: failures whose producer knows they cannot succeed on retry are-// classified from its marker, ahead of any word the message happens to contain.-#[test]-fn marked_permanent_failures_are_not_recoverable() {- use crate::tools::status::{NOT_FOUND_MARKER, UNSUPPORTED_MARKER};-- // Through the adapter's own wrapper, exactly as a tool's `Err` reaches the- // classifier.- let not_found = classify(- &tool_execution_error(- "use_skill",- format!("{NOT_FOUND_MARKER} skill 'timeout-helper' not found"),- ),- false,- );- assert_eq!(not_found.class, ToolFailureClass::NotFound);- assert!(!not_found.recoverable);-- let unsupported = classify(- &format!("{UNSUPPORTED_MARKER} Failed to install skill 'x': hosted on skills.sh"),- false,- );- assert_eq!(unsupported.class, ToolFailureClass::Unsupported);- assert!(!unsupported.recoverable);-}--// #6277 review: a marker counts only where a producer puts it. Text that merely-// contains one (shell stderr, an upstream body, an interpolated id) keeps its-// ordinary classification.-#[test]-fn markers_outside_the_producer_prefix_do_not_count() {- use crate::tools::status::{NOT_FOUND_MARKER, UNSUPPORTED_MARKER};-- for text in [- format!("grep: pattern {NOT_FOUND_MARKER} not in log"),- format!("upstream said: {UNSUPPORTED_MARKER}"),- format!("Failed to install skill '{NOT_FOUND_MARKER}x': network hiccup"),- tool_execution_error("shell", format!("exit 1\nstderr: {UNSUPPORTED_MARKER}")),- ] {- let class = classify(&text, false).class;- assert!(- !matches!(- class,- ToolFailureClass::NotFound | ToolFailureClass::Unsupported- ),- "{text:?} carries a marker outside the producer prefix but classified {class:?}"- );- }-}--#[test]-fn recoverable_flag_matches_category() {- assert!(classify("503 service unavailable", false).recoverable);- assert!(!classify("permission denied (os error 13)", false).recoverable);- assert!(!classify("blocked by policy", false).recoverable);-}--// Production misfires (Langfuse, Oct 2026): the classifier keyword-scanned the-// whole result, including the JSON schema the harness echoes back on a-// validation error and a command's own stderr. Structural shapes a producer-// owns are classified before any keyword scan, and their payload is never-// read for provider / timeout / credential words.-#[test]-fn structural_results_classify_before_any_keyword_scan() {- // The harness's schema-validation answer (`agent_loop/tools.rs`). The- // echoed shell schema describes a `timeout` argument; that must not read- // as "the action took too long".- let invalid_shell_args = "invalid arguments for tool `shell`: validation error: tool `shell` \- arguments failed schema validation: missing required property `command`; expected \- schema: {\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"},\- \"timeout\":{\"type\":\"integer\",\"description\":\"Timeout in seconds; the command \- is killed after the deadline (timed out)\"}},\"required\":[\"command\"]}";- // A command that ran and exited non-zero, rendered by- // `tinytools::render_command_failure`. Its stderr mentions ollama; that is- // the program's output, not OpenHuman failing to reach a model.- let ollama_stderr = "Command failed (exit code 1)\n[stdout]\nchecking models\n[stderr]\n\- Error: could not connect to ollama at 127.0.0.1:11434 (connection refused)";-- let cases: &[(&str, &str, bool, ToolFailureClass)] = &[- (- "empty-args shell validation error with `timeout` in the echoed schema",- invalid_shell_args,- false,- ToolFailureClass::InvalidArguments,- ),- (- "validation error even when the executor's text sniff set timed_out",- invalid_shell_args,- true,- ToolFailureClass::InvalidArguments,- ),- (- "validation error carrying credential/policy words in the schema",- "invalid arguments for tool `gmail_send`: missing `to`; expected schema: \- {\"description\":\"401 unauthorized forbidden; blocked by policy; permission denied\"}",- false,- ToolFailureClass::InvalidArguments,- ),- (- "non-zero exit whose stderr mentions ollama",- ollama_stderr,- false,- ToolFailureClass::CommandFailed,- ),- (- "non-zero exit whose stderr says timed out (text sniff set timed_out)",- "Command failed (exit code 1)\n[stderr]\npytest: test_fetch timed out after 5s",- true,- ToolFailureClass::CommandFailed,- ),- (- "non-zero exit whose output carries a 401 / unauthorized",- "Command failed (exit code 22)\n[stderr]\ncurl: (22) The requested URL returned \- error: 401 Unauthorized",- false,- ToolFailureClass::CommandFailed,- ),- (- "signal-terminated command",- "Command failed (terminated by a signal — no exit code)\n(no output was captured on \- stdout or stderr)",- false,- ToolFailureClass::CommandFailed,- ),- (- "SIGPIPE exit whose hint is pure data",- "Command failed (exit code 141 — SIGPIPE: a reader closed the pipe before the writer \- finished)\n[stdout]\nUpdate objects.md (#401)",- false,- ToolFailureClass::CommandFailed,- ),- (- "exit 127 keeps its missing-program meaning from the exit line",- "Command failed (exit code 127 — command not found: a required executable or \- dependency is missing or not on PATH)\n[stderr]\nbash: ollama: command not found",- false,- ToolFailureClass::MissingApp,- ),- (- "exit 126 keeps its permission meaning from the exit line",- "Command failed (exit code 126 — permission denied or not executable)\n[stderr]\n\- bash: ./run.sh: Permission denied",- false,- ToolFailureClass::MissingPermission,- ),- (- "exit report wrapped by the agent tool adapter",- "Error executing shell: Command failed (exit code 2)\n[stderr]\nprovider error: \- service unavailable",- false,- ToolFailureClass::CommandFailed,- ),- (- "unknown-tool answer echoing arguments that contain keywords",- "unknown tool `fetch_url` (arguments: {\"url\":\"https://x.test\",\"timeout\":30,\- \"note\":\"ollama 401\"}): no tool with that name is available to you, and calling \- it again will fail the same way.",- false,- ToolFailureClass::NotFound,- ),- ];- for (name, text, timed_out, expected) in cases {- assert_eq!(- classify(text, *timed_out).class,- *expected,- "case `{name}` misclassified: {text:?}"- );- }-}--// The structural prefixes count only at the start, like the producer markers:-// prose that merely mentions them keeps its ordinary classification.-#[test]-fn structural_prefixes_only_count_where_the_producer_puts_them() {- assert_eq!(- class_of("request timed out; Command failed (exit code 1) was logged earlier"),- ToolFailureClass::Timeout- );- assert_eq!(- class_of("ollama: provider error, see invalid arguments for tool `x` in the log"),- ToolFailureClass::ModelConnection- );-}--#[test]-fn structural_classes_carry_their_own_copy() {- let invalid = classify(- "invalid arguments for tool `shell`: missing `command`",- false,- );- assert_eq!(invalid.class, ToolFailureClass::InvalidArguments);- assert!(!invalid.recoverable);- assert!(!invalid.cause_plain.contains("took too long"));-- let exit = classify("Command failed (exit code 1)\n[stderr]\nboom", false);- assert_eq!(exit.class, ToolFailureClass::CommandFailed);- assert!(!exit.recoverable);- assert!(!exit.cause_plain.contains("AI model"));-}diff --git a/crates/openhuman-core/src/tools/status/types.rs b/crates/openhuman-core/src/tools/status/types.rsdeleted file mode 100644index 3fde1abdc1..0000000000--- a/crates/openhuman-core/src/tools/status/types.rs+++ /dev/null@@ -1,189 +0,0 @@-//! Domain types for tool-call lifecycle state and failure classification.-//!-//! These types are the shared vocabulary for the "Visible tool status, failure-//! diagnosis, and safe recovery flows" epic (#4254). They are intentionally-//! transport-agnostic serde types: the same values are carried on the-//! `tool` event-bus domain, returned over JSON-RPC, and rendered in the UI.-//!-//! Nothing here performs classification — see [`super::classify`] for the pure-//! mapping from a raw tool error into a [`ClassifiedFailure`]. Keeping the data-//! model and the heuristics in separate files lets the heuristics be unit-//! tested without any runtime state.--use serde::{Deserialize, Serialize};--/// Where a single tool call is in its lifecycle.-///-/// Rendered 1:1 in the UI status surfaces (chat timeline today, dedicated-/// status panel in a later phase). `Queued`/`Retrying`/`NeedsUserInput` are not-/// yet emitted by the executor in P1 — they are modelled here so downstream-/// phases (retry, status panel) do not need to reshape the enum.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum ToolLifecycleState {- /// Accepted but not yet started (e.g. waiting on a concurrency slot).- Queued,- /// Executing right now.- Running,- /// Finished successfully.- Succeeded,- /// Finished with a failure. Pair with a [`ClassifiedFailure`] for the cause.- Failed,- /// Refused before execution by the security policy / permission gate.- Blocked,- /// A bounded automatic retry is in progress.- Retrying,- /// Parked awaiting the user (approval or additional input).- NeedsUserInput,-}--/// The kind of failure, one of the classes called out in #4254 plus a catch-all.-///-/// The set is deliberately small and user-facing — it maps to the plain-language-/// explanations in [`ClassifiedFailure`], not to internal error enums.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum ToolFailureClass {- /// OpenHuman lacks an OS/tool permission it needs (e.g. file access).- MissingPermission,- /// A required application or command is not installed / not available.- MissingApp,- /// A dependency service is temporarily unavailable / unreachable.- ServiceUnavailable,- /// Saved credentials are missing, expired, or invalid.- BadCredentials,- /// The action was refused by the user's safety / autonomy policy.- BlockedByPolicy,- /// The AI model / provider could not be reached.- ModelConnection,- /// The action ran past its deadline and was stopped.- Timeout,- /// The user (or the approval gate on their behalf) refused this action at- /// the approval prompt. Non-retryable — re-running just re-prompts for an- /// effect the user already declined (#4459).- Denied,- /// The approval prompt expired (TTL) before anyone responded. Non-retryable:- /// nobody approved, so it must not read as an execution timeout that- /// auto-retries (#4459).- ApprovalExpired,- /// What the call named does not exist or is not available to this agent: a- /// tool it does not have, a catalog entry that is not there. The identical- /// call fails the same way every time (#6277).- NotFound,- /// The operation is not supported for this target, permanently: e.g. a- /// catalog skill with no direct download cannot be installed automatically- /// (#6277).- Unsupported,- /// The model called a real tool with arguments that do not match its- /// schema. Nothing ran; the model gets the expected schema back and can- /// correct the call. Classified from the harness's own validation answer,- /// never from the schema text it echoes.- InvalidArguments,- /// A command ran and exited non-zero (or was killed by a signal). The- /// tool worked; the program it ran reported failure, and its stdout/stderr- /// is data for the model, not a verdict about OpenHuman.- CommandFailed,- /// Could not be classified into any of the above.- Unknown,-}--/// Marker prefixing a failure whose target does not exist or is not available-/// ([`ToolFailureClass::NotFound`]). Emitted by the producer that *knows* the-/// lookup failed, so the classifier never has to guess from prose. Bracketed-/// like the policy markers so it survives the `Error executing …` wrapping.-pub const NOT_FOUND_MARKER: &str = "[not-found]";--/// Marker prefixing a failure the target can never support-/// ([`ToolFailureClass::Unsupported`]). Same contract as [`NOT_FOUND_MARKER`].-pub const UNSUPPORTED_MARKER: &str = "[unsupported]";--/// Phrase a module fault carries (`modules::ops`): a module that failed to-/// load stays unloaded until the app restarts, so any call that needs it fails-/// the same way for the rest of the process. Shared so the recovery policy-/// matches the producer's wording instead of a copy of it.-pub const MODULE_FAULT_MARKER: &str = "This is terminal for the running process";--/// Marker prefixing a delegated task (a TinyComputer browser task) that ended-/// without finishing: it failed, or was cancelled under the caller. The task-/// reports what it did and what to change, so the recovery policy gives the-/// model one changed attempt rather than reading the task's own prose (a-/// page's `403`, a planner's `timed out`) as the tool call's verdict.-pub const TASK_FAILED_MARKER: &str = "[task-failed]";--/// The three top-level states the UI separates, per the #4254 acceptance-/// criterion "clear separation between recoverable failure, blocked-by-policy,-/// and action-needs-user-confirmation states".-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub enum FailureCategory {- /// Transient — safe for OpenHuman to retry on its own (bounded, in a later- /// phase). `recoverable` on [`ClassifiedFailure`] is true iff this variant.- Recoverable,- /// Refused by policy. Not retried; the user must change settings to allow it.- BlockedByPolicy,- /// Needs the user to act (grant permission, install an app, sign in) before- /// the action can succeed.- NeedsUserConfirmation,- /// The user declined the action, or the approval prompt expired before- /// anyone responded. Never retried automatically — auto-re-attempting a- /// refused external effect is exactly the bug this category prevents- /// (#4459).- UserDeclined,- /// The identical call cannot succeed: what it named does not exist, or the- /// operation is not supported. Never retried automatically, and there is- /// nothing for the user to approve, grant or sign in to (#6277).- Permanent,-}--/// A tool failure rendered for a non-technical user: what class it is, which-/// top-level category it falls in, a plain-language cause, and a next action.-///-/// Constructed only via [`super::classify`]; the string fields are stable,-/// user-facing copy (English source; localized in the UI layer).-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct ClassifiedFailure {- /// The specific failure class.- pub class: ToolFailureClass,- /// The top-level category the UI separates on.- pub category: FailureCategory,- /// Plain-language description of what went wrong (no jargon, no stack).- pub cause_plain: String,- /// Plain-language description of what to do next.- pub next_action: String,- /// Whether OpenHuman may retry automatically. Always equal to- /// `category == FailureCategory::Recoverable` — carried explicitly so- /// serialized consumers don't have to re-derive it.- pub recoverable: bool,-}--impl FailureCategory {- /// Whether a failure in this category is safe to retry automatically.- pub fn is_recoverable(self) -> bool {- matches!(self, FailureCategory::Recoverable)- }-}--impl ToolFailureClass {- /// The category this class belongs to. Single source of truth for the- /// class→category mapping used by [`super::classify`].- pub fn category(self) -> FailureCategory {- match self {- ToolFailureClass::ServiceUnavailable- | ToolFailureClass::ModelConnection- | ToolFailureClass::Timeout- | ToolFailureClass::Unknown => FailureCategory::Recoverable,- ToolFailureClass::BlockedByPolicy => FailureCategory::BlockedByPolicy,- ToolFailureClass::Denied | ToolFailureClass::ApprovalExpired => {- FailureCategory::UserDeclined- }- ToolFailureClass::MissingPermission- | ToolFailureClass::MissingApp- | ToolFailureClass::BadCredentials => FailureCategory::NeedsUserConfirmation,- ToolFailureClass::NotFound- | ToolFailureClass::Unsupported- | ToolFailureClass::InvalidArguments- | ToolFailureClass::CommandFailed => FailureCategory::Permanent,- }- }-}--#[cfg(test)]-#[path = "types_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/status/types_tests.rs b/crates/openhuman-core/src/tools/status/types_tests.rsdeleted file mode 100644index a5c03f7462..0000000000--- a/crates/openhuman-core/src/tools/status/types_tests.rs+++ /dev/null@@ -1,65 +0,0 @@-use super::*;--#[test]-fn recoverable_iff_recoverable_category() {- assert!(FailureCategory::Recoverable.is_recoverable());- assert!(!FailureCategory::BlockedByPolicy.is_recoverable());- assert!(!FailureCategory::NeedsUserConfirmation.is_recoverable());- assert!(!FailureCategory::UserDeclined.is_recoverable());- assert!(!FailureCategory::Permanent.is_recoverable());-}--#[test]-fn every_class_maps_to_expected_category() {- use FailureCategory::*;- use ToolFailureClass::*;- assert_eq!(ServiceUnavailable.category(), Recoverable);- assert_eq!(ModelConnection.category(), Recoverable);- assert_eq!(Timeout.category(), Recoverable);- assert_eq!(Unknown.category(), Recoverable);- assert_eq!(- ToolFailureClass::BlockedByPolicy.category(),- FailureCategory::BlockedByPolicy- );- assert_eq!(MissingPermission.category(), NeedsUserConfirmation);- assert_eq!(MissingApp.category(), NeedsUserConfirmation);- assert_eq!(BadCredentials.category(), NeedsUserConfirmation);- assert_eq!(Denied.category(), UserDeclined);- assert_eq!(ApprovalExpired.category(), UserDeclined);- assert_eq!(NotFound.category(), Permanent);- assert_eq!(Unsupported.category(), Permanent);-}--#[test]-fn types_round_trip_through_json() {- let f = ClassifiedFailure {- class: ToolFailureClass::Timeout,- category: FailureCategory::Recoverable,- cause_plain: "took too long".into(),- next_action: "try again".into(),- recoverable: true,- };- let json = serde_json::to_string(&f).unwrap();- let back: ClassifiedFailure = serde_json::from_str(&json).unwrap();- assert_eq!(f, back);-}--#[test]-fn lifecycle_state_serializes_to_variant_name() {- let json = serde_json::to_string(&ToolLifecycleState::NeedsUserInput).unwrap();- assert_eq!(json, "\"NeedsUserInput\"");-}--#[test]-fn structural_classes_are_permanent() {- // Neither an argument the model got wrong nor a command that exited- // non-zero becomes right by re-running the identical call.- assert_eq!(- ToolFailureClass::InvalidArguments.category(),- FailureCategory::Permanent- );- assert_eq!(- ToolFailureClass::CommandFailed.category(),- FailureCategory::Permanent- );-}