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
feat(system): delegate install_tool to shared harness installer
Steven Enamakel2a7c06b32bd4
diff --git a/crates/openhuman-core/src/tools/impl/system/exec_adapters.rs b/crates/openhuman-core/src/tools/impl/system/exec_adapters.rsnew file mode 100644index 0000000000..bb516933d4--- /dev/null+++ b/crates/openhuman-core/src/tools/impl/system/exec_adapters.rs@@ -0,0 +1,108 @@+//! OpenHuman policy adapters for TinyAgents' generic execution tools.++use std::{path::PathBuf, sync::Arc};++use async_trait::async_trait;+use serde_json::Value;+use tinyagents_harness_tools::exec::{+ ExecAuditEvent, ExecAuditOutcome, ExecAuthorizationRequest, ExecBackendCapability,+ ExecDenied, ExecGate, ExecOperation, ExecPermit, ExecRefusalKind, NativeExecCapability,+};+use tinytools::ToolRunContext;++use crate::{+ agent::tinyagents::host::run_context::approval_for_tool,+ security::{AuditLogger, CommandExecutionLog, SecurityPolicy},+};++/// Host-owned gate for package installation. The generic TinyAgents tool owns+/// argument validation and process-result formatting; OpenHuman owns whether+/// a host install is permitted.+pub(super) struct InstallGate {+ pub security: Arc<SecurityPolicy>,+ pub audit: Arc<AuditLogger>,+}++#[async_trait]+impl ExecGate for InstallGate {+ async fn prepare_authorization(&self, _args: &Value) -> anyhow::Result<Option<Value>> {+ Ok(None)+ }++ fn external_effect_with_args(&self, _args: &Value) -> bool {+ true+ }++ async fn authorize(+ &self,+ request: &ExecAuthorizationRequest,+ context: Option<&dyn ToolRunContext>,+ ) -> Result<ExecPermit, ExecDenied> {+ let ExecOperation::Install { .. } = &request.operation else {+ return Err(ExecDenied("install gate received a non-install operation".into()));+ };+ if crate::core::runtime::is_saas() {+ return Err(ExecDenied(+ "[policy-denied] Package installation is unavailable in SaaS mode.".into(),+ ));+ }+ if !approval_for_tool(context).is_interactive() {+ return Err(ExecDenied(+ "[policy-denied] install_tool requires interactive approval and is not available in autonomous (background) turns.".into(),+ ));+ }+ if !self.security.allow_tool_install {+ return Err(ExecDenied(+ "[policy-denied] OS package installation is disabled. Enable it in the agent access settings (Full access mode / allow_tool_install) before installing tools.".into(),+ ));+ }+ if !self.security.can_act() {+ return Err(ExecDenied(+ "[policy-blocked] Action blocked: autonomy is read-only.".into(),+ ));+ }+ if self.security.is_rate_limited() || !self.security.record_action() {+ return Err(ExecDenied(+ "Rate limit exceeded: too many actions in the last hour".into(),+ ));+ }+ Ok(ExecPermit {+ action_dir: PathBuf::from(&self.security.workspace_dir),+ environment: Default::default(),+ backend_selection: "native".into(),+ backend_capability: ExecBackendCapability::new(NativeExecCapability),+ })+ }++ fn record(&self, event: ExecAuditEvent) {+ let (command, risk_level) = match &event.operation {+ ExecOperation::Install { package, manager } => {+ (format!("{manager} install {package}"), "install")+ }+ ExecOperation::Shell { command, category } => {+ (command.clone(), category.as_deref().unwrap_or("unknown"))+ }+ };+ let success = matches!(+ event.outcome,+ ExecAuditOutcome::Completed { success: true, .. }+ );+ if let Err(error) = self.audit.log_command_event(CommandExecutionLog {+ channel: "tool:install_tool",+ command: &command,+ risk_level,+ approved: event.approval_required,+ allowed: event.allowed,+ success,+ duration_ms: u64::try_from(event.duration.as_millis()).unwrap_or(u64::MAX),+ }) {+ tracing::warn!(error = %error, "[install_tool] failed to persist execution audit event");+ }+ if let ExecAuditOutcome::BackendRefused {+ kind: ExecRefusalKind::BackendUnavailable,+ } = event.outcome+ {+ tracing::warn!("[install_tool] selected execution backend is unavailable");+ }+ }+}diff --git a/crates/openhuman-core/src/tools/impl/system/install_tool.rs b/crates/openhuman-core/src/tools/impl/system/install_tool.rsindex 1fa51dcc94..d09d65fb64 100644--- a/crates/openhuman-core/src/tools/impl/system/install_tool.rs+++ b/crates/openhuman-core/src/tools/impl/system/install_tool.rs@@ -1,263 +1,85 @@-//! Tool: install_tool — install an OS / language package, heavily gated.-//!-//! This is the highest-blast-radius tool: it changes the user's machine. It is-//! therefore gated on `SecurityPolicy.allow_tool_install` (intended to be set-//! only in Full access mode), runs the package manager via an explicit argv-//! (never a shell string, so the package name can't inject commands), validates-//! the package name against a strict charset, and records an audit log line.-//!-//! It deliberately does NOT auto-prepend `sudo`: system managers that need root-//! (apt/dnf/pacman) will surface a permissions error, which the agent should-//! relay rather than silently escalate. User-scoped managers (brew, pipx,-//! `npm -g`, `cargo install`) work without elevation.+use std::sync::Arc;-use crate::security::SecurityPolicy;use async_trait::async_trait;-use serde_json::json;-use std::sync::Arc;-use std::time::Duration;-use tinytools::{PermissionLevel, Tool, ToolResult};-use tokio::process::Command as TokioCommand;+use serde_json::Value;+use tinyagents_harness_tools::exec::{ExecBackend, InstallTool};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext, ToolTimeout};-use tinyagents_harness_tools::exec::detect_tools::find_on_path;+use crate::security::{AuditLogger, SecurityPolicy};-/// Hard cap on an install before it is killed.-const INSTALL_TIMEOUT_SECS: u64 = 300;-/// Per-stream cap on captured installer output (1 MiB) — verbose package-/// managers can emit very large stdout/stderr and spike memory.-const MAX_OUTPUT_BYTES: usize = 1_048_576;+use super::exec_adapters::InstallGate;+/// OpenHuman host adapter for TinyAgents' generic package installer.pub struct InstallToolTool {- security: Arc<SecurityPolicy>,+ inner: InstallTool,}impl InstallToolTool {pub fn new(security: Arc<SecurityPolicy>) -> Self {- Self { security }+ Self::with_audit(security, AuditLogger::disabled())}-}-/// Map a manager id to its binary + the argv prefix that precedes the package.-fn manager_argv(manager: &str) -> Option<(&'static str, Vec<&'static str>)> {- match manager {- "apt" | "apt-get" => Some(("apt-get", vec!["install", "-y"])),- "dnf" => Some(("dnf", vec!["install", "-y"])),- "yum" => Some(("yum", vec!["install", "-y"])),- "pacman" => Some(("pacman", vec!["-S", "--noconfirm"])),- "apk" => Some(("apk", vec!["add"])),- "brew" => Some(("brew", vec!["install"])),- "winget" => Some(("winget", vec!["install", "-e", "--id"])),- "pipx" => Some(("pipx", vec!["install"])),- "npm" => Some(("npm", vec!["install", "-g"])),- "cargo" => Some(("cargo", vec!["install"])),- _ => None,+ pub fn with_audit(security: Arc<SecurityPolicy>, audit: Arc<AuditLogger>) -> Self {+ let gate = Arc::new(InstallGate {+ security,+ audit,+ });+ let backend: Arc<dyn ExecBackend> = Arc::new(+ tinyagents_harness_tools::exec::NativeExecBackend::new(+ tinyagents_harness_tools::exec::ShellFlavor::Posix,+ ),+ );+ Self {+ inner: InstallTool::new(gate, backend),+ }}}-/// Best-effort detection of the host's system package manager.-fn detect_system_manager() -> Option<&'static str> {- ["apt-get", "dnf", "yum", "pacman", "apk", "brew", "winget"]- .into_iter()- .find(|&m| find_on_path(m).is_some())- .map(|v| v as _)-}--/// A package name is accepted only if it contains exclusively characters that-/// appear in real package identifiers — letters, digits and `._+-@/:`. This-/// blocks shell metacharacters even though we never build a shell string.-fn is_valid_package_name(pkg: &str) -> bool {- !pkg.is_empty()- && pkg.len() <= 200- && pkg.chars().all(|c| {- c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-' | '@' | '/' | ':')- })-}-#[async_trait]impl Tool for InstallToolTool {fn name(&self) -> &str {- "install_tool"+ self.inner.name()}fn description(&self) -> &str {- "Install an OS or language package on the host (apt/dnf/pacman/apk/brew/winget/pipx/\- npm -g/cargo). HIGH IMPACT: only available when the user has enabled tool installation \- (Full access mode). Prefer detect_tools first; only install what's actually missing."+ self.inner.description()}- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "package": {- "type": "string",- "description": "Package name to install (e.g. 'ripgrep', 'jq', '@scope/cli')."- },- "manager": {- "type": "string",- "enum": ["apt", "apt-get", "dnf", "yum", "pacman", "apk", "brew", "winget", "pipx", "npm", "cargo"],- "description": "Package manager to use. If omitted, the host's system package manager is auto-detected."- }- },- "required": ["package"]- })+ fn parameters_schema(&self) -> Value {+ self.inner.parameters_schema()}fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous+ self.inner.permission_level()}fn external_effect(&self) -> bool {- true+ self.inner.external_effect()}- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_with_context(args, tinytools::ToolCallOptions::default(), None)- .await+ fn external_effect_with_args(&self, args: &Value) -> bool {+ self.inner.external_effect_with_args(args)}- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: tinytools::ToolCallOptions,- context: Option<&dyn tinytools::ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let approval = crate::agent::tinyagents::host::run_context::approval_for_tool(context);- self.run(args, &approval).await+ fn timeout_policy(&self, args: &Value) -> ToolTimeout {+ self.inner.timeout_policy(args)}-}--impl InstallToolTool {- /// Runs the install for a turn whose approval context is `approval`.- pub(crate) async fn run(- &self,- args: serde_json::Value,- approval: &crate::security::approval::ApprovalTurnContext,- ) -> anyhow::Result<ToolResult> {- // Gate 0: installs mutate the host (not the workspace), so they must- // never run without an explicit human Approve. The ApprovalGate only- // parks for an interactive turn (a chat context on the turn's approval- // context, set on the web-chat path); background / triage / cron turns- // bypass the gate entirely. Fail closed there — a doomed retry is- // short-circuited by the `[policy-denied]` marker.- if !approval.is_interactive() {- return Ok(ToolResult::error(- "[policy-denied] install_tool requires interactive approval and is not available \- in autonomous (background) turns.",- ));- }- // Gate 1: feature must be explicitly enabled (Full access mode).- if !self.security.allow_tool_install {- return Ok(ToolResult::error(- "[policy-denied] OS package installation is disabled. Enable it in the agent access settings \- (Full access mode / allow_tool_install) before installing tools.",- ));- }- // Gate 2: read-only autonomy never installs.- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: autonomy is read-only.",- ));- }- // Gate 3: rate limit.- if self.security.is_rate_limited() {- return Ok(ToolResult::error(- "Rate limit exceeded: too many actions in the last hour",- ));- }-- let package = match args.get("package").and_then(|v| v.as_str()) {- Some(p) => p.trim(),- None => return Ok(ToolResult::error("Missing 'package' parameter")),- };- if !is_valid_package_name(package) {- return Ok(ToolResult::error(format!(- "Invalid package name '{package}': only letters, digits and ._+-@/: are allowed"- )));- }-- let manager = match args.get("manager").and_then(|v| v.as_str()) {- Some(m) => m.to_string(),- None => match detect_system_manager() {- Some(m) => m.to_string(),- None => {- return Ok(ToolResult::error(- "No supported package manager detected on PATH. Pass 'manager' explicitly \- (e.g. brew, pipx, npm, cargo).",- ));- }- },- };- let Some((program, prefix)) = manager_argv(&manager) else {- return Ok(ToolResult::error(format!(- "Unsupported package manager '{manager}'"- )));- };- if find_on_path(program).is_none() {- return Ok(ToolResult::error(format!(- "Package manager '{program}' is not installed on PATH"- )));- }-- // Spend an action against the rate budget.- if !self.security.record_action() {- return Ok(ToolResult::error(- "Rate limit exceeded: action budget exhausted",- ));- }-- tracing::warn!(- channel = "tool:install_tool",- manager = %program,- package = %package,- "[install_tool] installing OS package (gated by allow_tool_install)"- );-- let mut cmd = TokioCommand::new(program);- cmd.args(&prefix).arg(package);- cmd.current_dir(&self.security.workspace_dir);+ async fn prepare_authorization(&self, args: &Value) -> anyhow::Result<Option<Value>> {+ self.inner.prepare_authorization(args).await+ }- let output = match tinyagents_harness_tools::exec::timeout::output_or_kill(- &mut cmd,- Duration::from_secs(INSTALL_TIMEOUT_SECS),- )- .await- {- Ok(Ok(out)) => out,- Ok(Err(e)) => {- return Ok(ToolResult::error(format!(- "Failed to launch {program}: {e}"- )));- }- Err(_) => {- return Ok(ToolResult::error(format!(- "Install timed out after {INSTALL_TIMEOUT_SECS}s and was killed"- )));- }- };+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ self.inner.execute(args).await+ }- let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();- let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1 MiB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1 MiB]");- }- if output.status.success() {- Ok(ToolResult::success(format!(- "Installed '{package}' via {program}.\n{stdout}"- )))- } else {- Ok(ToolResult::error(format!(- "{program} failed to install '{package}' (exit {:?}).\n{}",- output.status.code(),- if stderr.is_empty() { stdout } else { stderr }- )))- }+ async fn execute_with_context(+ &self,+ args: Value,+ options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ self.inner.execute_with_context(args, options, context).await}}diff --git a/crates/openhuman-core/src/tools/impl/system/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rsindex c3932264cc..02a47174ea 100644--- a/crates/openhuman-core/src/tools/impl/system/mod.rs+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs@@ -4,6 +4,7 @@//! `tools/impl/README.md`.mod install_tool;+mod exec_adapters;mod proxy_config;mod retrieve_tool_output;mod schedule;