Skip to content

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

feat(shell): describe the host shell and set UTF-8 defaults for children

Steven Enamakel330be3e9fc61
diff --git a/crates/openhuman-core/src/agent/platform_shell.rs b/crates/openhuman-core/src/agent/platform_shell.rs
index ab3295c4c1..acc7df198e 100644
--- a/crates/openhuman-core/src/agent/platform_shell.rs
+++ b/crates/openhuman-core/src/agent/platform_shell.rs
@@ -29,6 +29,30 @@
use std::path::Path;
+/// Which shell family [`build_tokio_command`] / [`build_std_command`] spawn.
+///
+/// A value rather than a bare `cfg!(windows)` so what is *told* to the model
+/// about the shell (the `shell` tool's description) can be built and tested for
+/// either platform on any host.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ShellFlavor {
+ /// `cmd.exe /C <command>` (Windows).
+ Cmd,
+ /// `bash -lc` / `sh -lc` (everything else).
+ Posix,
+}
+
+impl ShellFlavor {
+ /// The flavor this host spawns.
+ pub fn current() -> Self {
+ if cfg!(windows) {
+ Self::Cmd
+ } else {
+ Self::Posix
+ }
+ }
+}
+
/// Environment variables a Windows child process needs before it can run at
/// all, beyond the functional allow-list each launcher already forwards.
///
@@ -201,10 +225,9 @@ pub fn build_std_command(command: &str) -> std::process::Command {
/// platform matrix (adding pwsh, changing pipefail semantics) belong here plus
/// [`configure_shell_args`], so both `Command` flavours stay in lockstep.
fn shell_program() -> &'static str {
- if cfg!(windows) {
- "cmd"
- } else {
- bash_path().unwrap_or("sh")
+ match ShellFlavor::current() {
+ ShellFlavor::Cmd => "cmd",
+ ShellFlavor::Posix => bash_path().unwrap_or("sh"),
}
}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index 4fc56f5c4f..6b44c34669 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -1,4 +1,5 @@
use crate::agent::host_runtime::RuntimeAdapter;
+use crate::agent::platform_shell::ShellFlavor;
use crate::runtime::javascript::NodeBootstrap;
use crate::runtime::python::PythonBootstrap;
use crate::security::{AuditLogger, CommandExecutionLog, GateDecision, SecurityPolicy};
@@ -39,6 +40,78 @@ const SAFE_ENV_VARS: &[&str] = &[
"ProgramW6432",
];
+/// Python's text-encoding defaults for a shell child, unless the parent sets
+/// its own. Under `cmd.exe` the console code page is a legacy one (cp1252,
+/// cp437), so a script printing anything outside it dies with
+/// `UnicodeEncodeError: 'charmap' codec can't encode …`. UTF-8 mode
+/// (`PYTHONUTF8`) fixes `open()` and the stdio defaults; `PYTHONIOENCODING`
+/// covers interpreters older than 3.7 and stdio explicitly. Both are no-ops
+/// for a non-Python command and on a host whose locale is already UTF-8.
+const PYTHON_UTF8_DEFAULTS: &[(&str, &str)] = &[("PYTHONUTF8", "1"), ("PYTHONIOENCODING", "utf-8")];
+
+/// The Python encoding variables for a child: the parent's own value when
+/// `lookup` has one, else [`PYTHON_UTF8_DEFAULTS`].
+fn python_utf8_env(
+ lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
+) -> Vec<(&'static str, std::ffi::OsString)> {
+ PYTHON_UTF8_DEFAULTS
+ .iter()
+ .map(|(name, default)| {
+ let value = lookup(name).unwrap_or_else(|| (*default).into());
+ (*name, value)
+ })
+ .collect()
+}
+
+/// The environment a native shell child starts from after `env_clear()`:
+/// every [`SAFE_ENV_VARS`] name `lookup` (the parent environment) has, plus
+/// [`python_utf8_env`].
+///
+/// `var_os`, not `var`: a value that is not valid Unicode (possible on both
+/// Windows and Unix) used to be dropped silently. Lookups through
+/// `std::env::var_os` are case-insensitive on Windows, so `USERPROFILE`
+/// matches a parent that spells it `UserProfile`.
+fn shell_child_env(
+ lookup: impl Fn(&str) -> Option<std::ffi::OsString>,
+) -> Vec<(&'static str, std::ffi::OsString)> {
+ let mut env: Vec<(&'static str, std::ffi::OsString)> = SAFE_ENV_VARS
+ .iter()
+ .filter_map(|name| lookup(name).map(|value| (*name, value)))
+ .collect();
+ env.extend(python_utf8_env(&lookup));
+ env
+}
+
+/// The `shell` tool description for the shell this host spawns. Models default
+/// to POSIX syntax, so on Windows the description says outright that commands
+/// run under `cmd.exe` and gives the equivalents of the commands they reach for.
+fn shell_description(flavor: ShellFlavor) -> &'static str {
+ match flavor {
+ ShellFlavor::Cmd => {
+ "Execute a command under Windows cmd.exe (`cmd /C`), not a POSIX shell: run code, \
+ manipulate workspace files, or launch applications (`start \"\" music:`). Use cmd \
+ syntax: `cd` with no argument prints the current directory (no `pwd`), `dir` lists \
+ (no `ls`), `type` prints a file (no `cat`), `findstr` searches (no `grep`), \
+ `del`/`copy`/`move` replace rm/cp/mv, variables are `%VAR%` (not `$VAR`), and \
+ commands chain with `&&` (`;` is not a separator). For PowerShell run \
+ `powershell -NoProfile -Command \"...\"`. Only stdout/stderr comes back, so a script \
+ that computes silently or only writes a file returns nothing — print what you need, \
+ or read the file afterwards."
+ }
+ ShellFlavor::Posix => {
+ "Execute a shell command: run code, manipulate workspace files, or launch applications (`open -a Music`, `xdg-open music://`). Only stdout/stderr comes back, so a script that computes silently or only writes a file returns nothing — print what you need, or read the file afterwards."
+ }
+ }
+}
+
+/// The `command` parameter's description, matching [`shell_description`].
+fn command_param_description(flavor: ShellFlavor) -> &'static str {
+ match flavor {
+ ShellFlavor::Cmd => "The cmd.exe command to execute (cmd syntax, not POSIX)",
+ ShellFlavor::Posix => "The shell command to execute",
+ }
+}
+
/// Exit status coreutils `timeout` returns when its own limit expires.
const COMMAND_TIMEOUT_EXIT_CODE: i32 = 124;
/// Appended to an exit-124 failure: the command's own `timeout` fired, not the
@@ -192,7 +265,7 @@ impl Tool for ShellTool {
}
fn description(&self) -> &str {
- "Execute a shell command: run code, manipulate workspace files, or launch applications (`open -a Music`, `xdg-open music://`). Only stdout/stderr comes back, so a script that computes silently or only writes a file returns nothing — print what you need, or read the file afterwards."
+ shell_description(ShellFlavor::current())
}
fn parameters_schema(&self) -> serde_json::Value {
@@ -201,7 +274,7 @@ impl Tool for ShellTool {
"properties": {
"command": {
"type": "string",
- "description": "The shell command to execute"
+ "description": command_param_description(ShellFlavor::current())
},
"category": {
"type": "string",
@@ -415,10 +488,8 @@ impl ShellTool {
};
cmd.env_clear();
- for var in SAFE_ENV_VARS {
- if let Ok(val) = std::env::var(var) {
- cmd.env(var, val);
- }
+ for (var, val) in shell_child_env(|name| std::env::var_os(name)) {
+ cmd.env(var, val);
}
// Keep command-valued repository Git settings from executing host
@@ -552,6 +623,10 @@ impl ShellTool {
// Apply the same Git config hardening to local and sandboxed shells.
extra_env.extend(tinytools_std::filesystem::shell_git_env());
+ // And the same Python UTF-8 defaults the native path sets.
+ for (var, val) in python_utf8_env(|name| std::env::var_os(name)) {
+ extra_env.insert(var.into(), val);
+ }
// Sandbox backends require a finite deadline. Without an explicit
// `timeout_secs`, substitute the generous effective-unbounded cap so a