Skip to content

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

refactor(tools): consolidate tool implementations into a single collapsed module

Steven Enamakel19fde311d373
diff --git a/crates/openhuman-core/src/cron/tools/collapsed.rs b/crates/openhuman-core/src/cron/tools/collapsed.rs
index 90d9cb4dd8..37e19449ea 100644
--- a/crates/openhuman-core/src/cron/tools/collapsed.rs
+++ b/crates/openhuman-core/src/cron/tools/collapsed.rs
@@ -35,7 +35,7 @@ use super::{
};
use crate::config::Config;
use crate::security::policy::SecurityPolicy;
-use crate::tools::implementations::meta::collapse::{
+use tinytools::collapse::{
any_external_effect, args_without_action, merge_action_schemas, resolve, strictest_permission,
unknown_action_message, CollapsedAction,
};
diff --git a/crates/openhuman-core/src/memory/tools/collapsed.rs b/crates/openhuman-core/src/memory/tools/collapsed.rs
index 4e1282fa71..7462f8f0a9 100644
--- a/crates/openhuman-core/src/memory/tools/collapsed.rs
+++ b/crates/openhuman-core/src/memory/tools/collapsed.rs
@@ -49,7 +49,7 @@ use super::search::{MemoryChunkContextTool, MemoryHybridSearchTool, MemoryVector
use super::store::MemoryStoreTool;
use crate::config::Config;
use crate::security::policy::SecurityPolicy;
-use crate::tools::implementations::meta::collapse::{
+use tinytools::collapse::{
any_external_effect, args_without_action, merge_action_schemas, resolve, strictest_permission,
unknown_action_message, CollapsedAction,
};
diff --git a/crates/openhuman-core/src/tools/impl/meta/collapse.rs b/crates/openhuman-core/src/tools/impl/meta/collapse.rs
deleted file mode 100644
index 57d779f4d9..0000000000
--- a/crates/openhuman-core/src/tools/impl/meta/collapse.rs
+++ /dev/null
@@ -1,210 +0,0 @@
-//! Building blocks for collapsing a family of tools into one action-dispatched
-//! tool.
-//!
-//! # Why collapse
-//!
-//! Every tool on the wire costs its name, its description and its full
-//! parameter schema on every request. A family of six CRUD tools over one
-//! resource pays that six times to say almost the same thing: `cron_list`,
-//! `cron_add`, `cron_update`, `cron_remove`, `cron_run` and `cron_runs` were
-//! 3,938 bytes between them, and four of the six are a `job_id` and nothing
-//! else. Hermes reaches the same conclusion from the other direction — its
-//! whole scheduler surface is a single `cronjob` tool, its whole memory surface
-//! a single `memory`.
-//!
-//! # The two rules that make this safe
-//!
-//! Collapsing merges tools that the security layer had been judging
-//! separately, and getting that wrong is how a token optimisation becomes a
-//! privilege bug. So:
-//!
-//! 1. **The parameter schema is merged from the members, never retyped.** A
-//! hand-written union drifts the moment a member gains a field, and the
-//! drift is silent: the model is told about a parameter the implementation
-//! ignores, or not told about one it needs. [`merge_action_schemas`] derives
-//! it from the same `parameters_schema()` the members serve.
-//! 2. **Permission is per action, and the argument-free answer is the
-//! strictest.** [`Tool::permission_level`] has no arguments, so a collapsed
-//! tool cannot answer it honestly; it returns the strictest level any member
-//! requires, and [`Tool::permission_level_with_args`] gives the exact one
-//! once the action is known. A caller that ignores the arguments therefore
-//! over-restricts rather than under-restricts.
-//!
-//! The same reasoning applies to [`Tool::external_effect`], which has no
-//! argument-aware variant at all: a collapsed tool reports `true` if *any*
-//! member does.
-
-use std::collections::BTreeMap;
-
-use serde_json::{json, Map, Value};
-
-use tinytools::{PermissionLevel, Tool};
-
-/// One member of a collapsed family: the action name the model passes, and the
-/// tool that serves it.
-pub struct CollapsedAction<'a> {
- pub action: &'static str,
- pub tool: &'a dyn Tool,
-}
-
-/// Build the collapsed `parameters_schema` from the members' own schemas.
-///
-/// The result is an object with `action` (a required enum over the member
-/// names) plus the union of every member's properties. Property descriptions
-/// are prefixed with the action they belong to — the convention `memory_tree`
-/// and `todo` already use — so the model can tell which fields apply to the
-/// action it picked.
-///
-/// Nothing is `required` beyond `action`. A union cannot express "required for
-/// this action only", and marking a field required because one action needs it
-/// would make every other action's call invalid. The members already validate
-/// their own required arguments and return a useful error, so the check lives
-/// where it can be specific rather than in a schema that has to be vague.
-pub fn merge_action_schemas(actions: &[CollapsedAction<'_>]) -> Value {
- let mut properties: BTreeMap<String, Value> = BTreeMap::new();
- // Track which actions mentioned each property so a shared field reads as
- // shared rather than as belonging to whichever action happened to be first.
- let mut owners: BTreeMap<String, Vec<&str>> = BTreeMap::new();
-
- for entry in actions {
- let schema = entry.tool.parameters_schema();
- let Some(props) = schema.get("properties").and_then(Value::as_object) else {
- continue;
- };
- for (name, spec) in props {
- owners.entry(name.clone()).or_default().push(entry.action);
- properties
- .entry(name.clone())
- .or_insert_with(|| spec.clone());
- }
- }
-
- // Rewrite each description to name its actions. Done in a second pass so
- // the prefix can list every owner, which the first pass does not yet know.
- for (name, spec) in properties.iter_mut() {
- let Some(object) = spec.as_object_mut() else {
- continue;
- };
- let owned_by = owners.get(name).map(Vec::as_slice).unwrap_or(&[]);
- // A property every action takes needs no prefix — saying so would be
- // noise on every line.
- if owned_by.len() == actions.len() || owned_by.is_empty() {
- continue;
- }
- let prefix = owned_by.join("/");
- let existing = object
- .get("description")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string();
- let described = if existing.is_empty() {
- prefix
- } else {
- format!("{prefix}: {existing}")
- };
- object.insert("description".to_string(), Value::String(described));
- }
-
- let enum_values: Vec<Value> = actions
- .iter()
- .map(|entry| Value::String(entry.action.to_string()))
- .collect();
-
- let mut merged = Map::new();
- merged.insert(
- "action".to_string(),
- json!({
- "type": "string",
- "enum": enum_values,
- "description": "Which operation to run."
- }),
- );
- for (name, spec) in properties {
- merged.insert(name, spec);
- }
-
- json!({
- "type": "object",
- "properties": Value::Object(merged),
- "required": ["action"]
- })
-}
-
-/// The strictest permission level any member requires.
-///
-/// Used for the argument-free [`Tool::permission_level`], which cannot know
-/// which action is coming. Over-restricting is the only safe direction.
-pub fn strictest_permission(actions: &[CollapsedAction<'_>]) -> PermissionLevel {
- actions
- .iter()
- .map(|entry| entry.tool.permission_level())
- .max_by_key(permission_rank)
- .unwrap_or(PermissionLevel::None)
-}
-
-/// `true` when any member has an external effect.
-pub fn any_external_effect(actions: &[CollapsedAction<'_>]) -> bool {
- actions.iter().any(|entry| entry.tool.external_effect())
-}
-
-/// Order the permission levels from least to most privileged.
-///
-/// `PermissionLevel` does derive `Ord` over explicit discriminants, so `.max()`
-/// would work today. This exhaustive match is here for the day it gains a
-/// variant: a new level would compile fine against `.max()` and silently take
-/// whatever rank its discriminant implied, whereas here it is a compile error
-/// until someone decides where it sits. Getting that wrong under-restricts a
-/// collapsed tool, which is the failure this module exists to avoid.
-fn permission_rank(level: &PermissionLevel) -> u8 {
- match level {
- PermissionLevel::None => 0,
- PermissionLevel::ReadOnly => 1,
- PermissionLevel::Write => 2,
- PermissionLevel::Execute => 3,
- PermissionLevel::Dangerous => 4,
- }
-}
-
-/// Find the member serving `action`.
-pub fn resolve<'a>(
- actions: &'a [CollapsedAction<'a>],
- action: &str,
-) -> Option<&'a CollapsedAction<'a>> {
- actions.iter().find(|entry| entry.action == action)
-}
-
-/// The error a collapsed tool returns for an unknown or missing action.
-///
-/// Lists the valid actions, because the model's next move after this message is
-/// to guess, and a guess against a printed list is far more likely to be right.
-pub fn unknown_action_message(actions: &[CollapsedAction<'_>], got: Option<&str>) -> String {
- let valid = actions
- .iter()
- .map(|entry| entry.action)
- .collect::<Vec<_>>()
- .join("|");
- match got {
- Some(other) => format!("unknown action '{other}' (expected {valid})"),
- None => format!("missing required field `action` (expected {valid})"),
- }
-}
-
-/// Strip the dispatch key before forwarding to the member.
-///
-/// The members are the same tools that serve the legacy names, and several of
-/// them set `"additionalProperties": false`; leaving `action` in the object
-/// would be rejected by any validation they do.
-pub fn args_without_action(args: &Value) -> Value {
- match args.as_object() {
- Some(object) => {
- let mut cloned = object.clone();
- cloned.remove("action");
- Value::Object(cloned)
- }
- None => args.clone(),
- }
-}
-
-#[cfg(test)]
-#[path = "collapse_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/tools/impl/meta/collapse_tests.rs b/crates/openhuman-core/src/tools/impl/meta/collapse_tests.rs
deleted file mode 100644
index 0bdff285b2..0000000000
--- a/crates/openhuman-core/src/tools/impl/meta/collapse_tests.rs
+++ /dev/null
@@ -1,208 +0,0 @@
-use super::*;
-use async_trait::async_trait;
-use tinytools::ToolResult;
-
-struct Stub {
- name: &'static str,
- schema: Value,
- permission: PermissionLevel,
- external: bool,
-}
-
-#[async_trait]
-impl Tool for Stub {
- fn name(&self) -> &str {
- self.name
- }
- fn description(&self) -> &str {
- "stub"
- }
- fn parameters_schema(&self) -> Value {
- self.schema.clone()
- }
- fn permission_level(&self) -> PermissionLevel {
- self.permission
- }
- fn external_effect(&self) -> bool {
- self.external
- }
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::success("ok"))
- }
-}
-
-fn stub(name: &'static str, schema: Value, permission: PermissionLevel, external: bool) -> Stub {
- Stub {
- name,
- schema,
- permission,
- external,
- }
-}
-
-#[test]
-fn the_union_carries_every_members_properties() {
- let list = stub(
- "list",
- json!({"type": "object", "properties": {}}),
- PermissionLevel::ReadOnly,
- false,
- );
- let runs = stub(
- "runs",
- json!({"type": "object", "properties": {
- "job_id": {"type": "string"},
- "limit": {"type": "integer", "description": "How many."}
- }}),
- PermissionLevel::ReadOnly,
- false,
- );
- let actions = vec![
- CollapsedAction {
- action: "list",
- tool: &list,
- },
- CollapsedAction {
- action: "runs",
- tool: &runs,
- },
- ];
- let merged = merge_action_schemas(&actions);
- let props = merged["properties"].as_object().expect("properties");
- assert!(props.contains_key("action"));
- assert!(props.contains_key("job_id"));
- assert!(props.contains_key("limit"));
- assert_eq!(merged["required"], json!(["action"]));
-}
-
-#[test]
-fn only_action_is_required_because_a_union_cannot_say_otherwise() {
- // `job_id` is required for `runs` and meaningless for `list`. Marking
- // it required here would make every `list` call invalid.
- let list = stub(
- "list",
- json!({"type": "object", "properties": {}}),
- PermissionLevel::ReadOnly,
- false,
- );
- let runs = stub(
- "runs",
- json!({"type": "object", "properties": {"job_id": {"type": "string"}}, "required": ["job_id"]}),
- PermissionLevel::ReadOnly,
- false,
- );
- let actions = vec![
- CollapsedAction {
- action: "list",
- tool: &list,
- },
- CollapsedAction {
- action: "runs",
- tool: &runs,
- },
- ];
- assert_eq!(
- merge_action_schemas(&actions)["required"],
- json!(["action"])
- );
-}
-
-#[test]
-fn a_property_only_some_actions_take_is_labelled_with_them() {
- let a = stub(
- "a",
- json!({"type": "object", "properties": {"shared": {"type": "string"}}}),
- PermissionLevel::ReadOnly,
- false,
- );
- let b = stub(
- "b",
- json!({"type": "object", "properties": {
- "shared": {"type": "string"},
- "only_b": {"type": "string", "description": "B's field."}
- }}),
- PermissionLevel::ReadOnly,
- false,
- );
- let actions = vec![
- CollapsedAction {
- action: "a",
- tool: &a,
- },
- CollapsedAction {
- action: "b",
- tool: &b,
- },
- ];
- let merged = merge_action_schemas(&actions);
- let props = &merged["properties"];
- assert_eq!(props["only_b"]["description"], json!("b: B's field."));
- // Taken by every action, so no prefix — it would be noise.
- assert!(props["shared"].get("description").is_none());
-}
-
-#[test]
-fn permission_is_the_strictest_member_not_the_first() {
- let read = stub("r", json!({}), PermissionLevel::ReadOnly, false);
- let execute = stub("x", json!({}), PermissionLevel::Execute, false);
- let write = stub("w", json!({}), PermissionLevel::Write, false);
- let actions = vec![
- CollapsedAction {
- action: "r",
- tool: &read,
- },
- CollapsedAction {
- action: "x",
- tool: &execute,
- },
- CollapsedAction {
- action: "w",
- tool: &write,
- },
- ];
- assert_eq!(strictest_permission(&actions), PermissionLevel::Execute);
-}
-
-#[test]
-fn external_effect_is_true_when_any_member_has_one() {
- let clean = stub("c", json!({}), PermissionLevel::ReadOnly, false);
- let dirty = stub("d", json!({}), PermissionLevel::ReadOnly, true);
- assert!(!any_external_effect(&[CollapsedAction {
- action: "c",
- tool: &clean
- }]));
- assert!(any_external_effect(&[
- CollapsedAction {
- action: "c",
- tool: &clean
- },
- CollapsedAction {
- action: "d",
- tool: &dirty
- },
- ]));
-}
-
-#[test]
-fn the_dispatch_key_does_not_reach_the_member() {
- // Several members set `additionalProperties: false`.
- let args = json!({"action": "runs", "job_id": "j1"});
- assert_eq!(args_without_action(&args), json!({"job_id": "j1"}));
-}
-
-#[test]
-fn an_unknown_action_names_the_valid_ones() {
- let a = stub("a", json!({}), PermissionLevel::ReadOnly, false);
- let actions = vec![CollapsedAction {
- action: "add",
- tool: &a,
- }];
- assert_eq!(
- unknown_action_message(&actions, Some("addd")),
- "unknown action 'addd' (expected add)"
- );
- assert_eq!(
- unknown_action_message(&actions, None),
- "missing required field `action` (expected add)"
- );
-}
diff --git a/crates/openhuman-core/src/tools/impl/meta/deferred.rs b/crates/openhuman-core/src/tools/impl/meta/deferred.rs
index 00208f4e33..f0b6fb8f3c 100644
--- a/crates/openhuman-core/src/tools/impl/meta/deferred.rs
+++ b/crates/openhuman-core/src/tools/impl/meta/deferred.rs
@@ -33,56 +33,10 @@
//! because both only ever subtract from a set the belt and the security policy
//! already decided.
-use std::collections::HashSet;
-
-use tinytools::{Tool, ToolExposure};
-
/// The name an agent lists in `[tools] named` to opt a hand-written belt into
/// discovery. It is not a registered tool: the harness advertises its own
/// intrinsic `tool_search` whenever a run has a deferred tool, so the name in
/// a belt is a request for that, and the builder strips it from the allowlist.
pub const TOOL_SEARCH_NAME: &str = "tool_search";
-/// Remove every [`ToolExposure::Deferred`] and [`ToolExposure::Hidden`] tool
-/// from an agent's advertised set, returning the names of the deferred ones so
-/// the caller can keep them registered.
-///
-/// Hidden tools are dropped and **not** returned: they are not searchable
-/// either, by definition.
-pub fn strip_deferred_from_visible(
- visible: &mut HashSet<String>,
- tools: &[Box<dyn Tool>],
-) -> HashSet<String> {
- let mut deferred = HashSet::new();
- for tool in tools {
- let name = tool.name();
- if !visible.contains(name) {
- continue;
- }
- match tool.exposure() {
- ToolExposure::Direct => {}
- ToolExposure::Deferred => {
- visible.remove(name);
- deferred.insert(name.to_string());
- }
- ToolExposure::Hidden => {
- visible.remove(name);
- }
- }
- }
- deferred
-}
-
-/// Every [`ToolExposure::Deferred`] tool in `tools`, by name — the catalogue a
-/// belt that opted into discovery can reach whether or not it named them.
-pub fn deferred_tool_names(tools: &[Box<dyn Tool>]) -> HashSet<String> {
- tools
- .iter()
- .filter(|tool| tool.exposure() == ToolExposure::Deferred)
- .map(|tool| tool.name().to_string())
- .collect()
-}
-
-#[cfg(test)]
-#[path = "deferred_tests.rs"]
-mod tests;
+pub use tinytools::{deferred_tool_names, strip_deferred_from_visible};
diff --git a/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs b/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs
deleted file mode 100644
index ce0fb786be..0000000000
--- a/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-use std::collections::HashSet;
-
-use serde_json::json;
-use tinytools::{Tool, ToolExposure, ToolResult};
-
-use super::{deferred_tool_names, strip_deferred_from_visible};
-
-struct Fake(&'static str, ToolExposure);
-
-#[async_trait::async_trait]
-impl Tool for Fake {
- fn name(&self) -> &str {
- self.0
- }
- fn description(&self) -> &str {
- "fake"
- }
- fn parameters_schema(&self) -> serde_json::Value {
- json!({"type": "object"})
- }
- fn exposure(&self) -> ToolExposure {
- self.1
- }
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::success("ok"))
- }
-}
-
-fn tools() -> Vec<Box<dyn Tool>> {
- vec![
- Box::new(Fake("direct", ToolExposure::Direct)),
- Box::new(Fake("deferred", ToolExposure::Deferred)),
- Box::new(Fake("hidden", ToolExposure::Hidden)),
- Box::new(Fake("unlisted_deferred", ToolExposure::Deferred)),
- ]
-}
-
-#[test]
-fn strip_removes_deferred_and_hidden_but_returns_only_deferred() {
- let mut visible: HashSet<String> = ["direct", "deferred", "hidden"]
- .into_iter()
- .map(String::from)
- .collect();
- let deferred = strip_deferred_from_visible(&mut visible, &tools());
- assert_eq!(visible, HashSet::from(["direct".to_string()]));
- assert_eq!(deferred, HashSet::from(["deferred".to_string()]));
-}
-
-#[test]
-fn strip_ignores_tools_the_belt_never_named() {
- let mut visible: HashSet<String> = HashSet::from(["direct".to_string()]);
- let deferred = strip_deferred_from_visible(&mut visible, &tools());
- assert!(deferred.is_empty());
- assert_eq!(visible.len(), 1);
-}
-
-#[test]
-fn deferred_tool_names_lists_every_deferred_registration() {
- assert_eq!(
- deferred_tool_names(&tools()),
- HashSet::from(["deferred".to_string(), "unlisted_deferred".to_string()])
- );
-}
diff --git a/crates/openhuman-core/src/tools/impl/meta/mod.rs b/crates/openhuman-core/src/tools/impl/meta/mod.rs
index 02dfb0e4a2..683a9b6ed6 100644
--- a/crates/openhuman-core/src/tools/impl/meta/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/meta/mod.rs
@@ -8,10 +8,10 @@
//! because neither is a capability the host offers the user — it is the model
//! asking what it is able to do.
-pub mod collapse;
pub mod deferred;
-pub use collapse::{
+pub use tinytools::collapse;
+pub use tinytools::collapse::{
any_external_effect, args_without_action, merge_action_schemas, resolve, strictest_permission,
unknown_action_message, CollapsedAction,
};
diff --git a/crates/openhuman-core/src/tools/impl/system/command_output.rs b/crates/openhuman-core/src/tools/impl/system/command_output.rs
deleted file mode 100644
index c8ebb2a5bc..0000000000
--- a/crates/openhuman-core/src/tools/impl/system/command_output.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-//! 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.
-
-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;
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/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rs
index 404cdcce67..53e938771d 100644
--- a/crates/openhuman-core/src/tools/impl/system/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs
@@ -4,7 +4,6 @@
//! `tools/impl/README.md`; `security_for_tool_context` below is the shared
//! `SecurityPolicy` resolver that must stay in step with the `filesystem` copy.
-mod command_output;
mod current_time;
mod detect_tools;
mod insert_sql_record;
diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
index 648262099e..f1044863e6 100644
--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
@@ -358,7 +358,7 @@ impl NodeExecTool {
} else {
// Surface exit code + both streams so the agent can diagnose
// the failure instead of re-running it (#4095).
- Ok(super::command_output::command_failure(
+ Ok(tinytools::command_failure(
output.status.code(),
&stdout,
&stderr,
@@ -544,8 +544,8 @@ impl NodeExecTool {
))
}
} else {
- super::command_output::command_failure(
- super::command_output::sandbox_exit_code(result.exit_code),
+ tinytools::command_failure(
+ tinytools::sandbox_exit_code(result.exit_code),
&result.stdout,
&result.stderr,
)
@@ -590,7 +590,7 @@ fn pool_outcome_to_result(
ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}"))
}
} else {
- super::command_output::command_failure(outcome.exit_code, &stdout, &stderr)
+ tinytools::command_failure(outcome.exit_code, &stdout, &stderr)
}
}
diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
index 33a70f2484..9aae24e92d 100644
--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
@@ -350,7 +350,7 @@ impl NpmExecTool {
} else {
// Surface exit code + both streams so the agent can diagnose
// the failure instead of re-running it (#4095).
- Ok(super::command_output::command_failure(
+ Ok(tinytools::command_failure(
output.status.code(),
&stdout,
&stderr,
@@ -459,8 +459,8 @@ impl NpmExecTool {
))
}
} else {
- super::command_output::command_failure(
- super::command_output::sandbox_exit_code(result.exit_code),
+ tinytools::command_failure(
+ tinytools::sandbox_exit_code(result.exit_code),
&result.stdout,
&result.stderr,
)
diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
index 21087cac02..6fbf1e71a6 100644
--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
@@ -331,7 +331,7 @@ impl PythonExecTool {
Ok(ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}")))
}
} else {
- Ok(super::command_output::command_failure(
+ Ok(tinytools::command_failure(
output.status.code(),
&stdout,
&stderr,
@@ -471,8 +471,8 @@ impl PythonExecTool {
))
}
} else {
- super::command_output::command_failure(
- super::command_output::sandbox_exit_code(result.exit_code),
+ tinytools::command_failure(
+ tinytools::sandbox_exit_code(result.exit_code),
&result.stdout,
&result.stderr,
)
@@ -515,7 +515,7 @@ fn pool_outcome_to_result(
ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}"))
}
} else {
- super::command_output::command_failure(outcome.exit_code, &stdout, &stderr)
+ tinytools::command_failure(outcome.exit_code, &stdout, &stderr)
}
}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index 88d132977a..e816d97477 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -471,7 +471,7 @@ impl ShellTool {
// Surface the exit code AND both streams so the agent can
// diagnose the failure (e.g. 127 missing dependency, 126
// sandbox/permission wall) instead of looping on it (#4095).
- super::command_output::command_failure(output.status.code(), &stdout, &stderr)
+ tinytools::command_failure(output.status.code(), &stdout, &stderr)
}
}
Ok(Err(e)) => ToolResult::error(format!("Failed to execute command: {e}")),
@@ -558,8 +558,8 @@ impl ShellTool {
} else {
// Same exit-code + both-streams surfacing as the native path
// (#4095); the sandbox `-1` sentinel renders as a signal.
- super::command_output::command_failure(
- super::command_output::sandbox_exit_code(result.exit_code),
+ tinytools::command_failure(
+ tinytools::sandbox_exit_code(result.exit_code),
&result.stdout,
&result.stderr,
)