Skip to content

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

feat(shell): route shell execution through TinyAgents exec ports

Steven Enamakel43f9e6265228
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index 7609f44e77..378a997c37 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -10,12 +10,17 @@ use crate::core::runtime::DispatchCtx;
use crate::modules::tinybox::host_runtime::RuntimeAdapter;
use crate::security::{AuditLogger, CommandExecutionLog, SecurityPolicy};
use async_trait::async_trait;
-use serde_json::json;
+use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tinytools::ToolRunContext;
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};
+use tinyagents_harness_tools::exec::{
+ ExecAuditEvent, ExecAuditOutcome, ExecAuthorizationRequest, ExecBackend, ExecBackendCapability,
+ ExecBackendOutcome, ExecDenied, ExecGate, ExecOperation, ExecOutput, ExecPermit,
+ ExecRefusalKind, ExecRequest, ExecTool, ShellFlavor,
+};
/// Maximum output size in bytes (1MB).
const MAX_OUTPUT_BYTES: usize = 1_048_576;
@@ -741,6 +746,265 @@ impl ShellHost {
}
}
+#[derive(Debug, Clone, Copy)]
+struct HostShellCapability;
+
+/// The host supplies the authorization and execution ports consumed by the
+/// generic TinyAgents exec tool. Runtime routing stays in `ShellHost`, where
+/// OpenHuman applies its sandbox, SaaS, and command policy.
+struct ShellPorts {
+ host: Arc<ShellHost>,
+}
+
+#[async_trait]
+impl ExecGate for ShellPorts {
+ async fn prepare_authorization(&self, args: &Value) -> anyhow::Result<Option<Value>> {
+ self.host.prepare_authorization(args).await
+ }
+
+ fn external_effect_with_args(&self, args: &Value) -> bool {
+ self.host.external_effect_with_args(args)
+ }
+
+ async fn authorize(
+ &self,
+ request: &ExecAuthorizationRequest,
+ context: Option<&dyn ToolRunContext>,
+ ) -> Result<ExecPermit, ExecDenied> {
+ let ExecOperation::Shell {
+ command,
+ category,
+ } = &request.operation
+ else {
+ return Err(ExecDenied("shell gate received a non-shell operation".into()));
+ };
+
+ // Check policy here before issuing a permit. The execution path repeats
+ // the module analysis immediately before launch to close the approval
+ // to execution race and to protect workflow-driven direct calls too.
+ #[cfg(feature = "modules")]
+ {
+ let Some(config) = self.host.analysis_config.as_deref() else {
+ #[cfg(test)]
+ self.host
+ .security
+ .check_gated_command(command)
+ .map_err(ExecDenied)?;
+ #[cfg(not(test))]
+ return Err(ExecDenied("Command analysis is unavailable.".into()));
+ #[cfg(test)]
+ return self.permit(context);
+ };
+ let analysis = crate::modules::tinybox::analyze_command(config, command.clone())
+ .await
+ .map_err(|_| ExecDenied("Command analysis is unavailable.".into()))?;
+ self.host
+ .security
+ .check_gated_command_analysis(&analysis)
+ .map_err(ExecDenied)?;
+ }
+ #[cfg(not(feature = "modules"))]
+ {
+ #[cfg(test)]
+ self.host
+ .security
+ .check_gated_command(command)
+ .map_err(ExecDenied)?;
+ #[cfg(not(test))]
+ return Err(ExecDenied("Command analysis is unavailable.".into()));
+ }
+
+ let _ = category;
+ self.permit(context)
+ }
+
+ fn record(&self, event: ExecAuditEvent) {
+ let (command, risk_level) = match &event.operation {
+ ExecOperation::Shell { command, category } => (
+ command.as_str(),
+ category.as_deref().unwrap_or("unknown"),
+ ),
+ ExecOperation::Install { .. } => ("<invalid shell operation>", "unknown"),
+ };
+ let success = matches!(
+ event.outcome,
+ ExecAuditOutcome::Completed { success: true, .. }
+ );
+ if let Err(error) = self.host.audit.log_command_event(CommandExecutionLog {
+ channel: "tool:shell",
+ 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, channel = "tool:shell", "failed to persist shell audit event");
+ }
+ }
+}
+
+impl ShellPorts {
+ fn permit(&self, context: Option<&dyn ToolRunContext>) -> Result<ExecPermit, ExecDenied> {
+ let action_dir = self.host.effective_action_dir_for_context(context);
+ let environment = command_environment_for_tool(context)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|(name, value)| (name.into(), value.into()))
+ .collect();
+ Ok(ExecPermit {
+ action_dir,
+ environment,
+ backend_selection: "openhuman-runtime".into(),
+ backend_capability: ExecBackendCapability::new(HostShellCapability),
+ })
+ }
+}
+
+#[async_trait]
+impl ExecBackend for ShellPorts {
+ fn shell_flavor(&self) -> ShellFlavor {
+ match self.host.runtime.shell_flavor() {
+ crate::modules::tinybox::contract::ShellFlavor::Cmd => ShellFlavor::Cmd,
+ _ => ShellFlavor::Posix,
+ }
+ }
+
+ async fn execute(
+ &self,
+ request: ExecRequest,
+ context: Option<&dyn ToolRunContext>,
+ _progress: Option<tinyagents_harness_tools::exec::ExecProgress>,
+ ) -> ExecBackendOutcome {
+ if request.backend_selection != "openhuman-runtime"
+ || request
+ .backend_capability
+ .downcast_ref::<HostShellCapability>()
+ .is_none()
+ {
+ return ExecBackendOutcome::Refused {
+ kind: ExecRefusalKind::Preflight,
+ reason: "OpenHuman runtime was not selected or authorized".into(),
+ };
+ }
+ let Some(command) = request.shell_command else {
+ return ExecBackendOutcome::Refused {
+ kind: ExecRefusalKind::Preflight,
+ reason: "shell command is missing".into(),
+ };
+ };
+ let timeout_secs = request.timeout.map(|timeout| timeout.as_secs());
+ let (allowed, result) = crate::sandbox::shell_progress::with_shell_progress(
+ context,
+ crate::sandbox::shell_progress::HEARTBEAT_INTERVAL,
+ |meter| async {
+ self.host
+ .run_with_security_in_context(
+ &dispatch_ctx_for_tool(context),
+ &command,
+ timeout_secs,
+ context,
+ meter,
+ )
+ .await
+ },
+ )
+ .await;
+ if !allowed {
+ return ExecBackendOutcome::Refused {
+ kind: ExecRefusalKind::Preflight,
+ reason: result.output(),
+ };
+ }
+ ExecBackendOutcome::Completed(ExecOutput {
+ stdout: result.output().into_bytes(),
+ stderr: Vec::new(),
+ exit_code: Some(if result.is_error { 1 } else { 0 }),
+ timed_out: false,
+ })
+ }
+}
+
+/// Public OpenHuman adapter that presents the upstream generic exec tool.
+pub struct ShellTool {
+ inner: ExecTool,
+ host: Arc<ShellHost>,
+}
+
+impl ShellTool {
+ pub fn new(
+ security: Arc<SecurityPolicy>,
+ runtime: Arc<dyn RuntimeAdapter>,
+ audit: Arc<AuditLogger>,
+ ) -> Self {
+ Self::from_host(Arc::new(ShellHost::new(security, runtime, audit)))
+ }
+
+ pub fn with_config(
+ security: Arc<SecurityPolicy>,
+ runtime: Arc<dyn RuntimeAdapter>,
+ audit: Arc<AuditLogger>,
+ config: Arc<Config>,
+ ) -> Self {
+ Self::from_host(Arc::new(ShellHost::with_config(
+ security, runtime, audit, config,
+ )))
+ }
+
+ fn from_host(host: Arc<ShellHost>) -> Self {
+ let ports = Arc::new(ShellPorts {
+ host: Arc::clone(&host),
+ });
+ let gate: Arc<dyn ExecGate> = ports.clone();
+ let backend: Arc<dyn ExecBackend> = ports;
+ Self {
+ inner: ExecTool::new(gate, backend),
+ host,
+ }
+ }
+
+ /// Retains the workflow command entry point while the registered agent
+ /// tool uses TinyAgents' generic ExecTool and the same host policy path.
+ pub(crate) async fn run_with_security(
+ &self,
+ ctx: &DispatchCtx,
+ command: &str,
+ requested_timeout: Option<u64>,
+ ) -> (bool, ToolResult) {
+ self.host
+ .run_with_security(ctx, command, requested_timeout)
+ .await
+ }
+}
+
+#[async_trait]
+impl Tool for ShellTool {
+ fn name(&self) -> &str { self.inner.name() }
+ fn description(&self) -> &str { self.inner.description() }
+ fn parameters_schema(&self) -> Value { self.inner.parameters_schema() }
+ fn max_result_size_chars(&self) -> Option<usize> { self.inner.max_result_size_chars() }
+ fn timeout_policy(&self, args: &Value) -> ToolTimeout { self.inner.timeout_policy(args) }
+ fn permission_level(&self) -> PermissionLevel { self.inner.permission_level() }
+ fn external_effect_with_args(&self, args: &Value) -> bool {
+ self.inner.external_effect_with_args(args)
+ }
+ async fn prepare_authorization(&self, args: &Value) -> anyhow::Result<Option<Value>> {
+ self.inner.prepare_authorization(args).await
+ }
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ self.inner.execute(args).await
+ }
+ async fn execute_with_context(
+ &self,
+ args: Value,
+ options: ToolCallOptions,
+ context: Option<&dyn ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let _ = &self.host;
+ self.inner.execute_with_context(args, options, context).await
+ }
+}
+
#[cfg(test)]
#[path = "shell_tests.rs"]
mod tests;