Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

configure session kernel bash shells (#3540)

ktcf119a7a8c86
diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rs
index 87ecc26a56..8ffd6e7b82 100644
--- a/crates/pa-core/src/kernel/provisioner.rs
+++ b/crates/pa-core/src/kernel/provisioner.rs
@@ -1292,6 +1292,102 @@ pub fn provisioner_for_path(
mod tests {
use super::*;
+ /// A shell file the resolver accepts: existing, and executable on unix.
+ fn executable_shell(dir: &Path, name: &str) -> PathBuf {
+ let path = dir.join(name);
+ std::fs::write(&path, b"").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ path
+ }
+
+ /// The scripted session both shell-setting tests build: a model and
+ /// `stream_fn` the settings validation never reaches, no kernel prewarm.
+ async fn shell_test_session(
+ cwd: PathBuf,
+ agent_dir: PathBuf,
+ ) -> anyhow::Result<crate::session_engine::engine::SessionEngine> {
+ use crate::session_engine::engine::{create_session, SessionEngineConfig};
+
+ let model = pa_agent::types::Model {
+ id: "shell-test".into(),
+ name: "Shell test".into(),
+ api: "test".into(),
+ provider: "test".into(),
+ base_url: "http://localhost".into(),
+ reasoning: false,
+ cost: pa_agent::types::UsageCost::default(),
+ context_window: 1_000,
+ max_tokens: 100,
+ max_tokens_explicit: false,
+ };
+ let provider = Arc::new(pa_agent::scripted::ScriptedProvider::new(model.clone()));
+ create_session(SessionEngineConfig {
+ cwd,
+ agent_dir,
+ model: Some(model),
+ stream_fn: Some(provider.stream_fn()),
+ prewarm_ipython_kernel: Some(false),
+ ..Default::default()
+ })
+ .await
+ }
+
+ #[tokio::test]
+ async fn session_settings_reach_the_kernel_shell() {
+ let dir = tempfile::tempdir().unwrap();
+ let agent_dir = dir.path().join("agent");
+ let cwd = dir.path().join("project");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ std::fs::create_dir_all(cwd.join(".prime/agent")).unwrap();
+ // Project settings override the global setting before the session captures it.
+ let global = executable_shell(dir.path(), "global-bash");
+ let project = executable_shell(dir.path(), "project-bash");
+ std::fs::write(
+ agent_dir.join("settings.json"),
+ serde_json::json!({ "shellPath": global.to_string_lossy() }).to_string(),
+ )
+ .unwrap();
+ std::fs::write(
+ cwd.join(".prime/agent/settings.json"),
+ serde_json::json!({ "shellPath": format!(" {} ", project.to_string_lossy()) })
+ .to_string(),
+ )
+ .unwrap();
+ let engine = shell_test_session(cwd, agent_dir).await.unwrap();
+ assert_eq!(engine.provisioner.inner.options.shell_path, Some(project));
+ }
+
+ #[tokio::test]
+ async fn session_settings_reject_a_missing_shell_path() {
+ let dir = tempfile::tempdir().unwrap();
+ let agent_dir = dir.path().join("agent");
+ let cwd = dir.path().join("project");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ std::fs::create_dir_all(cwd.join(".prime/agent")).unwrap();
+ let missing = cwd.join("no-such-shell");
+ std::fs::write(
+ cwd.join(".prime/agent/settings.json"),
+ serde_json::json!({ "shellPath": missing.to_string_lossy() }).to_string(),
+ )
+ .unwrap();
+ let Err(err) = shell_test_session(cwd, agent_dir).await else {
+ panic!("create_session must reject a missing shellPath");
+ };
+ let message = err.to_string();
+ assert!(
+ message.contains("shellPath"),
+ "error names the setting: {message}"
+ );
+ assert!(
+ message.contains(missing.to_string_lossy().as_ref()),
+ "error names the path: {message}"
+ );
+ }
+
#[test]
fn a_spent_stop_arm_releases_only_its_own_boot() {
let provisioner = IpythonKernelProvisioner::new(
diff --git a/crates/pa-core/src/platform/shell.rs b/crates/pa-core/src/platform/shell.rs
index fa90190308..258ebc2115 100644
--- a/crates/pa-core/src/platform/shell.rs
+++ b/crates/pa-core/src/platform/shell.rs
@@ -3,7 +3,6 @@
//! the canonical install dirs, then `where bash.exe` (System32 candidates
//! demoted to last — the WSL launcher), never PATH for the kernel shell.
-#[cfg(any(unix, windows))]
use std::path::Path;
/// Shell program plus the fixed argument list used to run a command string.
@@ -13,21 +12,44 @@ pub struct ShellConfig {
pub args: Vec<String>,
}
+/// One predicate for every explicit `shellPath` consumer (the user-bash
+/// [`get_shell_config`] and the kernel [`resolve_kernel_bash_shell`]):
+/// the same setting fails the same way everywhere, naming the setting.
+///
+/// # Errors
+///
+/// Error when the path does not exist or (on unix) is not an executable
+/// regular file.
+fn check_custom_shell_path(path: &str) -> anyhow::Result<()> {
+ if !Path::new(path).exists() {
+ anyhow::bail!("Custom shell path not found: {path} (shellPath setting)");
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let executable = std::fs::metadata(path)
+ .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0);
+ if !executable {
+ anyhow::bail!("Custom shell path is not executable: {path} (shellPath setting)");
+ }
+ }
+ Ok(())
+}
+
/// Resolve the shell to run commands with, honoring an explicit custom path.
///
/// # Errors
///
-/// Error when the explicit custom shell path does not exist; built-ins never fail.
+/// Error when the explicit custom shell path fails [`check_custom_shell_path`];
+/// the built-ins never fail.
#[cfg(unix)]
pub fn get_shell_config(custom_shell_path: Option<&str>) -> anyhow::Result<ShellConfig> {
if let Some(path) = custom_shell_path {
- if Path::new(path).exists() {
- return Ok(ShellConfig {
- shell: path.to_string(),
- args: vec!["-c".to_string()],
- });
- }
- return Err(anyhow::anyhow!("Custom shell path not found: {path}"));
+ check_custom_shell_path(path)?;
+ return Ok(ShellConfig {
+ shell: path.to_string(),
+ args: vec!["-c".to_string()],
+ });
}
if Path::new("/bin/bash").exists() {
@@ -56,15 +78,13 @@ pub fn get_shell_config(custom_shell_path: Option<&str>) -> anyhow::Result<Shell
///
/// # Errors
///
-/// Error when the explicit path does not exist; the fallbacks otherwise
-/// resolve or name the classes searched.
+/// Error when the explicit path fails [`check_custom_shell_path`]; the
+/// fallbacks otherwise resolve or name the classes searched.
#[cfg(windows)]
pub fn get_shell_config(custom_shell_path: Option<&str>) -> anyhow::Result<ShellConfig> {
if let Some(path) = custom_shell_path {
- if Path::new(path).exists() {
- return Ok(bash_config(path));
- }
- return Err(anyhow::anyhow!("Custom shell path not found: {path}"));
+ check_custom_shell_path(path)?;
+ return Ok(bash_config(path));
}
let paths = windows_git_bash_search_paths();
@@ -172,14 +192,12 @@ fn windows_git_bash_search_paths() -> Vec<String> {
paths
}
-/// Absolute default shell for the kernel's `bash()`: explicit path wins;
-/// POSIX uses `/bin/bash` else `/bin/sh`. `None` when no shell resolves
-/// (kernel startup must not fail; `bash()` raises its teaching error).
+/// Absolute default shell for the kernel's `bash()` when no `shellPath` is
+/// configured: POSIX uses `/bin/bash` else `/bin/sh`. `None` when no shell
+/// resolves (kernel startup must not fail; `bash()` raises its teaching error).
#[cfg(unix)]
-pub fn resolve_kernel_bash_shell(custom_shell_path: Option<&str>) -> Option<String> {
- if let Some(explicit) = custom_shell_path.map(str::trim).filter(|s| !s.is_empty()) {
- return Some(explicit.to_string());
- }
+#[must_use]
+pub fn default_kernel_bash_shell() -> Option<String> {
if Path::new("/bin/bash").exists() {
Some("/bin/bash".to_string())
} else {
@@ -187,19 +205,17 @@ pub fn resolve_kernel_bash_shell(custom_shell_path: Option<&str>) -> Option<Stri
}
}
-/// Windows: canonical Git Bash install paths only, never PATH (TS
-/// `resolveKernelBashShell` win32): a repo-controlled PATH must not pick
-/// the kernel shell, and hardcoded candidates avoid ambient attacker-
+/// Windows default: the canonical Git Bash install paths only, never PATH
+/// (TS `resolveKernelBashShell` win32): a repo-controlled PATH must not
+/// pick the kernel shell, and hardcoded candidates avoid ambient attacker-
/// influenceable `ProgramFiles` input. `None`: `bash()` raises its teaching error.
#[cfg(windows)]
-pub fn resolve_kernel_bash_shell(custom_shell_path: Option<&str>) -> Option<String> {
+#[must_use]
+pub fn default_kernel_bash_shell() -> Option<String> {
const WINDOWS_GIT_BASH_PATHS: [&str; 2] = [
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files (x86)\Git\bin\bash.exe",
];
- if let Some(explicit) = custom_shell_path.map(str::trim).filter(|s| !s.is_empty()) {
- return Some(explicit.to_string());
- }
WINDOWS_GIT_BASH_PATHS
.into_iter()
.find(|path| Path::new(path).exists())
@@ -207,11 +223,31 @@ pub fn resolve_kernel_bash_shell(custom_shell_path: Option<&str>) -> Option<Stri
}
#[cfg(not(any(unix, windows)))]
-pub fn resolve_kernel_bash_shell(custom_shell_path: Option<&str>) -> Option<String> {
- custom_shell_path
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
+#[must_use]
+pub fn default_kernel_bash_shell() -> Option<String> {
+ None
+}
+
+/// Resolve the absolute shell for the kernel's `bash()` from an explicit
+/// `shellPath`, validated here so a bad setting fails session creation
+/// once instead of every kernel `bash()` call: a trimmed non-empty
+/// explicit path must be absolute and pass [`check_custom_shell_path`];
+/// anything else falls back to [`default_kernel_bash_shell`].
+///
+/// # Errors
+///
+/// Error naming the path and the `shellPath` setting when the explicit
+/// path is relative, missing, or (on unix) not executable. The default
+/// never fails.
+pub fn resolve_kernel_bash_shell(custom: Option<&str>) -> anyhow::Result<Option<String>> {
+ if let Some(path) = custom.map(str::trim).filter(|s| !s.is_empty()) {
+ if !Path::new(path).is_absolute() {
+ anyhow::bail!("Custom shell path must be absolute: {path} (shellPath setting)");
+ }
+ check_custom_shell_path(path)?;
+ return Ok(Some(path.to_string()));
+ }
+ Ok(default_kernel_bash_shell())
}
#[cfg(all(test, windows))]
@@ -246,22 +282,63 @@ mod windows_tests {
assert_eq!(order_windows_bash_candidates(&candidates, None), candidates);
}
- /// The kernel shell candidates are the hardcoded Git Bash paths, not
- /// PATH-derived (a repo-controlled PATH must not pick the kernel
- /// shell); an explicit path always wins.
+ /// An explicit path is validated (it must exist) and wins over the
+ /// hardcoded Git Bash candidates; without one the resolution is the
+ /// platform default.
#[test]
fn kernel_shell_prefers_explicit_then_hardcoded_git_bash() {
+ let dir = tempfile::tempdir().unwrap();
+ let explicit = dir.path().join("bash.exe");
+ std::fs::write(&explicit, b"").unwrap();
+ let explicit = explicit.to_string_lossy().to_string();
assert_eq!(
- resolve_kernel_bash_shell(Some(" C:/my/bash.exe ")),
- Some("C:/my/bash.exe".to_string())
+ resolve_kernel_bash_shell(Some(format!(" {explicit} ").as_str())).unwrap(),
+ Some(explicit)
);
- // Hardcoded candidates are environment-independent: absent on a
- // clean CI runner, the resolution is None (bash() raises its
- // teaching error, kernel startup still succeeds).
- let clean = !Path::new(r"C:\Program Files\Git\bin\bash.exe").exists()
- && !Path::new(r"C:\Program Files (x86)\Git\bin\bash.exe").exists();
- if clean {
- assert_eq!(resolve_kernel_bash_shell(None), None);
+ assert_eq!(
+ resolve_kernel_bash_shell(None).unwrap(),
+ default_kernel_bash_shell()
+ );
+ }
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ /// A rejected explicit shell: the error names the path and the
+ /// `shellPath` setting, whatever the validation failure was.
+ #[test]
+ fn explicit_shell_paths_are_validated() {
+ for path in ["relative/bash", "/no/such/shell"] {
+ let message = resolve_kernel_bash_shell(Some(path))
+ .unwrap_err()
+ .to_string();
+ assert!(message.contains("shellPath"), "{path}: {message}");
+ assert!(message.contains(path), "{path}: {message}");
}
+ let dir = tempfile::tempdir().unwrap();
+ let not_executable = dir.path().join("shell");
+ std::fs::write(&not_executable, b"").unwrap();
+ let path = not_executable.to_string_lossy().to_string();
+ let message = resolve_kernel_bash_shell(Some(path.as_str()))
+ .unwrap_err()
+ .to_string();
+ assert!(message.contains("shellPath"), "not executable: {message}");
+ assert!(message.contains(&path), "not executable: {message}");
+ }
+
+ #[test]
+ fn padded_executable_shell_resolves_trimmed() {
+ let dir = tempfile::tempdir().unwrap();
+ let shell = dir.path().join("bash");
+ std::fs::write(&shell, b"").unwrap();
+ std::fs::set_permissions(&shell, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let padded = format!(" {} ", shell.to_string_lossy());
+ assert_eq!(
+ resolve_kernel_bash_shell(Some(padded.as_str())).unwrap(),
+ Some(shell.to_string_lossy().to_string())
+ );
}
}
diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rs
index f66602fc75..c98f98090a 100644
--- a/crates/pa-core/src/session_engine/engine.rs
+++ b/crates/pa-core/src/session_engine/engine.rs
@@ -209,6 +209,13 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S
};
let (settings, trace_consent) =
crate::agent_traces::ContinuousTraceUpload::load_settings(&cwd, &config.agent_dir);
+ // Resolve the kernel shell once, before any side effects: an invalid
+ // `shellPath` must fail session creation with a clear config error
+ // naming the setting, not every kernel `bash()` call later.
+ let kernel_shell_path = crate::platform::shell::resolve_kernel_bash_shell(
+ settings.settings().shell_path.as_deref(),
+ )?
+ .map(std::path::PathBuf::from);
let traces = session_manager
.is_persisted()
.then(|| {
@@ -429,6 +436,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S
python_skills,
cwd.clone(),
&config.agent_dir,
+ kernel_shell_path,
session_artifact_dir,
on_restore,
config.on_background_work_settled.clone(),
diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rs
index 75eedd9cf6..5d2f6f3ccf 100644
--- a/crates/pa-core/src/session_engine/runtime_wiring.rs
+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs
@@ -210,6 +210,8 @@ pub fn kernel_python_skills(skills: &[Skill]) -> Vec<KernelPythonSkill> {
/// plus the pre-imported skills. The session's agent dir is propagated into the kernel env
/// (`PRIME_AGENT_CODING_AGENT_DIR`): an embedding host whose ambient env differs must not
/// leak its own paths into the kernel (#109). `cwd` is the SESSION's working directory.
+/// `shell_path` is the session-start-resolved kernel shell: an invalid `shellPath` fails
+/// `create_session`, not the kernel boot.
#[allow(clippy::too_many_arguments)] // one wiring funnel, same style as AgentSession::from_session_arc
#[must_use]
pub fn kernel_provisioner(
@@ -218,6 +220,7 @@ pub fn kernel_provisioner(
python_skills: Vec<KernelPythonSkill>,
cwd: std::path::PathBuf,
agent_dir: &std::path::Path,
+ shell_path: Option<std::path::PathBuf>,
snapshot_dir: Option<std::path::PathBuf>,
on_restore: Option<crate::kernel::provisioner::RestoreCallback>,
on_background_work_settled: Option<crate::kernel::shared::BackgroundWorkSettledCallback>,
@@ -235,7 +238,7 @@ pub fn kernel_provisioner(
python: None,
env,
command_prefix: None,
- shell_path: None,
+ shell_path,
session_id: Some(session_id),
host_handlers: handlers,
python_skills,
diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rs
index b314860cef..04bf062bd8 100644
--- a/crates/pa-core/src/settings/types.rs
+++ b/crates/pa-core/src/settings/types.rs
@@ -327,6 +327,13 @@ pub struct Settings {
/// fail with a configuration hint instead of silently dropping the images.
pub image_model: Option<String>,
pub autonomous: Option<AutonomousSettings>,
+ /// Custom shell that runs every kernel `bash()` and user-bash command as
+ /// `<shell> -c <command>`: an absolute path to an existing executable,
+ /// validated once at session start (a bad value fails session creation
+ /// naming this setting). Project `.prime/agent/settings.json` overrides
+ /// the global value (TS parity), so opening an untrusted repo lets it
+ /// choose the binary that wraps every agent shell command - review
+ /// project settings before running the agent there.
pub shell_path: Option<String>,
pub quiet_startup: Option<bool>,
pub shell_command_prefix: Option<String>,
diff --git a/crates/pa-core/src/update/installer.rs b/crates/pa-core/src/update/installer.rs
index 27ee42df74..ba3d6d6eaf 100644
--- a/crates/pa-core/src/update/installer.rs
+++ b/crates/pa-core/src/update/installer.rs
@@ -583,7 +583,7 @@ fn trusted_shell() -> PathBuf {
PathBuf::from("/bin/sh")
}
-/// On Windows the kernel shell resolver's TRUSTED Git Bash roots -
+/// On Windows the kernel shell default's TRUSTED Git Bash roots -
/// hardcoded install-dir literals, never PATH and never `where bash.exe`
/// (the `get_shell_config` fallback that serves the kernel shell would
/// let a repo-controlled `PATH` place the interpreter that receives the
@@ -593,7 +593,7 @@ fn trusted_shell() -> PathBuf {
/// Returns the failure when no trusted Git Bash root exists.
#[cfg(windows)]
fn trusted_shell() -> std::result::Result<std::path::PathBuf, UpdateFailure> {
- crate::platform::shell::resolve_kernel_bash_shell(None)
+ crate::platform::shell::default_kernel_bash_shell()
.map(std::path::PathBuf::from)
.ok_or_else(|| UpdateFailure {
// No shellPath guidance here: the funnel, like its unix side