Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): run the shell tool in PowerShell on Windows without bash (#9129)
Akarshan Biswas807a9879803f
diff --git a/Makefile b/Makefileindex 2f515bae6..2d5eb28bf 100644--- a/Makefile+++ b/Makefile@@ -153,6 +153,8 @@ test-rust: stub-resourcescargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-hardware/Cargo.tomlcargo test --locked --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlcargo test --locked --manifest-path src-tauri/utils/Cargo.toml+ # No --locked: this crate gitignores its Cargo.lock, as rust-check.yml assumes.+ cargo test --manifest-path src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml --no-default-features --test sandbox_spawn# protocol/schema.json is committed, and core::cli::protocol_schema fails when it# no longer matches the types that define the channel. This is the fix for thatdiff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex 160a008c3..151d5fe63 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -148,6 +148,21 @@ permanently would leave no way to run a single command without it.`backend` is the confinement that *would* be used. `none` means none is available on this machine -with `enabled: true` that combination is what withholds `bash` entirely.+### Which shell runs commands++On macOS and Linux the `bash` tool runs `bash` (or `sh` where there is none). On Windows it runs+PowerShell, never a bash: the sandbox is an AppContainer, and Git Bash's MSYS runtime cannot start+inside one. Jan uses the first of these that it finds:++1. PowerShell 7 (`pwsh`), unless it is only the Microsoft Store alias, which cannot start inside+ the sandbox.+2. Windows PowerShell 5.1, which ships with Windows.+3. `cmd.exe`.++The model is told which shell it has, so it writes PowerShell or cmd syntax when that is what+runs. Hooks and plugin tools use the same shell. To force a specific shell, set+`JAN_AGENT_SHELL` to its full path.+### The shell environmentThe shell does **not** inherit your full environment. Jan starts it from a minimal base -diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlindex c6f9e2276..c469df1a1 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -130,3 +130,10 @@ windows-sys = { version = "0.60.2", features = ["Win32_System_Memory","Win32_System_Threading",] }++# Real shells started inside the Windows sandbox. Its own `main`, because the+# sandbox re-execs the running binary as its helper and libtest would answer+# that re-exec by running the suite again.+[[test]]+name = "sandbox_spawn"+harness = falsediff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rsindex d7d63730f..536f5a324 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs@@ -134,13 +134,20 @@ fn quote_arg(arg: &str) -> String {out}-/// Join a program and its arguments into a `CreateProcessW` command line.+/// Join a program and its arguments into a `CreateProcessW` command line. cmd+/// does not parse its line with `CommandLineToArgvW`, so for cmd the last+/// argument -- the command -- is appended in cmd's own form instead of quoted.#[cfg_attr(not(windows), allow(dead_code))]fn command_line(program: &Path, args: &[String]) -> String {let mut line = quote_arg(&program.to_string_lossy());- for a in args {+ let cmd = super::proc::kind_of(program) == super::proc::ShellKind::Cmd;+ for (i, a) in args.iter().enumerate() {line.push(' ');- line.push_str("e_arg(a));+ if cmd && i + 1 == args.len() {+ line.push_str(&super::proc::cmd_payload(a));+ } else {+ line.push_str("e_arg(a));+ }}line}@@ -244,11 +251,26 @@ whereblock}+/// The shell's working directory: the long form of `workspace` (`long`, its+/// canonical path) when that is still a drive path, else `workspace` as given.+///+/// The long form fixes an 8.3 short path, which Windows PowerShell 5.1 cannot+/// expand inside the container. But a workspace on a mapped drive canonicalizes+/// to `\\?\UNC\server\share\...`, and cmd refuses a UNC working directory+/// and silently runs in `C:\Windows` instead, so that one keeps its drive path.+#[cfg(any(windows, test))]+fn working_dir(workspace: &Path, long: Option<PathBuf>) -> PathBuf {+ match long.map(|l| super::proc::without_verbatim_prefix(&l)) {+ Some(l) if !l.to_string_lossy().starts_with(r"\\") => l,+ _ => workspace.to_path_buf(),+ }+}+/// The message for a confined spawn that never started. The advice is keyed to/// the error: `ERROR_ACCESS_DENIED` is the one case where a shell installed/// under the user profile is the likely cause, and every other failure used to-/// be told the same thing - which sent the report that prompted this to-/// reinstall Git for Windows system-wide on a machine that already had it.+/// be told the same thing - which sent one report to reinstall a shell that+/// was already installed system-wide.#[cfg_attr(not(windows), allow(dead_code))]fn spawn_failure(program: &Path, error: &std::io::Error) -> String {/// `ERROR_ACCESS_DENIED`.@@ -259,8 +281,9 @@ fn spawn_failure(program: &Path, error: &std::io::Error) -> String {match error.raw_os_error() {Some(DENIED) => format!("could not start {} inside the sandbox: {error}. A shell installed \- under your user profile is unreadable to the sandbox; install \- Git for Windows system-wide instead.",+ under your user profile is unreadable to the sandbox; install it \+ system-wide (under Program Files), or unset JAN_AGENT_SHELL to use \+ the built-in Windows PowerShell.",program.display()),Some(ENVVAR_NOT_FOUND) => format!(@@ -671,7 +694,13 @@ mod win {startup.lpAttributeList = attributes;let mut line = wide(OsStr::new(&command_line(&req.program, &req.args)));- let cwd = wide(req.workspace.as_os_str());+ // The moniker and ACEs keep the path as given. The shell's working+ // directory is the long form: a `TEMP`-based workspace is often 8.3+ // (`C:\Users\RUNNER~1\...`), and Windows PowerShell 5.1 expands a short+ // name by listing each parent, which the container may not read, so it+ // fails with access denied. Resolved here, outside the container, and+ // without the verbatim prefix `canonicalize` adds, which cmd refuses.+ let cwd = wide(super::working_dir(&req.workspace, req.workspace.canonicalize().ok()).as_os_str());// The helper's own environment, which `proc.rs` reduced to// `SANDBOX_ENV_ALLOW` before re-exec'ing it. Passed explicitly rather// than left to inheritance: see `environment_block`.@@ -871,6 +900,38 @@ mod tests {);}+ /// A short or verbatim path becomes its long drive form; a mapped drive+ /// that resolves to UNC keeps its drive letter, which cmd can start in.+ #[test]+ fn the_working_dir_is_the_long_form_unless_that_is_unc() {+ let short = Path::new(r"C:\Users\RUNNER~1\ws");+ assert_eq!(+ working_dir(short, Some(PathBuf::from(r"\\?\C:\Users\runneradmin\ws"))),+ PathBuf::from(r"C:\Users\runneradmin\ws")+ );+ let mapped = Path::new(r"Z:\proj");+ assert_eq!(+ working_dir(mapped, Some(PathBuf::from(r"\\?\UNC\server\share\proj"))),+ PathBuf::from(r"Z:\proj")+ );+ assert_eq!(working_dir(mapped, None), PathBuf::from(r"Z:\proj"));+ }++ /// cmd reads its own line, not `CommandLineToArgvW`'s: its fixed switches+ /// are quoted as usual, but the command goes in cmd's `/S` form so its own+ /// quotes are not turned into `\"`.+ #[test]+ fn the_cmd_command_line_hands_the_command_over_in_cmds_form() {+ let line = command_line(+ Path::new(r"C:\Windows\System32\cmd.exe"),+ &["/D".into(), "/S".into(), "/C".into(), r#"echo "a b" && dir"#.into()],+ );+ assert_eq!(+ line,+ r#"C:\Windows\System32\cmd.exe /D /S /C "echo "a b" && dir""#+ );+ }+/// The block's entries, with the terminating NULs removed.fn entries(block: &[u16]) -> Vec<String> {let text = String::from_utf16(block).expect("utf-16");diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rsindex 96ff7ce76..0c8069f61 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rs@@ -25,6 +25,151 @@ pub enum CommandScan {const OPAQUE: &[&str] = &["eval", "xargs", "source", ".", "sudo", "su", "doas", "ssh", "watch",];+/// Windows shells, PowerShell's run-this-text commands, and the cmdlets (with+/// their aliases) that run a `{ ... }` script block. Their argument is code in+/// a language this scanner does not parse, so a grant on one of them must+/// never cover what they run: approving `ls | ForEach-Object { $_.Name }`+/// must not also approve `ls | ForEach-Object { Remove-Item $_ }`. Matched+/// case-insensitively and without `.exe`, as Windows and PowerShell both+/// resolve them.+const WINDOWS_OPAQUE: &[&str] = &[+ "cmd", "powershell", "pwsh", "invoke-expression", "iex", "invoke-command", "icm",+ "start-process", "saps", "start", "invoke-item", "ii", "invoke-wmimethod", "iwmi",+ "invoke-cimmethod", "icim", "foreach-object", "foreach", "%", "where-object",+ "where", "?", "start-job", "sajb", "start-threadjob", "invoke-commandinjob",+ // Hosts that run a program, script or command line named in their+ // arguments, or schedule one to run.+ "wsl", "conhost", "cscript", "wscript", "mshta", "rundll32", "forfiles", "wmic",+ "schtasks", "at", "runas", "regsvr32", "msiexec", "explorer", "pcalua", "cmstp",+ "msbuild", "installutil", "regasm", "regsvcs", "certutil", "bitsadmin",+ "scriptrunner", "sc",+];++fn is_windows_opaque(base: &str) -> bool {+ WINDOWS_OPAQUE.contains(&windows_name(base).as_str())+}++/// `base` as Windows resolves it: case-insensitive and without `.exe`.+fn windows_name(base: &str) -> String {+ let lower = base.to_ascii_lowercase();+ lower.strip_suffix(".exe").unwrap_or(&lower).to_string()+}++/// Whether `seg` holds a brace outside quotes and outside a `${...}` variable.+/// Such a brace is a PowerShell script block (`& { ... }`, `%{ ... }`,+/// `try{...}finally{...}`) or a POSIX `{ ...; }` group, whose contents are not+/// split into segments: scanning would yield the brace, the keyword before it,+/// or a fused token like `%{echo`, and a grant on that would cover any block.+///+/// Deliberately broad. Brace expansion (`*.{rs,toml}`) also counts, and so+/// prompts every time, because telling it apart from an unspaced script block+/// would need a PowerShell parser. Quoted braces (JSON, `awk '{...}'`, `jq`)+/// and `${HOME}` are not blocks.+fn has_block(seg: &str) -> bool {+ // POSIX shells read `\"` inside a double-quoted string as an escaped quote;+ // PowerShell reads it as a literal backslash that closes the string. A+ // brace one reading keeps inside quotes can be live under the other, so+ // either reading finding a block is enough.+ has_block_with(seg, true) || has_block_with(seg, false)+}++/// [`has_block`] under one quoting rule: whether `\` escapes a quote inside+/// a double-quoted string (`posix_escapes`) or is literal, as in PowerShell.+fn has_block_with(seg: &str, posix_escapes: bool) -> bool {+ let chars: Vec<char> = seg.chars().collect();+ let mut quote: Option<char> = None;+ let mut i = 0;+ while i < chars.len() {+ let c = chars[i];+ if let Some(q) = quote {+ if posix_escapes && c == '\\' && q == '"' {+ i += 1;+ } else if c == q {+ quote = None;+ }+ i += 1;+ continue;+ }+ match c {+ '\\' if posix_escapes => i += 1,+ '\'' | '"' => quote = Some(c),+ // `${NAME}` (and `${NAME:-x}`) is a variable, not a block: skip to+ // its closing brace. A `${` that never closes counts as a block.+ '$' if chars.get(i + 1) == Some(&'{') => {+ match chars[i + 2..].iter().position(|&ch| ch == '}') {+ Some(end) => i += 2 + end,+ None => return true,+ }+ }+ '{' | '}' => return true,+ _ => {}+ }+ i += 1;+ }+ false+}++/// Whether `command` has a backtick outside single quotes. POSIX reads it as a+/// command substitution, PowerShell as its escape character (`` `' `` is a+/// literal quote, `` `; `` a literal semicolon), so the two disagree about+/// where strings and commands end and no single scan is right for both. Inside+/// single quotes both read it literally. Checked under both quoting rules, as+/// [`has_block`] is, since `\"` decides whether a `'` is inside a string.+fn has_live_backtick(command: &str) -> bool {+ has_live_backtick_with(command, true) || has_live_backtick_with(command, false)+}++/// [`has_live_backtick`] under one quoting rule; see [`has_block_with`].+fn has_live_backtick_with(command: &str, posix_escapes: bool) -> bool {+ let chars: Vec<char> = command.chars().collect();+ let mut quote: Option<char> = None;+ let mut i = 0;+ while i < chars.len() {+ let c = chars[i];+ match quote {+ Some('\'') => {+ if c == '\'' {+ quote = None;+ }+ }+ Some(q) => {+ if c == '`' {+ return true;+ }+ if posix_escapes && c == '\\' {+ i += 1;+ } else if c == q {+ quote = None;+ }+ }+ None => match c {+ '`' => return true,+ '\\' if posix_escapes => i += 1,+ '\'' | '"' => quote = Some(c),+ _ => {}+ },+ }+ i += 1;+ }+ false+}++/// PowerShell assignment operators, when written as their own token.+const PS_ASSIGN_OPS: &[&str] = &["=", "+=", "-=", "*=", "/=", "%=", "??="];++/// For a token that can start a PowerShell assignment target -- a variable+/// (`$x`, `$a.b`, `$env:X`, `${x}`, `$a[0]`) or a typed one (`[int]$x`) --+/// what follows a fused `=`: `Some("rm")` for `$x=rm`, `Some("")` for `$x=`+/// or a bare target (the caller then checks for an operator token). `None`+/// for anything else. Compound operators (`+=`, `??=`) end in the same `=`,+/// and PowerShell compares with `-eq`, so the first `=` is the operator.+fn ps_assignment_rest(token: &str) -> Option<&str> {+ if !(token.starts_with('$') || token.starts_with('[')) {+ return None;+ }+ Some(token.find('=').map_or("", |eq| &token[eq + 1..]))+}+/// `find` predicates that run an arbitrary command.const EXEC_PREDICATES: &[&str] = &["-exec", "-execdir", "-ok", "-okdir"];/// POSIX shells: `<shell> -c "<cmd>"` runs `<cmd>`, so we recurse into it.@@ -37,7 +182,19 @@ const WRAPPERS: &[&str] = &["until", "for", "case", "function", "select", "coproc", "!",];+/// Typographic quotes PowerShell accepts as `'` (U+2018-U+201B) and `"`+/// (U+201C-U+201E), each closing a string any of its class opened.+const PS_UNICODE_QUOTES: &[char] =+ &['\u{2018}', '\u{2019}', '\u{201A}', '\u{201B}', '\u{201C}', '\u{201D}', '\u{201E}'];+pub fn scan_command(command: &str) -> CommandScan {+ // POSIX shells read these as plain characters, so the quote tracking here+ // (block detection, segment splitting) would disagree with PowerShell about+ // where a string ends: in `echo 'a\u{2019}; rm x; \u{2019}'` PowerShell runs+ // `rm`. They are rare in real commands, so prompting costs little.+ if command.contains(PS_UNICODE_QUOTES) || has_live_backtick(command) {+ return CommandScan::Opaque;+ }let mut bases = BTreeSet::new();if scan_into(command, &mut bases, 0) {CommandScan::Bases(bases)@@ -58,7 +215,14 @@ fn scan_into(command: &str, bases: &mut BTreeSet<String>, depth: usize) -> boolreturn false;}}- for seg in split_segments(&outer) {+ // An unquoted `\` escapes the next character in POSIX shells and is a+ // literal in PowerShell, so in `ls C:\; rm x` PowerShell runs `rm`. When the+ // two readings split the command differently, one of them hides a command.+ let segments = split_segments(&outer, true);+ if segments != split_segments(&outer, false) {+ return false;+ }+ for seg in segments {if !scan_segment(&seg, bases, depth) {return false;}@@ -191,8 +355,9 @@ fn capture_backtick(chars: &[char], tick: usize) -> (String, usize) {/// Split on the shell control operators that separate commands, honoring/// quotes. `(`/`)` (subshell grouping; substitutions are already removed) also-/// separate.-fn split_segments(s: &str) -> Vec<String> {+/// separate. `posix_escapes`: whether an unquoted `\` escapes the next+/// character (POSIX) or is a literal (PowerShell).+fn split_segments(s: &str, posix_escapes: bool) -> Vec<String> {let chars: Vec<char> = s.chars().collect();let mut segs = Vec::new();let mut cur = String::new();@@ -214,7 +379,7 @@ fn split_segments(s: &str) -> Vec<String> {cur.push(c);i += 1;}- '\\' if i + 1 < chars.len() => {+ '\\' if posix_escapes && i + 1 < chars.len() => {cur.push(c);cur.push(chars[i + 1]);i += 2;@@ -239,11 +404,21 @@ fn split_segments(s: &str) -> Vec<String> {/// Resolve one simple command segment to its base(s). Returns `false` if it is/// opaque.fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, depth: usize) -> bool {- let tokens = tokenize(seg);+ let tokens = tokenize(seg, true);+ // PowerShell reads `\` literally, so `C:\Windows\System32\cmd.exe` is+ // `cmd.exe` to it but an escaped `C:WindowsSystem32cmd.exe` to the POSIX+ // reading. Both readings must name the same command (checked below).+ let literal = tokenize(seg, false);// Any command-running find predicate makes the whole segment opaque.if tokens.iter().any(|t| EXEC_PREDICATES.contains(&t.as_str())) {return false;}+ // So does a script block or brace group anywhere in it: `try { ... }` and+ // `if ($x) { ... }` put the block after a keyword the scan would stop at.+ // `find -exec`'s `{}` placeholder has already made the segment opaque.+ if has_block(seg) {+ return false;+ }let mut idx = 0;let mut guard = 0;loop {@@ -254,14 +429,63 @@ fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, depth: usize) -> bool {while idx < tokens.len() && is_assignment(&tokens[idx]) {idx += 1;}+ // PowerShell `$var = <command>` (also `$a.b = ...`, `+=`, `$x=cmd`):+ // the command is the right-hand side, so that is what gets scanned.+ // Using `$var` as the base would let a grant on it cover any command+ // assigned to it.+ // A bare type cast before the target (`[string] $x = ...`).+ if tokens.get(idx).is_some_and(|t| t.starts_with('[') && t.ends_with(']'))+ && tokens.get(idx + 1).is_some_and(|t| t.starts_with('$'))+ {+ idx += 1;+ }+ // A .NET static call (`[Diagnostics.Process]::Start('x')`) can start+ // any program or touch any file, whatever its arguments.+ if tokens.get(idx).is_some_and(|t| t.starts_with('[') && t.contains("::")) {+ return false;+ }+ if let Some(rest) = tokens.get(idx).and_then(|t| ps_assignment_rest(t)) {+ let fused_op = tokens[idx].contains('=');+ let spaced_op = !fused_op+ && tokens.get(idx + 1).is_some_and(|t| PS_ASSIGN_OPS.contains(&t.as_str()));+ if spaced_op {+ // `$var = <cmd>`: what follows the operator token.+ let rhs = tokens[idx + 2..].join(" ");+ return scan_segment(&rhs, bases, depth + 1);+ }+ if fused_op || !rest.is_empty() {+ // `$var=<cmd>` / `$var= <cmd>`: the value fused to the+ // operator, if any, then the remaining tokens.+ let mut rhs: Vec<String> = Vec::new();+ if !rest.is_empty() {+ rhs.push(rest.to_string());+ }+ rhs.extend_from_slice(&tokens[idx + 1..]);+ return scan_segment(&rhs.join(" "), bases, depth + 1);+ }+ }+ // A variable as the command (`& $cmd`, `& $env:ComSpec /c ...`) runs+ // whatever it holds, so a grant on its name would cover every later+ // value: always prompt.+ if tokens.get(idx).is_some_and(|t| t.starts_with('$')) {+ return false;+ }if idx >= tokens.len() {return true; // only assignments / empty: runs nothing}let base = strip_base(&tokens[idx]);+ if literal.len() != tokens.len() || strip_base(&literal[idx]) != base {+ return false;+ }if base.is_empty() {return true;}- if OPAQUE.contains(&base.as_str()) {+ // Windows resolves `SSH` and `ssh.exe` to `ssh`, so the POSIX list is+ // matched by that name too.+ if OPAQUE.contains(&base.as_str())+ || OPAQUE.contains(&windows_name(&base).as_str())+ || is_windows_opaque(&base)+ {return false;}if base == "env" {@@ -276,7 +500,7 @@ fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, depth: usize) -> bool {}continue;}- if SHELLS.contains(&base.as_str()) {+ if SHELLS.contains(&base.as_str()) || SHELLS.contains(&windows_name(&base).as_str()) {if let Some(p) = tokens[idx + 1..].iter().position(|t| t == "-c") {let c_arg = idx + 1 + p + 1;return match tokens.get(c_arg) {@@ -307,9 +531,10 @@ fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, depth: usize) -> bool {}}-/// Split a segment into whitespace-delimited tokens, stripping quotes and-/// resolving backslash escapes.-fn tokenize(s: &str) -> Vec<String> {+/// Split a segment into whitespace-delimited tokens, stripping quotes and,+/// with `posix_escapes`, resolving backslash escapes (else `\` is literal, as+/// in PowerShell).+fn tokenize(s: &str, posix_escapes: bool) -> Vec<String> {let chars: Vec<char> = s.chars().collect();let mut out = Vec::new();let mut cur = String::new();@@ -321,7 +546,7 @@ fn tokenize(s: &str) -> Vec<String> {if let Some(q) = quote {if c == q {quote = None;- } else if c == '\\' && q == '"' && i + 1 < chars.len() {+ } else if posix_escapes && c == '\\' && q == '"' && i + 1 < chars.len() {cur.push(chars[i + 1]);has = true;i += 2;@@ -339,7 +564,7 @@ fn tokenize(s: &str) -> Vec<String> {has = true;i += 1;}- '\\' if i + 1 < chars.len() => {+ '\\' if posix_escapes && i + 1 < chars.len() => {cur.push(chars[i + 1]);has = true;i += 2;@@ -453,7 +678,9 @@ mod tests {#[test]fn command_substitution_is_scanned() {assert_eq!(bases("echo $(rm x)"), set(&["echo", "rm"]));- assert_eq!(bases("echo `rm x`"), set(&["echo", "rm"]));+ // A backtick is a substitution to POSIX and an escape to PowerShell;+ // no one scan is right for both, so it prompts.+ assert_eq!(scan_command("echo `rm x`"), CommandScan::Opaque);}#[test]@@ -495,6 +722,130 @@ mod tests {assert_eq!(bases("find . -name '*.rs'"), set(&["find"]));}+ /// On Windows the shell may be PowerShell, so a grant on `powershell` or+ /// `iex` would cover any code at all; those always prompt, in any case.+ #[test]+ fn windows_shells_and_powershell_evaluators_are_opaque() {+ for command in [+ "powershell -Command Remove-Item -Recurse C:\\",+ "PowerShell.exe -c x",+ "pwsh -c x",+ "cmd /c del x",+ "CMD.EXE /c del x",+ "Invoke-Expression $x",+ "iex $x",+ "Invoke-Command { rm x }",+ "Start-Process notepad",+ "Get-ChildItem | ForEach-Object { Remove-Item $_ }",+ "ls | % { rm $_ }",+ "ls | Where-Object { $_.Length -gt 0 }",+ "Start-Job { rm x }",+ "git status; iex $x",+ // A script block or brace group is code this scanner does not+ // split, so a grant on one must not cover every other block.+ "& { Remove-Item -Recurse ~ }",+ "if ($x) { Remove-Item a }",+ "try { rm x } catch { }",+ "{ ls; rm -rf ~; }",+ "{ls}",+ "try{ rm x }",+ "%{echo $_}",+ "ls | %{a}{b}",+ "try{a}finally{b}",+ "ls *.{rs,toml}",+ // PowerShell does not escape `\"`: the string closes there, so the+ // block after it is live.+ r#"Select-Object -InputObject "C:\" -Property { Remove-Item -Recurse ~ }"#,+ r#"Sort-Object -InputObject "a\" { Remove-Item -Recurse ~ }"#,+ // PowerShell closes a string at a typographic quote of its class.+ "Sort-Object -InputObject \"abc\u{201D} { Remove-Item -Recurse ~ } \"\"",+ "echo 'a\u{2019} ; rm x ; \u{2019}'",+ // PowerShell's backtick escape: `' is a literal quote, so the+ // `;` after it is live.+ "echo `'`' ; Remove-Item -Recurse -Force ~",+ "echo \"a`\" ; rm x ; \"",+ "echo a`; rm x",+ // PowerShell reads `\` literally, so the separator or quote after+ // it is live.+ "ls C:\\; Remove-Item -Recurse -Force ~",+ "ls C:\\| rm x",+ "echo \\' x '; Remove-Item ~",+ // Starting a program by another name.+ "[Diagnostics.Process]::Start('x')",+ "[System.IO.File]::Delete('C:\\x')",+ "Invoke-Item x.exe",+ "ii x.exe",+ "Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList calc.exe",+ "iwmi -Class Win32_Process -Name Create -ArgumentList calc.exe",+ "Invoke-CimMethod -ClassName Win32_Process -MethodName Create",+ "icim -ClassName Win32_Process -MethodName Create",+ "ssh.exe host rm -rf ~",+ "SSH host x",+ "sudo.exe rm x",+ "forfiles /c \"cmd /c del @file\"",+ "wmic process call create calc.exe",+ "schtasks /create /tr calc.exe /tn x /sc once /st 00:00",+ "runas /user:x calc.exe",+ "msiexec /i x.msi",+ "explorer.exe x.exe",+ "wsl rm -rf ~",+ "bash.exe -c 'iex x'",+ "mshta x.hta",+ "rundll32 x.dll,Entry",+ // A full path names the same program; PowerShell reads `\` literally.+ "C:\\Windows\\System32\\cmd.exe /c del /s /q C:\\",+ "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -c x",+ // A variable as the command runs whatever it holds.+ "& $env:ComSpec /c dir",+ "& $cmd args",+ "$cmd",+ "git status; & $x",+ ] {+ assert_eq!(scan_command(command), CommandScan::Opaque, "{command}");+ }+ // An ordinary cmdlet is still a base that a grant can cover.+ assert_eq!(bases("Get-ChildItem -Recurse"), set(&["Get-ChildItem"]));+ // Quoted braces and `${...}` variables are not blocks.+ for (command, base) in [+ (r#"echo '{"a":1}'"#, "echo"),+ ("jq '{a: .b}' f.json", "jq"),+ ("awk '{print $1}' f", "awk"),+ ("echo ${HOME}", "echo"),+ ("echo ${HOME:-/root} ${USER}", "echo"),+ (r#"curl -d "{\"x\":1}" u"#, "curl"),+ ] {+ assert_eq!(bases(command), set(&[base]), "{command}");+ }+ }++ /// A PowerShell assignment runs its right-hand side, so that is the base:+ /// a grant on the variable must not cover whatever is assigned to it.+ #[test]+ fn a_powershell_assignment_scans_its_right_hand_side() {+ for (command, base) in [+ ("$files = Get-ChildItem", "Get-ChildItem"),+ ("$x=rm -rf ~", "rm"),+ ("$x= rm -rf ~", "rm"),+ ("$a.b += Remove-Item x", "Remove-Item"),+ ("$x ??= Get-Item a", "Get-Item"),+ ] {+ assert_eq!(bases(command), set(&[base]), "{command}");+ }+ for (command, base) in [+ ("[string]$x = rm -rf ~", "rm"),+ ("[int] $x = Remove-Item a", "Remove-Item"),+ ("${x} = rm -rf ~", "rm"),+ ("$a[0] = rm -rf ~", "rm"),+ ("$a[0]=rm -rf ~", "rm"),+ ("[int]$x=Get-Item a", "Get-Item"),+ ] {+ assert_eq!(bases(command), set(&[base]), "{command}");+ }+ // `&` splits segments, so a bare `$x` reads like `& $x`: it prompts.+ assert_eq!(scan_command("$x | rm y"), CommandScan::Opaque);+ assert!(bases("$x =").is_empty(), "nothing to run, so nothing a grant covers");+ }+#[test]fn empty_command_has_no_bases() {assert_eq!(bases(""), set(&[]));diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 5a5c049da..c187227a6 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -926,10 +926,6 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// collecting output after this call has already returned.let sink = ctx.on_output.clone();let sandboxed = ctx.sandbox;- // The model writes POSIX commands by default, which `cmd` rejects. Surface- // the resolved shell so it can adapt when the only shell on a Windows box- // is cmd, instead of the tool silently presenting cmd as bash.- let shell_description = shell.description;tokio::spawn(async move {let mut out = collect_and_format(child, spill_scratch, sink).await;// Appended inside the task so a backgrounded job carries the hint too.@@ -940,14 +936,6 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if sandboxed && bash_result_failed(&out) && jail::looks_denied(&out) {out.push_str(&jail::denial_hint(&policy));}- if shell_description == "cmd" {- out.insert_str(- 0,- "[shell: cmd.exe - no bash is installed. Write commands in cmd syntax \- (e.g. `dir`, `type`, `set`, `mkdir`, `%VAR%` for variables), not \- POSIX/bash. Alternatively install git-bash and this tool will use it.]\n",- );- }if let Some(pid) = pid {proc::unregister(thread_owned.as_deref(), pid);}@@ -1492,21 +1480,38 @@ pub async fn render_html_png(// headless-new process spawned directly by a non-bundled parent fails its// singleton/TCC check with "Multiple targets are not supported in headless// mode", while the same invocation via the shell succeeds. The `bash` tool- // already relies on this property, so we inherit it here.- let profile_quoted = shell_quote(profile.to_str().unwrap_or_default());- let shot_quoted = shell_quote(shot.to_str().unwrap_or_default());- let url_quoted = shell_quote(&file_url);- let chrome_quoted = shell_quote(chrome.to_str().unwrap_or_default());- let cmd = format!(- "{chrome_quoted} --headless=new --disable-gpu --hide-scrollbars --no-sandbox \- --disable-dev-shm-usage --no-first-run --user-data-dir={profile_quoted} \- --force-device-scale-factor={scale} \- --window-size={width},{height} --screenshot={shot_quoted} {url_quoted}"- );+ // already relies on this property, so we inherit it here. The quoting below+ // is POSIX, so a PowerShell or cmd shell (Windows, where the quirk does not+ // exist) gets Chrome directly with its arguments instead.+ let chrome_args = [+ "--headless=new".to_string(),+ "--disable-gpu".to_string(),+ "--hide-scrollbars".to_string(),+ "--no-sandbox".to_string(),+ "--disable-dev-shm-usage".to_string(),+ "--no-first-run".to_string(),+ format!("--user-data-dir={}", profile.display()),+ format!("--force-device-scale-factor={scale}"),+ format!("--window-size={width},{height}"),+ format!("--screenshot={}", shot.display()),+ file_url.clone(),+ ];let shell = proc::shell();- let mut child = match tokio::process::Command::new(shell.program.clone())- .args(shell.args.clone())- .arg(&cmd)+ let mut launcher = if shell.kind == proc::ShellKind::Posix {+ let line = std::iter::once(chrome.to_string_lossy().into_owned())+ .chain(chrome_args.iter().cloned())+ .map(|a| shell_quote(&a))+ .collect::<Vec<_>>()+ .join(" ");+ let mut c = tokio::process::Command::new(&shell.program);+ c.args(&shell.args).arg(line);+ c+ } else {+ let mut c = tokio::process::Command::new(&chrome);+ c.args(&chrome_args);+ c+ };+ let mut child = match launcher.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).spawn()@@ -2974,6 +2979,8 @@ mod tests {/// A command's output reaches the sink as it is produced, not just in the/// returned string -- this is what makes a long command visible while it runs.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_streams_output_to_the_sink() {let root = unique_root();@@ -3009,6 +3016,8 @@ mod tests {/// A backgrounded command keeps streaming after the call has returned: the/// sink lives in the detached task, which is the whole reason a long job can/// show progress while it runs on.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_backgrounded_command_keeps_streaming() {let root = unique_root();@@ -3054,6 +3063,8 @@ mod tests {/// run under it) and report again when it really finishes, naming the file/// the output was published to. The order matters -- the file is written/// before the ping, so reacting to the ping always finds it there.+ // POSIX command text, and a 1.2s budget a cold PowerShell start can miss.+ #[cfg(unix)]#[tokio::test]async fn a_backgrounded_command_rings_the_doorbell_when_it_finishes() {let root = unique_root();@@ -3235,6 +3246,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_exit_marker_is_on_its_own_line() {let root = unique_root();@@ -3255,6 +3268,8 @@ mod tests {/// Typical command output (well under the caps) must reach the model whole:/// lowering the caps for context economy must not start truncating the/// everyday `cargo check` / `git status` sized result.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_output_under_the_cap_survives_intact() {let root = unique_root();@@ -3277,6 +3292,8 @@ mod tests {/// The counterpart: past the cap the notice appears. Pinned just above/// 64KB so the test fails if the cap drifts back up to the old 256KB.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_output_past_the_byte_cap_is_truncated() {let root = unique_root();@@ -3302,6 +3319,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_cr_progress_is_collapsed_not_truncated() {let root = unique_root();@@ -3326,6 +3345,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_output_overflow_spills_to_readable_temp_file() {let root = unique_root();@@ -3367,6 +3388,8 @@ mod tests {/// scratch and be advertised by the one name that works from both the fs/// tools and the shell, so the `read` the note asks for actually finds it./// The no-scratch case above cannot catch this -- there `/tmp` is not remapped.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_spill_is_readable_when_a_scratch_is_set() {let root = unique_root();@@ -3462,6 +3485,8 @@ mod tests {let _ = std::fs::remove_dir_all(&scratch);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_line_overflow_keeps_the_tail_not_the_head() {let root = unique_root();@@ -3486,6 +3511,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_strips_control_chars_but_keeps_text() {let root = unique_root();@@ -3506,6 +3533,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn bash_command_reading_stdin_does_not_hang() {let root = unique_root();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rsindex c44957f59..f47b13c2a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs@@ -603,10 +603,10 @@ mod tests {}}- /// Render a path for embedding in a hook's shell command. On Windows the- /// resolved shell is git-bash, which eats the backslashes of a native- /// `C:\Users\...` path and writes to a mangled name; forward slashes work- /// there too, and the quotes keep a path with spaces a single word.+ /// Render a path for embedding in a hook's shell command. Forward slashes+ /// and single quotes read the same in bash and PowerShell, so a+ /// `C:\Users\...` temp path survives either, and the quotes keep a path+ /// with spaces a single word.fn shq(path: &Path) -> String {format!("'{}'", path.to_string_lossy().replace('\\', "/"))}@@ -859,6 +859,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn the_payload_reaches_the_hook_on_stdin() {let root = unique_root("payload");@@ -1130,6 +1132,8 @@ mod tests {/// PostToolUse sees the result the tool produced, and its own "deny" is/// ignored: the call already happened, so there is nothing left to stop.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn posttooluse_through_execute_builtin_sees_the_result() {let root = unique_root("builtinpost");diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex d079bc319..6fd0b1ddb 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -254,14 +254,12 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {Backend::Bubblewrap => Some(ShellConfig {program: bwrap_path()?,args: bwrap_args(policy, cfg),- via_stdin: cfg.via_stdin,- description: cfg.description,+ kind: cfg.kind,}),Backend::Seatbelt => Some(ShellConfig {program: PathBuf::from(seatbelt_program()),args: seatbelt_args(policy, cfg),- via_stdin: cfg.via_stdin,- description: cfg.description,+ kind: cfg.kind,}),// AppContainer is a token attribute on the spawn rather than an argv// prefix, and `tokio::process::Command` cannot set one, so the wrapper is@@ -277,8 +275,7 @@ pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {&cfg.program,&cfg.args,),- via_stdin: cfg.via_stdin,- description: cfg.description,+ kind: cfg.kind,}),Backend::None => None,}@@ -720,8 +717,7 @@ mod tests {ShellConfig {program: PathBuf::from("/bin/bash"),args: vec!["-c".to_string()],- via_stdin: false,- description: "bash",+ kind: super::super::proc::ShellKind::Posix,}}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rsindex 3b06ce403..75134667b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs@@ -661,6 +661,8 @@ mod tests {assert_eq!(spec.interval, Duration::from_secs(MAX_INTERVAL_SECS));}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_script_matching_at_start_reports_its_output_and_stops() {let dir = unique_root();@@ -690,6 +692,8 @@ mod tests {panic!("the set still reports pending work after the match");}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_later_change_is_caught_by_a_following_poll() {let dir = unique_root();@@ -713,6 +717,8 @@ mod tests {assert!(update.text.contains("phase two done"), "{}", update.text);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn snapshot_lists_active_monitors_with_their_poll_count() {let dir = unique_root();@@ -777,6 +783,8 @@ mod tests {assert!(!set.has_pending_work());}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn wait_for_notice_wakes_on_a_match() {let dir = unique_root();@@ -801,6 +809,8 @@ mod tests {assert!(notices[0].text.contains("a hit at last"));}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_subscriber_gets_updates_instead_of_the_queue() {let dir = unique_root();diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rsindex fb3e158a4..3232f099b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs@@ -419,6 +419,8 @@ mod tests {/// A capped result the model reads as complete is the failure this note/// exists to prevent.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn output_past_the_cap_is_marked_as_truncated() {let root = unique_root("truncate");@@ -496,6 +498,8 @@ mod tests {assert_eq!(schema["function"]["parameters"]["required"][0], "path");}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn arguments_reach_the_command_on_stdin_and_stdout_is_the_result() {let root = unique_root("exec");@@ -515,6 +519,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_failing_plugin_tool_returns_an_error_string_not_a_panic() {let root = unique_root("execfail");@@ -568,6 +574,8 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_silent_success_still_reports_something_to_the_model() {let root = unique_root("execsilent");diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex b9b1b13cf..d3284393f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -41,18 +41,179 @@ pub fn is_reserved_env_key(key: &str) -> bool {|| key.starts_with("SUDO_")}+/// The command language a resolved shell speaks. It decides how the command is+/// handed over (see [`spawn_with_stdin`]) and what the model is told to write.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ShellKind {+ /// `bash`/`sh` and anything else that takes `-c <command>`.+ Posix,+ /// Windows PowerShell 5.1 (`powershell.exe`) or PowerShell 7 (`pwsh`).+ PowerShell,+ /// `cmd.exe`, the last resort on a Windows box with neither.+ Cmd,+}++impl ShellKind {+ /// The sentence that tells the model which syntax to write, for every shell+ /// that is not the POSIX one it assumes by default. Shared by the tool+ /// description and the system prompt's runtime block so the two agree.+ pub fn syntax_note(self) -> Option<&'static str> {+ match self {+ ShellKind::Posix => None,+ ShellKind::PowerShell => Some(+ "Commands run in PowerShell: write PowerShell syntax (e.g. `Get-ChildItem`, \+ `Get-Content`, `$env:VAR`, `;` between statements), not bash/POSIX. \+ Relative paths work. For a full path, use `Convert-Path` rather than \+ `$PWD` or `Resolve-Path`, which may show a drive other programs cannot open.",+ ),+ ShellKind::Cmd => Some(+ "Commands run in cmd.exe: write cmd syntax (e.g. `dir`, `type`, `set`, \+ `%VAR%`), not bash/POSIX.",+ ),+ }+ }+}+/// How to invoke the host shell. `program` + `args` are fixed; the command-/// string is appended as the final argv element, or piped to stdin when-/// `via_stdin` is set (legacy WSL `bash.exe`, which cannot take `-c`).-/// `description` names the shell for the model (e.g. git-bash vs `cmd`), so it-/// can adapt command syntax instead of assuming POSIX bash.+/// string is appended as the final argv element.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ShellConfig {pub program: PathBuf,pub args: Vec<String>,- pub via_stdin: bool,- /// A short human-readable name of the resolved shell, for the model.- pub description: &'static str,+ /// The language of the shell the command finally runs in. Kept through+ /// [`super::jail::wrap`], whose wrapper program is not the shell itself.+ pub kind: ShellKind,+}++/// Fixed PowerShell arguments, the command following `-Command`. No profile so+/// a user's `$PROFILE` cannot change or slow every call; non-interactive so a+/// prompt fails instead of hanging; `Bypass` so a `.ps1` the agent writes can+/// run on a client whose default policy is `Restricted`. `-EncodedCommand` is+/// deliberately not used: with redirected output, Windows PowerShell 5.1 then+/// writes errors and progress to stderr as `#< CLIXML` records.+const POWERSHELL_ARGS: &[&str] = &[+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-Command",+];++/// `/D` skips the AutoRun registry hook, as `-NoProfile` does for PowerShell.+/// `/S` makes cmd strip exactly the outer quote pair [`cmd_payload`] adds, so+/// the command's own quotes survive whatever it contains.+const CMD_ARGS: &[&str] = &["/D", "/S", "/C"];++/// Classify a shell by its file name, case-insensitively and with either path+/// separator, so a `JAN_AGENT_SHELL` pointing at PowerShell or cmd is driven as+/// one rather than handed `-c`.+pub fn kind_of(program: &Path) -> ShellKind {+ let text = program.to_string_lossy();+ let name = text.rsplit(['/', '\\']).next().unwrap_or(&text).to_ascii_lowercase();+ match name.strip_suffix(".exe").unwrap_or(&name) {+ "pwsh" | "powershell" => ShellKind::PowerShell,+ "cmd" => ShellKind::Cmd,+ _ => ShellKind::Posix,+ }+}++/// The fixed arguments a shell of `kind` takes before its command.+pub fn shell_args(kind: ShellKind) -> Vec<String> {+ let args: &[&str] = match kind {+ ShellKind::Posix => &["-c"],+ ShellKind::PowerShell => POWERSHELL_ARGS,+ ShellKind::Cmd => CMD_ARGS,+ };+ args.iter().map(|s| s.to_string()).collect()+}++/// The config that drives `program` according to its [`kind_of`].+fn config_for(program: PathBuf) -> ShellConfig {+ let kind = kind_of(&program);+ ShellConfig {+ program,+ args: shell_args(kind),+ kind,+ }+}++/// The inbox modules behind everyday cmdlets: `Get-ChildItem`/`Get-Content`/+/// `Set-Location` (Management), `Write-Output`/`Select-String`/+/// `ConvertTo-Json` (Utility), `Get-Acl` (Security), `Expand-Archive`+/// (Archive). Anything else on 5.1 needs its own `Import-Module`.+const POWERSHELL_CORE_MODULES: &str = "Microsoft.PowerShell.Management, \+ Microsoft.PowerShell.Utility, Microsoft.PowerShell.Security, Microsoft.PowerShell.Archive";++/// The script PowerShell is given for `command`. PowerShell's own exit code is+/// only 0 or 1, so it is made to report a failing native command's real code,+/// which the tool output's `[exit N]` line and the model both rely on.+/// `$LASTEXITCODE` is reset first so a code left by an earlier call cannot+/// leak in.+///+/// Success is `$?` of the last statement, as in POSIX shells. On failure the+/// native code is used only when it is non-zero, so a cmdlet failing after a+/// native command that succeeded still reports 1 rather than 0. PowerShell+/// does not record which statement set `$LASTEXITCODE`, so when a cmdlet fails+/// after an earlier native command that failed, the code is that native+/// command's: still non-zero, possibly not the failing statement's own.+///+/// The command runs inside a function, and the code is handed to+/// `$host.SetShouldExit` rather than `exit`:+/// - A top-level `exit` discards formatted output that has not been flushed,+/// so `Get-Location; Write-Output x` printed nothing.+/// - An error is reported against the statement that raised it. At top level+/// that statement is the whole `-Command` text, so 5.1 echoed this wrapper+/// back with every `Write-Error`; inside the function it is just `jan_cmd`.+///+/// Output is switched to UTF-8: 5.1 otherwise encodes with the OEM code page+/// and mangles every non-ASCII character. The progress stream is silenced+/// because it is noise in captured output.+///+/// Inside the AppContainer two things need help:+/// - Windows PowerShell 5.1 cannot autoload modules: `Write-Output` is "not+/// recognized" although `Import-Module` of the same module succeeds, so on+/// 5.1 the core inbox modules are imported explicitly. pwsh 7 autoloads.+/// - PowerShell starts at `C:\` rather than the working directory it was+/// given, because it cannot read the workspace's parent folders to resolve+/// the path; relative paths, `Get-ChildItem` and, on 5.1, every external+/// program then fail. The session first moves to the process's working+/// directory by its real path. Only if that is refused does it fall back to+/// a `JanWs:` drive rooted there, which needs no parent access, so the drive+/// is never used where a real path works. Under the drive, `$PWD` and+/// `Resolve-Path` read `JanWs:\...`, which a native program cannot open;+/// [`ShellKind::syntax_note`] tells the model to pass `Convert-Path` output+/// instead, which is the real path.+///+/// A `return` in the command leaves `jan_cmd` before its status line runs, so+/// the code is then taken after the call: the native code if one was set,+/// else success.+pub fn powershell_script(command: &str) -> String {+ format!(+ "$ProgressPreference = 'SilentlyContinue'\n\+ if ($PSVersionTable.PSVersion.Major -lt 6) {{ Import-Module {POWERSHELL_CORE_MODULES} -ErrorAction SilentlyContinue }}\n\+ try {{ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) }} catch {{}}\n\+ $OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n\+ $JanWs = [Environment]::CurrentDirectory\n\+ try {{ Set-Location -LiteralPath $JanWs -ErrorAction Stop }} catch {{ try {{ $null = New-PSDrive -Name JanWs -PSProvider FileSystem -Root $JanWs -Scope Global -ErrorAction Stop; Set-Location JanWs:\\ }} catch {{}} }}\n\+ $global:LASTEXITCODE = $null\n\+ $JanExit = $null\n\+ function jan_cmd {{\n\+ {command}\n\+ $script:JanExit = if ($?) {{ 0 }} elseif ($LASTEXITCODE) {{ $LASTEXITCODE }} else {{ 1 }}\n\+ }}\n\+ jan_cmd\n\+ if ($null -eq $JanExit) {{ $JanExit = if ($LASTEXITCODE) {{ $LASTEXITCODE }} else {{ 0 }} }}\n\+ $host.SetShouldExit($JanExit)\n"+ )+}++/// The text appended, unescaped, after [`CMD_ARGS`]. cmd does its own quote+/// handling rather than the `CommandLineToArgvW` rules every argv quoter+/// follows, so an escaped `\"` reaches it literally; the command is wrapped in+/// one quote pair that `/S` removes again instead.+pub fn cmd_payload(command: &str) -> String {+ format!("\"{command}\"")}/// User-configured additions to the shell's environment, layered on top of the@@ -67,33 +228,48 @@ pub struct ShellEnv<'a> {pub set: &'a [(String, String)],}-/// Resolved shell for this process, computed once. Prefers a real `bash`-/// (matching the tool's name and documented guidance) and falls back to a-/// POSIX `sh`/`cmd` only when no bash is found.+/// Resolved shell for this process, computed once. `JAN_AGENT_SHELL` wins;+/// otherwise `bash` on unix and PowerShell on Windows, with `cmd` only as the+/// last resort.pub fn shell() -> &'static ShellConfig {static SHELL: OnceLock<ShellConfig> = OnceLock::new();SHELL.get_or_init(resolve_shell)}-fn c(program: &str, args: &[&str], description: &'static str) -> ShellConfig {- ShellConfig {- program: PathBuf::from(program),- args: args.iter().map(|s| s.to_string()).collect(),- via_stdin: false,- description,- }+/// Whether a `pwsh` at `path` can start inside the AppContainer: only under a+/// Program Files folder (`program_files`), which every container may read.+/// A per-user install (scoop, a zip under the profile, dotnet tool) has no+/// such grant and fails at startup with "Failed to resolve full path of the+/// current executable"; a Store alias is a reparse point that cannot start+/// either. Both would leave 5.1, which always works, unused.+#[cfg(any(windows, test))]+fn container_can_run(path: &Path, program_files: &[PathBuf]) -> bool {+ let p = path.to_string_lossy().replace('/', "\\").to_ascii_lowercase();+ !is_app_execution_alias(path)+ && program_files.iter().any(|root| {+ let root = root.to_string_lossy().replace('/', "\\").to_ascii_lowercase();+ let root = root.trim_end_matches('\\');+ !root.is_empty() && p.starts_with(&format!("{root}\\"))+ })+}++/// True for a Store app-execution alias under `%LOCALAPPDATA%\Microsoft\+/// WindowsApps`, such as the Store PowerShell 7's `pwsh.exe`.+/// An alias is a reparse point that cannot start inside the AppContainer, so+/// choosing one leaves the sandboxed shell failing every command while a+/// working shell later in the order goes unused. String-based so it is+/// testable on any host.+#[cfg(any(windows, test))]+fn is_app_execution_alias(path: &Path) -> bool {+ let p = path.to_string_lossy().replace('/', "\\").to_ascii_lowercase();+ p.contains("\\microsoft\\windowsapps\\")}fn resolve_shell() -> ShellConfig {if let Some(path) = std::env::var_os("JAN_AGENT_SHELL") {let p = PathBuf::from(&path);if p.exists() {- return ShellConfig {- program: p,- args: vec!["-c".to_string()],- via_stdin: false,- description: "custom",- };+ return config_for(p);}}#[cfg(unix)]@@ -106,91 +282,74 @@ fn resolve_shell() -> ShellConfig {// or `PATH` is degenerate but `/bin/bash` is real (e.g. cron); `/bin/sh`// is the guaranteed-POSIX last resort.if let Some(p) = which("bash") {- return ShellConfig {- program: p,- args: vec!["-c".to_string()],- via_stdin: false,- description: "bash",- };+ return config_for(p);}if Path::new("/bin/bash").exists() {- return c("/bin/bash", &["-c"], "bash");+ return config_for(PathBuf::from("/bin/bash"));}- c("/bin/sh", &["-c"], "sh")+ config_for(PathBuf::from("/bin/sh"))}#[cfg(windows)]{- // Prefer a real bash before ever falling back to cmd, so POSIX command- // syntax keeps working. Check the standard git-bash/msys install- // locations under the well-known program dirs first, then `bash` on- // PATH.- for var in ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"] {- if let Some(base) = std::env::var_os(var) {- let git_bash = PathBuf::from(base).join("Git").join("bin").join("bash.exe");- if git_bash.exists() {- return ShellConfig {- program: git_bash,- args: vec!["-c".to_string()],- via_stdin: false,- description: "git-bash",- };- }- }+ // PowerShell, never a bash: the sandbox is an AppContainer, where the+ // MSYS runtime behind Git Bash cannot create its objects under+ // `\BaseNamedObjects` and dies at startup (#9101). 7 (`pwsh`) when+ // installed under Program Files, else the inbox 5.1 by absolute path so+ // a PATH entry cannot shadow it.+ let program_files: Vec<PathBuf> = ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"]+ .iter()+ .filter_map(std::env::var_os)+ .map(PathBuf::from)+ .collect();+ if let Some(p) = which_all("pwsh")+ .into_iter()+ .find(|p| container_can_run(p, &program_files))+ {+ return config_for(p);}- if let Some(p) = which("bash") {- // The WSL launcher is the shim at System32\bash.exe; it rejects- // `-c`, so the command must be piped to `bash -s` on stdin. Only- // that exact location is treated as WSL, so a real bash that merely- // lives under a directory named `system32` is not misrouted to- // stdin one-shot mode.- let is_wsl = p- .file_name()- .and_then(|n| n.to_str())- .map(|n| n.eq_ignore_ascii_case("bash.exe"))- .unwrap_or(false)- && p.parent()- .and_then(|d| d.file_name())- .and_then(|n| n.to_str())- .map(|n| n.eq_ignore_ascii_case("System32"))- .unwrap_or(false);- if is_wsl {- return ShellConfig {- program: p,- args: vec!["-s".to_string()],- via_stdin: true,- description: "wsl bash",- };- }- return ShellConfig {- program: p,- args: vec!["-c".to_string()],- via_stdin: false,- description: "bash",- };+ let system = std::env::var_os("SystemRoot")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from(r"C:\Windows"))+ .join("System32");+ let powershell = system+ .join("WindowsPowerShell")+ .join("v1.0")+ .join("powershell.exe");+ if powershell.exists() {+ return config_for(powershell);}- // No bash anywhere: cmd is the only shell. The model is told this (the- // runtime env block reports COMSPEC, and the bash handler's output note- // names cmd) so it can write cmd syntax rather than silently passing- // POSIX commands that cmd would reject.- c("cmd.exe", &["/C"], "cmd")+ config_for(system.join("cmd.exe"))}}/// Locate an executable on PATH via the platform's own resolver. Also used by/// [`super::jail`] to find `bwrap` on distros with no FHS paths (NixOS keeps it/// only at a Nix-store path).+/// Unix only outside tests: Windows resolution needs every match (see+/// [`which_all`]) to step past the app-execution aliases.+#[cfg(any(unix, test))]pub(crate) fn which(name: &str) -> Option<PathBuf> {+ which_all(name).into_iter().next()+}++/// Every match for `name` on PATH, in PATH order.+fn which_all(name: &str) -> Vec<PathBuf> {#[cfg(unix)]let finder = "which";#[cfg(windows)]let finder = "where";- let out = std::process::Command::new(finder).arg(name).output().ok()?;+ let Ok(out) = std::process::Command::new(finder).arg(name).output() else {+ return Vec::new();+ };if !out.status.success() {- return None;+ return Vec::new();}- let text = String::from_utf8_lossy(&out.stdout);- let first = text.lines().map(str::trim).find(|l| !l.is_empty())?;- Some(PathBuf::from(first))+ String::from_utf8_lossy(&out.stdout)+ .lines()+ .map(str::trim)+ .filter(|l| !l.is_empty())+ .map(PathBuf::from)+ .collect()}/// Spawn `command` in `cwd` using the resolved shell, as a new process group,@@ -222,6 +381,12 @@ const SANDBOX_ENV_ALLOW: &[&str] = &["PATHEXT","ProgramFiles","ProgramData",+ // PowerShell keeps its module-analysis cache under `LOCALAPPDATA`, and+ // npm, pip and most Windows toolchains resolve per-user state through these.+ // Locations, not secrets; also unset on unix.+ "SystemDrive",+ "LOCALAPPDATA",+ "APPDATA",];/// Every spelling of "where temporary files go": POSIX tools read `TMPDIR`,@@ -392,17 +557,52 @@ pub async fn spawn(spawn_with_stdin(cfg, command, cwd, scratch, env, thread, None).await}+/// `path` without the `\\?\` verbatim prefix `canonicalize` adds on Windows:+/// `\\?\C:\x` becomes `C:\x` and `\\?\UNC\srv\share` becomes+/// `\\srv\share`. cmd refuses a verbatim working directory and silently runs+/// in `C:\Windows` instead, and tools print the prefix back at the model. Any+/// other path, including other verbatim forms, is returned unchanged.+pub fn without_verbatim_prefix(path: &Path) -> PathBuf {+ let text = path.to_string_lossy();+ if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {+ return PathBuf::from(format!(r"\\{rest}"));+ }+ if let Some(rest) = text.strip_prefix(r"\\?\") {+ let b = rest.as_bytes();+ if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\' {+ return PathBuf::from(rest);+ }+ }+ path.to_path_buf()+}++/// Append `command` to `cmd` in the form `cfg`'s shell reads it. When `cfg` is a+/// sandbox wrapper rather than the shell itself, the command travels as a plain+/// argument and the AppContainer helper re-applies the cmd rule when it builds+/// the shell's own command line (see `appcontainer::command_line`).+fn append_command(cmd: &mut Command, cfg: &ShellConfig, command: &str) {+ match cfg.kind {+ ShellKind::Posix => {+ cmd.arg(command);+ }+ ShellKind::PowerShell => {+ cmd.arg(powershell_script(command));+ }+ ShellKind::Cmd => {+ #[cfg(windows)]+ if kind_of(&cfg.program) == ShellKind::Cmd {+ cmd.raw_arg(cmd_payload(command));+ return;+ }+ cmd.arg(command);+ }+ }+}+/// [`spawn`] plus a string fed to the child on stdin and then closed. Used by/// the hook and plugin-tool runners, whose contract is "JSON in on stdin, JSON/// out on stdout".///-/// On a `via_stdin` shell (legacy WSL `bash.exe`, which cannot take `-c`) stdin-/// already carries the command itself, so the payload is written on the lines-/// after it. That is still readable -- the shell consumes its script line by-/// line and leaves the rest of the descriptor to the script -- but it is the-/// one shell where a hook reading stdin sees the payload only after its own-/// source text has been consumed.-////// The write itself happens on a detached task, so this function returns as/// soon as the child is spawned and the caller's timeout covers the whole/// exchange. See the comment at the write site.@@ -417,9 +617,7 @@ pub async fn spawn_with_stdin() -> std::io::Result<Child> {let mut cmd = Command::new(&cfg.program);cmd.args(&cfg.args);- if !cfg.via_stdin {- cmd.arg(command);- }+ append_command(&mut cmd, cfg, command);// Strip every inherited variable, then re-add only the allowlist so the// sandboxed process holds no host secrets regardless of which backend wraps// it. `current_dir` on the workspace keeps relative work correct.@@ -459,10 +657,10 @@ pub async fn spawn_with_stdin(cmd.env(key, scratch);}}- cmd.current_dir(cwd)+ cmd.current_dir(without_verbatim_prefix(cwd)).stdout(Stdio::piped()).stderr(Stdio::piped())- .stdin(if cfg.via_stdin || stdin_payload.is_some() {+ .stdin(if stdin_payload.is_some() {Stdio::piped()} else {Stdio::null()@@ -474,7 +672,7 @@ pub async fn spawn_with_stdin(let mut child = cmd.spawn()?;- if cfg.via_stdin || stdin_payload.is_some() {+ if let Some(payload) = stdin_payload {if let Some(mut stdin) = child.stdin.take() {// Written from a detached task, never awaited here: a payload// larger than the pipe buffer blocks until the child reads it, and@@ -482,22 +680,13 @@ pub async fn spawn_with_stdin(// it could arm its timeout. A PostToolUse hook carries a whole tool// result, so this is the common size, not a corner case. Detached,// the write simply fails when the child is killed or exits.- let script = cfg.via_stdin.then(|| command.to_string());- let payload = stdin_payload.map(str::to_string);+ let payload = payload.to_string();tokio::spawn(async move {use tokio::io::AsyncWriteExt;- if let Some(script) = script {- if stdin.write_all(script.as_bytes()).await.is_err() {- return;- }- let _ = stdin.write_all(b"\n").await;- }- if let Some(payload) = payload {- if stdin.write_all(payload.as_bytes()).await.is_err() {- return;- }- let _ = stdin.write_all(b"\n").await;+ if stdin.write_all(payload.as_bytes()).await.is_err() {+ return;}+ let _ = stdin.write_all(b"\n").await;let _ = stdin.shutdown().await;});}@@ -688,7 +877,10 @@ mod env_allowlist_tests {/// a bare Windows box can actually run a command.#[test]fn allowlist_has_windows_system_keys() {- for key in ["SystemRoot", "windir", "ComSpec", "PATHEXT", "ProgramFiles", "ProgramData"] {+ for key in [+ "SystemRoot", "windir", "ComSpec", "PATHEXT", "ProgramFiles", "ProgramData",+ "SystemDrive", "LOCALAPPDATA", "APPDATA",+ ] {assert!(SANDBOX_ENV_ALLOW.contains(&key),"missing {key} in SANDBOX_ENV_ALLOW"@@ -697,6 +889,211 @@ mod env_allowlist_tests {}}+#[cfg(test)]+mod shell_kind_tests {+ use super::*;++ #[test]+ fn kind_of_reads_the_file_name_on_any_separator_and_case() {+ for (path, kind) in [+ ("/bin/bash", ShellKind::Posix),+ ("/bin/sh", ShellKind::Posix),+ (r"C:\Program Files\Git\bin\bash.exe", ShellKind::Posix),+ (r"C:\Program Files\PowerShell\7\pwsh.exe", ShellKind::PowerShell),+ ("/usr/bin/pwsh", ShellKind::PowerShell),+ (+ r"C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.EXE",+ ShellKind::PowerShell,+ ),+ (r"C:\Windows\System32\cmd.exe", ShellKind::Cmd),+ ("CMD.EXE", ShellKind::Cmd),+ ] {+ assert_eq!(kind_of(Path::new(path)), kind, "{path}");+ }+ }++ #[test]+ fn each_kind_gets_the_arguments_its_shell_reads() {+ assert_eq!(config_for(PathBuf::from("/bin/bash")).args, vec!["-c"]);+ let ps = config_for(PathBuf::from("pwsh.exe"));+ assert_eq!(ps.kind, ShellKind::PowerShell);+ assert_eq!(ps.args.last().map(String::as_str), Some("-Command"));+ assert!(ps.args.iter().any(|a| a == "-NoProfile"));+ assert!(ps.args.iter().any(|a| a == "-NonInteractive"));+ assert_eq!(config_for(PathBuf::from("cmd.exe")).args, vec!["/D", "/S", "/C"]);+ }++ /// Only a pwsh under Program Files can start in the AppContainer: a Store+ /// alias or a per-user install is skipped, so 5.1 is used instead.+ #[test]+ fn only_a_program_files_pwsh_is_chosen() {+ let pf = [PathBuf::from(r"C:\Program Files"), PathBuf::from(r"C:\Program Files (x86)\")];+ assert!(container_can_run(Path::new(r"C:\Program Files\PowerShell\7\pwsh.exe"), &pf));+ assert!(container_can_run(Path::new(r"c:\program files (x86)\PowerShell\7\pwsh.exe"), &pf));+ for skipped in [+ r"C:\Users\a\AppData\Local\Microsoft\WindowsApps\pwsh.exe",+ r"C:\Users\a\scoop\apps\pwsh\current\pwsh.exe",+ r"C:\Program Files Extra\pwsh.exe",+ r"D:\tools\pwsh.exe",+ ] {+ assert!(!container_can_run(Path::new(skipped), &pf), "{skipped}");+ }+ assert!(!container_can_run(Path::new(r"C:\Program Files\pwsh.exe"), &[]));+ }++ /// A Store PowerShell 7 is an app-execution alias, which cannot start in+ /// the AppContainer, so it is skipped; an installed pwsh is not.+ #[test]+ fn a_store_pwsh_alias_is_recognised_and_an_installed_pwsh_is_not() {+ assert!(is_app_execution_alias(Path::new(+ r"C:\Users\a\AppData\Local\Microsoft\WindowsApps\pwsh.exe"+ )));+ assert!(!is_app_execution_alias(Path::new(r"C:\Program Files\PowerShell\7\pwsh.exe")));+ }++ #[test]+ fn the_verbatim_prefix_is_stripped_only_from_drive_and_unc_paths() {+ assert_eq!(+ without_verbatim_prefix(Path::new(r"\\?\C:\Users\a\proj")),+ PathBuf::from(r"C:\Users\a\proj")+ );+ assert_eq!(+ without_verbatim_prefix(Path::new(r"\\?\UNC\server\share\proj")),+ PathBuf::from(r"\\server\share\proj")+ );+ for unchanged in [r"C:\Users\a", "/home/a/proj", r"\\?\Volume{abc}\x"] {+ assert_eq!(without_verbatim_prefix(Path::new(unchanged)), PathBuf::from(unchanged));+ }+ }++ /// cmd with `/S` strips exactly the outer pair, so the command's own quotes+ /// reach it untouched -- the `\"` an argv quoter would produce never does.+ #[test]+ fn the_cmd_payload_keeps_the_commands_own_quotes() {+ let payload = cmd_payload(r#""C:\Program Files\x.exe" "a b" && echo "done""#);+ assert_eq!(payload, r#"""C:\Program Files\x.exe" "a b" && echo "done"""#);+ assert!(!payload.contains(r#"\""#));+ }++ #[test]+ fn the_powershell_script_runs_the_command_and_reports_its_exit_code() {+ let script = powershell_script("git status");+ assert!(script.contains("\ngit status\n"));+ let (setup, rest) = script.split_once("git status").unwrap();+ assert!(setup.contains("$global:LASTEXITCODE = $null"), "reset before the command");+ assert!(+ setup.contains("Major -lt 6) { Import-Module Microsoft.PowerShell.Management,"),+ "5.1 imports the core modules it cannot autoload in the sandbox"+ );+ assert!(setup.contains("OutputEncoding"));+ assert!(setup.contains("Set-Location -LiteralPath $JanWs"), "real path first");+ assert!(setup.contains("Set-Location JanWs:\\"), "the drive only as the fallback");+ assert!(setup.contains("function jan_cmd {"), "runs inside the function");+ assert!(rest.contains("elseif ($LASTEXITCODE) { $LASTEXITCODE }"), "real code after it");+ assert!(rest.contains("$host.SetShouldExit($JanExit)"), "exit without dropping output");+ }++ /// The syntax note names the language for every non-POSIX shell and is+ /// absent for POSIX, which the model already assumes.+ #[test]+ fn only_non_posix_shells_carry_a_syntax_note() {+ assert!(ShellKind::Posix.syntax_note().is_none());+ assert!(ShellKind::PowerShell.syntax_note().unwrap().contains("PowerShell"));+ assert!(ShellKind::Cmd.syntax_note().unwrap().contains("cmd.exe"));+ }++ /// Run the PowerShell script through a real `pwsh` when one is installed+ /// (`JAN_TEST_PWSH`, else `pwsh` on PATH); skipped otherwise. Covers the+ /// pieces that only an actual PowerShell can prove: quoting survives, a+ /// native command's exit code comes back, and a failing cmdlet is not 0.+ #[tokio::test]+ async fn powershell_runs_commands_and_reports_exit_codes() {+ let Some(pwsh) = std::env::var_os("JAN_TEST_PWSH")+ .map(PathBuf::from)+ .or_else(|| which("pwsh"))+ else {+ eprintln!("skipped: no pwsh");+ return;+ };+ let cfg = config_for(pwsh);+ let run = |command: &'static str| {+ let cfg = cfg.clone();+ async move {+ let child = spawn(&cfg, command, &std::env::temp_dir(), None, ShellEnv::default(), None)+ .await+ .unwrap();+ let pid = child.id().unwrap();+ let out = child.wait_with_output().await.unwrap();+ unregister(None, pid);+ (+ out.status.code(),+ String::from_utf8_lossy(&out.stdout).trim().to_string(),+ String::from_utf8_lossy(&out.stderr).to_string(),+ )+ }+ };+ // Non-ASCII written as escapes to keep the source ASCII; UTF-8 output is+ // what the script's encoding switch is for.+ let (code, stdout, _) = run("Write-Output \"say \"\"hi\"\" & 'bye' \u{fc}n\u{ef}\"").await;+ assert_eq!(code, Some(0));+ assert_eq!(stdout, "say \"hi\" & 'bye' \u{fc}n\u{ef}");++ let (code, _, _) = run("Get-Item ./definitely-not-here-jan").await;+ assert_eq!(code, Some(1), "a failing cmdlet must not report success");++ // A cmdlet failing after a native command that succeeded: the native+ // code (0) must not mask the failure.+ let (code, _, _) = run(+ "& (Get-Process -Id $PID).Path -NoProfile -Command 'exit 0'; \+ Get-Item ./definitely-not-here-jan",+ )+ .await;+ assert_eq!(code, Some(1), "a later cmdlet failure must not report 0");++ // The last statement succeeding is success, as in a POSIX shell.+ let (code, _, _) = run("Get-Item ./definitely-not-here-jan; Write-Output ok").await;+ assert_eq!(code, Some(0));++ // The running PowerShell itself as the native command, so the test does+ // not depend on what else is installed.+ let (code, _, stderr) =+ run("& (Get-Process -Id $PID).Path -NoProfile -Command 'exit 7'").await;+ assert_eq!(code, Some(7), "a native command's own code comes back");+ assert!(!stderr.contains("CLIXML"), "errors stay plain text: {stderr}");++ // Formatted output is flushed before the process exits.+ let (code, stdout, _) = run("Get-Location; Write-Output after").await;+ assert_eq!(code, Some(0));+ assert!(stdout.contains("after") && stdout.contains("Path"), "{stdout}");++ // An error names the command's own text, never the wrapper's.+ let (code, _, stderr) = run("Write-Error boom; exit 2").await;+ assert_eq!(code, Some(2));+ assert!(stderr.contains("boom"), "{stderr}");+ assert!(!stderr.contains("SetShouldExit"), "wrapper leaked: {stderr}");+ assert!(!stderr.contains("ProgressPreference"), "wrapper leaked: {stderr}");++ // A `return` leaves the function early and still reports success.+ let (code, _, _) = run("if ($true) { return }; Get-Item ./definitely-not-here-jan").await;+ assert_eq!(code, Some(0), "an early return is not a failure");++ // The location is a real path, not the fallback drive.+ let (_, stdout, _) = run("$PWD.Provider.Name; $PWD.Path").await;+ assert!(stdout.starts_with("FileSystem"), "{stdout}");+ assert!(!stdout.contains("JanWs:"), "{stdout}");++ // Relative paths resolve in the working directory it was started in.+ let (code, stdout, _) = run("(Convert-Path .).TrimEnd('/', '\\')").await;+ assert_eq!(code, Some(0));+ let tmp = std::env::temp_dir();+ assert_eq!(+ stdout,+ tmp.to_string_lossy().trim_end_matches(['/', '\\']),+ "starts in the working directory"+ );+ }+}+#[cfg(all(test, unix))]mod tests {use super::*;diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 57198095e..741bfcd44 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -9,6 +9,20 @@use serde_json::{json, Value};+/// The `bash` tool's description before any shell-specific note.+const BASH_DESCRIPTION: &str = "Run a shell command in the project root. Returns combined stdout and stderr, followed by a final `[exit N]` line (or `[terminated by signal]`). Judge success by that exit code, not by whether there is text on stderr: many commands (e.g. `git push`) write normal status to stderr on success, so `[exit 0]` means it worked. The output is COMPLETE and verbatim: trust it and do not re-run a command to double-check. It is truncated only when it exceeds 2000 lines or 64KB, and only then is an explicit `[output truncated ...]` notice appended with a temp-file path holding the full output; when truncated the LAST lines are kept (so the final result and errors stay visible). Absent that notice, you have the full output. If the command doesn't finish within `timeout` seconds (default 30), it keeps running in the background instead of erroring or being killed, and this call returns the path to a file where its full output will be written once it finishes; read that file (with the read tool) to collect the result. The file appears only when the command is done, so its presence means the output is complete.";++/// The `bash` description for a shell of `kind`. The model writes POSIX by+/// default, so a PowerShell or cmd host says so up front rather than letting the+/// first command fail. Fixed per process (the shell is resolved once), so the+/// tool array stays byte-identical across turns.+pub fn bash_description(kind: super::proc::ShellKind) -> String {+ match kind.syntax_note() {+ Some(note) => format!("{note} {BASH_DESCRIPTION}"),+ None => BASH_DESCRIPTION.to_string(),+ }+}+/// OpenAI function schemas for the built-in tools, one per `BUILTIN_TOOLS`/// entry. `screenshot` is desktop-only (`feature = "tauri"`), so the headless/// CLI advertises one fewer.@@ -98,7 +112,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "bash",- "description": "Run a shell command in the project root. Returns combined stdout and stderr, followed by a final `[exit N]` line (or `[terminated by signal]`). Judge success by that exit code, not by whether there is text on stderr: many commands (e.g. `git push`) write normal status to stderr on success, so `[exit 0]` means it worked. The output is COMPLETE and verbatim: trust it and do not re-run a command to double-check. It is truncated only when it exceeds 2000 lines or 64KB, and only then is an explicit `[output truncated ...]` notice appended with a temp-file path holding the full output; when truncated the LAST lines are kept (so the final result and errors stay visible). Absent that notice, you have the full output. If the command doesn't finish within `timeout` seconds (default 30), it keeps running in the background instead of erroring or being killed, and this call returns the path to a file where its full output will be written once it finishes; read that file (with the read tool) to collect the result. The file appears only when the command is done, so its presence means the output is complete.",+ "description": bash_description(super::proc::shell().kind),"parameters": {"type": "object","properties": {@@ -344,6 +358,19 @@ mod tests {assert_eq!(once, twice);}+ /// A PowerShell or cmd host says so before the generic text, so the model+ /// reads it before writing a command; a POSIX host is unchanged.+ #[test]+ fn the_bash_description_leads_with_the_shells_syntax() {+ use crate::tools::proc::ShellKind;+ assert_eq!(bash_description(ShellKind::Posix), BASH_DESCRIPTION);+ for kind in [ShellKind::PowerShell, ShellKind::Cmd] {+ let d = bash_description(kind);+ assert!(d.starts_with(kind.syntax_note().unwrap()), "{d}");+ assert!(d.ends_with(BASH_DESCRIPTION));+ }+ }+/// The search schemas name the arguments the handlers actually read; a/// rename on either side would otherwise silently produce a tool whose/// required argument never arrives.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rsnew file mode 100644index 000000000..24c1fa4a1--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tests/sandbox_spawn.rs@@ -0,0 +1,149 @@+//! Starts real shells inside the Windows AppContainer sandbox (#9101).+//!+//! The unit tests around the sandbox check argv quoting and the environment+//! block's layout, and all of them passed while every sandboxed spawn on a real+//! machine failed with os error 203. Only a real `CreateProcessW` into a real+//! container catches that, so this test does one, with the same filtered+//! environment and helper re-exec the shell tool uses.+//!+//! `harness = false` because the backend re-execs the running binary as its+//! helper: under libtest that re-exec would run the test suite again instead of+//! the spawn, so `main` hands control to the helper before anything else.++fn main() {+ tauri_plugin_agent_tools::run_sandbox_helper_if_requested();+ #[cfg(windows)]+ windows::run();+ #[cfg(not(windows))]+ eprintln!("sandbox_spawn: AppContainer only, nothing to run on this platform");+}++#[cfg(windows)]+mod windows {+ use std::path::{Path, PathBuf};+ use tauri_plugin_agent_tools::tools::jail::{self, Backend, Policy};+ use tauri_plugin_agent_tools::tools::proc::{self, ShellConfig, ShellEnv, ShellKind};++ pub fn run() {+ assert_eq!(+ jail::backend(),+ Backend::AppContainer,+ "the sandbox must be available on a Windows runner"+ );+ // Deliberately the raw `TEMP` path: on a runner it is the 8.3+ // `RUNNER~1` form, as it is for any user with a long name, and the+ // helper must still give the shell a working directory it can use.+ let ws = std::env::temp_dir().join(format!("jan_sandbox_spawn_{}", std::process::id()));+ std::fs::create_dir_all(&ws).expect("create workspace");+ let rt = tokio::runtime::Runtime::new().expect("runtime");++ let system = PathBuf::from(std::env::var_os("SystemRoot").expect("SystemRoot"))+ .join("System32");+ let shells = [+ ("resolved", proc::shell().clone()),+ (+ "powershell 5.1",+ ShellConfig {+ program: system.join(r"WindowsPowerShell\v1.0\powershell.exe"),+ args: proc::shell_args(ShellKind::PowerShell),+ kind: ShellKind::PowerShell,+ },+ ),+ (+ "cmd",+ ShellConfig {+ program: system.join("cmd.exe"),+ args: proc::shell_args(ShellKind::Cmd),+ kind: ShellKind::Cmd,+ },+ ),+ ];+ assert_ne!(+ proc::shell().kind,+ ShellKind::Posix,+ "Windows must resolve a native shell, not bash: {}",+ proc::shell().program.display()+ );+ for (label, shell) in &shells {+ let (ok, out) = rt.block_on(spawn(shell, &ws, "echo ok"));+ assert!(ok, "{label}: a command must start and succeed in the sandbox: {out}");+ assert!(out.contains("ok"), "{label}: output lost: {out}");+ let (ok, out) = rt.block_on(spawn(shell, &ws, "exit 3"));+ assert!(!ok, "{label}: a failing command must report failure: {out}");+ eprintln!("sandbox_spawn: {label} ({}) ok", shell.program.display());+ }+ // Windows PowerShell 5.1 cannot autoload modules in the container, so+ // cmdlets from each imported inbox module must still resolve.+ let (ok, out) = rt.block_on(spawn(+ &shells[1].1,+ &ws,+ "Get-ChildItem | Out-Null; 'x' | ConvertTo-Json; echo ok",+ ));+ assert!(ok && out.contains("ok"), "powershell 5.1 core cmdlets: {out}");+ // Each shell works *in* the workspace: a relative write lands there, a+ // listing reads it back, and an external program starts. PowerShell+ // otherwise begins at `C:\`, which the container cannot use, and on+ // 5.1 then fails every external program ("Cannot find drive").+ for (label, shell, command) in [+ (+ "resolved",+ &shells[0].1,+ "Set-Content -Path rel-a.txt -Value hi; Get-ChildItem rel-a.txt | Out-Null; \+ Get-Content rel-a.txt; whoami | Out-Null; cmd /c exit 5",+ ),+ (+ "powershell 5.1",+ &shells[1].1,+ "Set-Content -Path rel-b.txt -Value hi; Get-ChildItem rel-b.txt | Out-Null; \+ Get-Content rel-b.txt; whoami | Out-Null; cmd /c exit 5",+ ),+ // The external program here is a nested cmd: `whoami >NUL` is+ // refused ("Access is denied.") in the container, which is not the+ // workspace behavior this checks.+ ("cmd", &shells[2].1, "echo hi> rel-c.txt && type rel-c.txt && cmd /c exit 5"),+ ] {+ let (code, out) = rt.block_on(spawn_code(shell, &ws, command));+ assert_eq!(code, Some(5), "{label}: the external program's code comes back: {out}");+ assert!(out.contains("hi"), "{label}: relative read failed: {out}");+ }+ for name in ["rel-a.txt", "rel-b.txt", "rel-c.txt"] {+ assert!(ws.join(name).is_file(), "{name} must be written inside the workspace");+ }+ // An error names the command, never the wrapper script around it.+ for (label, shell) in &shells[..2] {+ let (ok, out) = rt.block_on(spawn(shell, &ws, "Write-Error boom; exit 2"));+ assert!(!ok && out.contains("boom"), "{label}: {out}");+ assert!(!out.contains("SetShouldExit"), "{label}: wrapper leaked: {out}");+ }+ // cmd keeps a command's own quotes rather than seeing them escaped.+ let (ok, out) = rt.block_on(spawn(&shells[2].1, &ws, r#"echo "a b""#));+ assert!(ok && out.contains(r#""a b""#), "cmd quoting: {out}");++ let _ = std::fs::remove_dir_all(&ws);+ }++ /// Spawn `command` through the sandbox exactly as the shell tool does:+ /// `jail::wrap` turns the shell into the helper re-exec, and `proc::spawn`+ /// clears the environment down to the allowlist before starting it.+ async fn spawn(shell: &ShellConfig, ws: &Path, command: &str) -> (bool, String) {+ let (code, text) = spawn_code(shell, ws, command).await;+ (code == Some(0), text)+ }++ /// [`spawn`] with the exit code itself.+ async fn spawn_code(shell: &ShellConfig, ws: &Path, command: &str) -> (Option<i32>, String) {+ let policy = Policy::new(ws, false);+ let wrapped = jail::wrap(shell, &policy).expect("AppContainer wrapper");+ let child = proc::spawn(&wrapped, command, ws, None, ShellEnv::default(), None)+ .await+ .expect("spawn the helper");+ let pid = child.id();+ let out = child.wait_with_output().await.expect("wait");+ if let Some(pid) = pid {+ proc::unregister(None, pid);+ }+ let mut text = String::from_utf8_lossy(&out.stdout).into_owned();+ text.push_str(&String::from_utf8_lossy(&out.stderr));+ (out.status.code(), text)+ }+}diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex 2d2f8e7cb..d89f0f94c 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -538,6 +538,8 @@ mod tests {/// The `PreCompact` call site: the hook runs, and it is told how much/// conversation is about to be summarized away -- the one fact a hook that/// archives a transcript needs.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn pre_compact_hooks_fire_with_the_message_count() {let root = std::env::temp_dir().join(format!(diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 2254c0496..f198d8abc 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -289,9 +289,16 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Strstd::env::consts::ARCH);- let shell = std::env::var("SHELL")- .or_else(|_| std::env::var("COMSPEC"))- .unwrap_or_else(|_| "unknown".to_string());+ // The shell the tool actually runs, not the user's `$SHELL`/`COMSPEC`: on+ // Windows those name cmd even when the tool resolved PowerShell, and the+ // model writes its commands for whatever is named here.+ let resolved = tauri_plugin_agent_tools::tools::proc::shell();+ let shell = display_path(&resolved.program);+ let shell_note = resolved+ .kind+ .syntax_note()+ .map(|note| format!("\n{note}"))+ .unwrap_or_default();// Where to do temporary work. Named by the one spelling that resolves from// both `bash` and the filesystem tools on this platform: `/tmp` where the@@ -310,7 +317,7 @@ fn runtime_environment_block(project_root: &Path, scratch: Option<&Path>) -> Str"# Runtime Environment\n\n\Work directory: `{cwd}`\n\OS: `{os}`\n\-Shell: `{shell}`{scratch_line}"+Shell: `{shell}`{shell_note}{scratch_line}")}@@ -1213,6 +1220,25 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The block names the shell the tool resolved, not `$SHELL`/`COMSPEC`,+ /// and carries the syntax note exactly when that shell needs one.+ #[test]+ fn runtime_environment_block_names_the_resolved_shell() {+ let root = scratch_project("resolved_shell");+ std::fs::create_dir_all(&root).unwrap();+ let block = runtime_environment_block(&root, None);+ let resolved = tauri_plugin_agent_tools::tools::proc::shell();+ assert!(+ block.contains(&format!("Shell: `{}`", display_path(&resolved.program))),+ "got: {block}"+ );+ match resolved.kind.syntax_note() {+ Some(note) => assert!(block.contains(note)),+ None => assert!(!block.contains("not bash/POSIX")),+ }+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn work_directory_is_written_with_forward_slashes() {let root = scratch_project("cwd_slashes");diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex a298014a1..ff41d5ad2 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -8621,6 +8621,8 @@ mod tests {/// Phase 2: a plugin-declared tool is dispatched, runs its command with the/// call's arguments on stdin, and returns its stdout as the tool result.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_plugin_declared_tool_is_dispatched_and_returns_its_output() {let root = hooks_root("plugintool");@@ -8740,6 +8742,8 @@ mod tests {/// A hook that does not deny leaves the MCP call alone, and its input/// reaches the hook: a PreToolUse audit hook is useless if it cannot see/// what was asked for.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn an_mcp_pretooluse_hook_sees_the_call_and_may_let_it_through() {let root = hooks_root("mcpallow");@@ -9449,6 +9453,8 @@ mod tests {/// the toolset's `execute_builtin` bracket, so they are pinned here: each/// fires, each receives its payload, and each is still live in Plan mode/// (unlike the tool events above).+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn session_and_prompt_hooks_fire_with_their_payloads() {let root = hooks_root("lifecycle");@@ -10525,6 +10531,8 @@ mod tests {/// already holds delivers a merged background notice carrying a headline/// and the matched content, and the pending flag clears once all conditions/// are met.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn monitor_match_arrives_as_a_headlined_background_notice() {let root = unique_project_root();@@ -10587,6 +10595,8 @@ mod tests {/// fired leaves `background_pending` false (the turn ends and the user can/// keep talking), while a queued match still resumes the run, and taking/// it clears the flag again.+ // POSIX command text: Windows runs PowerShell.+ #[cfg(unix)]#[tokio::test]async fn a_session_owned_monitor_does_not_park_the_run_until_it_fires() {let root = unique_project_root();diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex ade7c6e0e..03bbc26f4 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -64,12 +64,9 @@ mod prefix_stability;/// Render a path for embedding in a hook/plugin-tool shell command in tests.///-/// The hook runner hands the command to the resolved shell, which on the-/// Windows CI runner is git-bash: a native `C:\Users\...` path reaches it as a-/// backslash-escaped string and those escapes are eaten, so the command writes-/// to a mangled name and the file the test asserts on never appears. Bash-/// accepts forward slashes on Windows, and the quotes keep a path containing-/// spaces a single word.+/// Forward slashes and single quotes read the same in bash and PowerShell, so+/// a `C:\Users\...` temp path survives either shell, and the quotes keep a path+/// containing spaces a single word.#[cfg(test)]pub(crate) fn shell_quoted_path(path: &std::path::Path) -> String {format!("'{}'", path.to_string_lossy().replace('\\', "/"))diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsxindex 92c093950..152f65bb5 100644--- a/web-app/src/containers/message/AgentToolWidget.tsx+++ b/web-app/src/containers/message/AgentToolWidget.tsx@@ -168,9 +168,11 @@ export const TerminalWidget = memo(<spanclassName={cn('ml-auto shrink-0 rounded px-1.5 py-0.5 font-mono',+ // Success is neutral rather than `primary`: the default accent+ // is an orange-red that read as a failure next to `exit 0`.failed? 'bg-destructive/10 text-destructive'- : 'bg-primary/10 text-primary'+ : 'bg-muted text-muted-foreground')}>{t('tools:toolCall.exitCode', { code: result.exit })}