Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(release): backport #9139, #9129, #9130 and #9141 to v0.8.5 (Windows shell tool) (#9143)
James Dam4397d1a7c70c
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/adk/python/tests/test_adk.py b/adk/python/tests/test_adk.pyindex e80d00086..feda204bd 100644--- a/adk/python/tests/test_adk.py+++ b/adk/python/tests/test_adk.py@@ -202,7 +202,7 @@ class AdkTest(unittest.TestCase):self.assertTrue(fork.id)self.assertNotEqual(fork.id, first.id)self.assertEqual(fork.model, "stub-model")- self.assertIn("bash", fork.get_tools()["tools"])+ self.assertIn("shell", fork.get_tools()["tools"])def test_a_turn_is_bounded_when_nobody_drains_it(self) -> None:scratch = self.prepare([prose("unread")])diff --git a/docs/src/pages/docs/agent/adk-nightly.mdx b/docs/src/pages/docs/agent/adk-nightly.mdxindex 1fc3e181c..58c13d570 100644--- a/docs/src/pages/docs/agent/adk-nightly.mdx+++ b/docs/src/pages/docs/agent/adk-nightly.mdx@@ -57,8 +57,9 @@ version and compatible runtime. Use it rather than the moving latest manifest.## Install the runtime-For a first run, the hosted installer puts the latest nightly `jan` on your PATH, which also gives-you `jan login`:+For a first run, the hosted installer puts the latest nightly `jan` in `~/.local/bin`, which also+gives you `jan login`. Make sure that directory is on your PATH; on Windows, see the+[Agent quickstart](/docs/agent/quickstart) for the `-AddToPath` form:```bashcurl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash # macOS / Linuxdiff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex f87e28c5d..ba2ccf6ce 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -295,7 +295,7 @@ Each tool is advertised to the model as `host__<name>`. A name that is not ASCIIoriginal name is appended so names that sanitize alike stay distinct. `yam.move_ee_ik` isadvertised as `host__yam_move_ee_ik_<hash>`. The mapping is deterministic, and `init.tool_specs`shows the name the model will call. Still refused: an empty name, a name with a control character,-a built-in's name (`bash`, `read`, ...), and two declarations that land on the same advertised name.+a built-in's name (`shell`, `read`, ...), and two declarations that land on the same advertised name.When the model calls one, the run emits a `tool_request` and waits:@@ -394,7 +394,7 @@ The first line of a `stream-json` run is always an `init` record, printed beforeevent:```json-{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","bash","host__robot_arm_move"],"tool_specs":[{"type":"function","function":{"name":"host__robot_arm_move","description":"Move the arm.","parameters":{"type":"object"}}}],"input_kinds":["user","abort","permission","tool_result"],"input_content_parts":{"mime_types":["image/png","image/jpeg","image/gif","image/webp"],"max_image_bytes":5242880,"max_message_image_bytes":10485760,"max_images":8,"max_line_bytes":16777216,"max_echo_bytes":4096}}+{"type":"init","protocol_version":1,"session_id":"3f7a91c2-4e5d-4a6b-8c7d-0e1f2a3b4c5d","model":"tokamak-1-preview","cwd":"/home/me/app","tools":["read","write","shell","host__robot_arm_move"],"tool_specs":[{"type":"function","function":{"name":"host__robot_arm_move","description":"Move the arm.","parameters":{"type":"object"}}}],"input_kinds":["user","abort","permission","tool_result"],"input_content_parts":{"mime_types":["image/png","image/jpeg","image/gif","image/webp"],"max_image_bytes":5242880,"max_message_image_bytes":10485760,"max_images":8,"max_line_bytes":16777216,"max_echo_bytes":4096}}```| Field | Notes |@@ -736,7 +736,7 @@ jan mcp serve --tool read --tool grep # narrow the set| `--port <PORT>` | Port for `http`. Defaults to an ephemeral one || `--token <TOKEN>` | Bearer token for `http`. One is generated and printed if omitted || `--allow-write` | Offer `write` and `edit`, confined to the project root |-| `--allow-exec` | Offer `bash`, under the same OS sandbox the agent's shell uses |+| `--allow-exec` | Offer `shell`, under the same OS sandbox the agent's shell uses || `--tool <NAME>` | Serve only these tools. Repeatable; never widens what the flags above permit |The default set touches no project file, and the two classes that can change the machine are opt-in:diff --git a/docs/src/pages/docs/agent/files.mdx b/docs/src/pages/docs/agent/files.mdxindex 08ac3d510..b6692e03e 100644--- a/docs/src/pages/docs/agent/files.mdx+++ b/docs/src/pages/docs/agent/files.mdx@@ -71,7 +71,7 @@ produced before it lands.| Tool | What it does || --- | --- |-| `bash` | Run a shell command in the project root |+| `shell` | Run a shell command in the project root |Output is combined stdout and stderr, followed by a final `[exit N]` line. That last part matters:it's how the agent knows a command actually failed rather than assuming it worked.@@ -93,7 +93,7 @@ command. If you only meant to allow this one, use `y`.## Staying inside the projectPath arguments are checked against the project root, so a write outside the project is caught before-it happens rather than silently allowed. `bash` runs with the project root as its working directory.+it happens rather than silently allowed. `shell` runs with the project root as its working directory.This is a guard, not a jail: a shell command can still reach outside if you approve it. Plan modeblocks the whole category, and that's the control to reach for when you want a hard boundary. Seediff --git a/docs/src/pages/docs/agent/hide-secrets.mdx b/docs/src/pages/docs/agent/hide-secrets.mdxindex fa09a5205..ce30c8088 100644--- a/docs/src/pages/docs/agent/hide-secrets.mdx+++ b/docs/src/pages/docs/agent/hide-secrets.mdx@@ -45,7 +45,7 @@ schemas and ids are left alone. It applies to the main run, subagents and compac```texttool output "token=ghp_abc…" -> provider sees "token=$$GITHUBTOKEN_3P8W5JH1TK2Q$$"-model calls bash("curl -H $$GITHUBTOKEN_3P8W5JH1TK2Q$$") -> bash runs with the real token+model calls shell("curl -H $$GITHUBTOKEN_3P8W5JH1TK2Q$$") -> shell runs with the real token```- A placeholder is derived from the secret and a random key kept in `~/.jan/secret-placeholder.key`diff --git a/docs/src/pages/docs/agent/hooks.mdx b/docs/src/pages/docs/agent/hooks.mdxindex 121ac6396..1554761b4 100644--- a/docs/src/pages/docs/agent/hooks.mdx+++ b/docs/src/pages/docs/agent/hooks.mdx@@ -13,11 +13,11 @@ prompt is submitted, when a session starts or ends, and before a compaction. Thestdin as JSON and the command's stdout is its answer.The point is to make a team policy enforceable rather than merely requested. "Run `cargo fmt` after-every `edit`", "never let `bash` touch `infra/`", "log every tool call to our audit sink" used to+every `edit`", "never let `shell` touch `infra/`", "log every tool call to our audit sink" used tohave only one lever - a line in the system prompt, which the model is free to ignore. A hook is notadvice. A `PreToolUse` hook that answers `deny` stops the call.-A hook is a shell command, not a plugin runtime. It runs through the same confinement `bash` gets,+A hook is a shell command, not a plugin runtime. It runs through the same confinement `shell` gets,so nothing here is a new execution primitive.## A first hook@@ -82,7 +82,7 @@ shared config does not take the other hooks down with it - it is dropped, with a```json[- { "event": "PreToolUse", "matcher": "bash", "command": "./hooks/audit.sh", "timeout_secs": 10 },+ { "event": "PreToolUse", "matcher": "shell", "command": "./hooks/audit.sh", "timeout_secs": 10 },{ "event": "SessionEnd", "command": "./hooks/report.sh" }]```@@ -121,7 +121,7 @@ event has them:{"event": "PreToolUse","project_root": "/home/you/code/app",- "tool_name": "bash",+ "tool_name": "shell","tool_input": { "command": "rm -rf infra/" },"session_id": "01J9...","message_count": 24@@ -137,6 +137,11 @@ event has them:| `session_id` | `SessionStart`, `SessionEnd`, `UserPromptSubmit` || `message_count` | `SessionStart`, `UserPromptSubmit`, `PreCompact` |+The shell tool is named `shell` (formerly `bash`). A `matcher` or a script that tests `tool_name`+for `bash` no longer matches it; change it to `shell`. A `bash` matcher is reported: by the `jan`+CLI when a run starts, and by the desktop app under each shell call. A script's `tool_name` check+cannot be detected, so search your hooks for it.+## The answerWhatever the command writes to stdout, up to 64KB.@@ -160,7 +165,7 @@ When a `PreToolUse` hook denies, the model sees the same refusal shape every oththe hook's reason attached:```-ERROR: tool 'bash' denied: infra/ is managed by terraform, not by the agent+ERROR: tool 'shell' denied: infra/ is managed by terraform, not by the agent```A worked example - refuse shell commands that touch a protected directory:@@ -168,7 +173,7 @@ A worked example - refuse shell commands that touch a protected directory:```toml[[hooks]]event = "PreToolUse"-matcher = "bash"+matcher = "shell"command = "jq -e '.tool_input.command | test(\"infra/\") | not' >/dev/null || echo '{\"decision\":\"deny\",\"reason\":\"infra/ is managed by terraform, not by the agent\"}'"```@@ -209,7 +214,7 @@ Entries dropped while loading - a bad event name, a blank command, an invalid mareported the same way, once per run, before anything fires.<Callout type="info">-Hooks run confined exactly the way `bash` does. Under a sandboxed run a hook is sandboxed; on the+Hooks run confined exactly the way `shell` does. Under a sandboxed run a hook is sandboxed; on theCLI, where the sandbox is off by default, a hook runs with your own access. The shell environment isthe same minimal one, so a hook does not see your secrets unless `[tools] env_passthrough` or`[tools] env_set` names them. See [Tool Permissions](/docs/agent/permissions#the-shell-environment).@@ -257,7 +262,7 @@ description = "End tag, defaults to HEAD"```The model sees it as `plugin__release-tools__changelog`. The `plugin__<plugin>__<tool>` form is-mandatory so a plugin cannot shadow a built-in like `bash` or `edit`, or collide with an MCP tool.+mandatory so a plugin cannot shadow a built-in like `shell` or `edit`, or collide with an MCP tool.Names are ASCII alphanumerics, `_` and `-`, may not contain `__`, and the whole qualified name mustbe 64 characters or shorter - several providers reject a longer function name, and reject the entirerequest rather than the one tool. An entry that breaks a rule is dropped; where two plugins declare@@ -305,7 +310,7 @@ jan cli agent status --project ~/code/app"hooks": [{"event": "PreToolUse",- "matcher": "bash",+ "matcher": "shell","command": "./hooks/audit.sh","timeout_secs": 10,"source": "/home/you/.jan/projects/app-1a2b3c4d/plugins/auditor/hooks/hooks.json"diff --git a/docs/src/pages/docs/agent/index.mdx b/docs/src/pages/docs/agent/index.mdxindex 4c244326b..6cd8bf3fe 100644--- a/docs/src/pages/docs/agent/index.mdx+++ b/docs/src/pages/docs/agent/index.mdx@@ -73,6 +73,12 @@ curl -fsSL https://delta.jan.ai/jan-cli/install-jan-agent.sh | bash<Tabs.Tab>```powershellirm https://delta.jan.ai/jan-cli/install-jan-agent.ps1 | iex+```++Installs to `%USERPROFILE%\.local\bin`. To also add it to your user `PATH`:++```powershell+& ([scriptblock]::Create((irm https://delta.jan.ai/jan-cli/install-jan-agent.ps1))) -AddToPath```</Tabs.Tab></Tabs>diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdxindex b030e45ed..c9a800c59 100644--- a/docs/src/pages/docs/agent/mcp.mdx+++ b/docs/src/pages/docs/agent/mcp.mdx@@ -155,7 +155,7 @@ rather than a person who can answer a permission prompt:| Flag | Adds || --- | --- || `--allow-write` | `write` and `edit`, confined to the project root |-| `--allow-exec` | `bash`, under the same OS sandbox the agent's shell uses |+| `--allow-exec` | `shell`, under the same OS sandbox the agent's shell uses || `--tool NAME` | Narrows the set to these names; never widens what the flags above permit |Anything that would otherwise wait for an approval returns an error instead of blocking, so a peerdiff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex 160a008c3..aaebec9f1 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -21,7 +21,7 @@ Reads are free. Writes and shell commands stop and ask:n no```-For `write` and `edit` you see a diff first. For `bash` you see the exact command.+For `write` and `edit` you see a diff first. For `shell` you see the exact command.`a` grants that capability for the rest of the session. Nothing is written to disk, so a new sessionstarts cautious again - a grant can't leak into tomorrow.@@ -34,7 +34,7 @@ Every tool maps to one capability, and approval applies at that level rather tha| --- | --- | --- || Read | `read`, `ls`, `find`, `grep`, `web_search`, `web_fetch`, `memory_read`, `memory_list`, `skill_read`, `skill_list` | Allowed || Write | `write`, `edit`, `memory_write`, `skill_write` | Prompts |-| Exec | `bash` | Prompts |+| Exec | `shell` | Prompts |So approving `a` on a shell command allows further shell commands, not just that one. That's thetrade for not being asked twenty times during a test loop - and the reason to prefer `y` when you@@ -43,7 +43,7 @@ only meant one.## Path checksTools that take a path have it checked against the project root, so a write outside the project is-refused before it happens. `bash` has no path argument and runs in the project root; a command you+refused before it happens. `shell` has no path argument and runs in the project root; a command youapprove can still reach outside, which is why plan mode exists as the hard boundary.A symbolic link is followed only while it stays inside the project (or the session scratch). Links@@ -82,6 +82,13 @@ allow_write = []`deny` always wins over `allow`. A tool in both lists is denied.+The shell tool is named `shell`; it used to be `bash`, and that name is no longer recognised.+Rename `bash` to `shell` wherever you name the tool: `allow`, `deny`, hook matchers and a+subagent's `allowed_tools`. An old `deny = ["bash"]` matches nothing. The `jan` CLI warns about+each such `[tools]` entry when a run starts (the desktop app does not read `[tools]`), and every+surface refuses a subagent whose `allowed_tools` still says `bash`. `jan mcp serve --tool bash`+says so too.+## The shell sandboxJan can run shell commands under OS confinement - bubblewrap on Linux, Seatbelt on macOS,@@ -101,7 +108,7 @@ Whether it is on depends on the surface:| Surface | Sandbox | Can it be changed? || --- | --- | --- |-| Desktop chat agent | Always on | No. If no sandbox can be established, `bash` is withheld rather than run unconfined |+| Desktop chat agent | Always on | No. If no sandbox can be established, `shell` is withheld rather than run unconfined || `jan` CLI and console | **Off by default** | Yes, see below |The CLI runs unconfined because it is a coding agent in your own project, started from your own@@ -146,7 +153,23 @@ 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.+with `enabled: true` that combination is what withholds `shell` entirely.++### Which shell runs commands++On macOS and Linux the `shell` 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`), when it is installed under Program Files. The sandbox can only start+ programs from folders all apps may read, so a `pwsh` from the Microsoft Store, scoop, a zip in+ your profile or a dotnet tool is skipped in favor of 5.1.+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 environmentdiff --git a/docs/src/pages/docs/agent/quickstart.mdx b/docs/src/pages/docs/agent/quickstart.mdxindex 502fdd03f..eb9754216 100644--- a/docs/src/pages/docs/agent/quickstart.mdx+++ b/docs/src/pages/docs/agent/quickstart.mdx@@ -45,6 +45,13 @@ sure the directory is on your `PATH`.<Tabs.Tab>```powershellirm https://delta.jan.ai/jan-cli/install-jan-agent.ps1 | iex+```++Installs to `%USERPROFILE%\.local\bin`, which isn't on your `PATH` by default. To install and add+it to your user `PATH` in one go, then open a new terminal:++```powershell+& ([scriptblock]::Create((irm https://delta.jan.ai/jan-cli/install-jan-agent.ps1))) -AddToPath```</Tabs.Tab></Tabs>@@ -188,7 +195,9 @@ jan --task "fix the failing test in tests/auth"## Troubleshooting**`jan: command not found`** - the install directory isn't on your `PATH`. The installer prints a-note when it detects this. Add `~/.local/bin` to your shell profile.+note when it detects this. Add `~/.local/bin` to your shell profile. On Windows, re-run the installer+with `-AddToPath` (see [Install Nightly](#install-nightly)) and open a new terminal. If the installer warns that+another `jan` comes first on your `PATH`, remove the entry it names.**"no providers configured"** - run `jan config set --provider <id> --api-key <key>`, or `jan login`for Tokamak. `jan config path` prints the file it reads.diff --git a/docs/src/pages/docs/agent/run-modes.mdx b/docs/src/pages/docs/agent/run-modes.mdxindex 2286cfb70..b4e5b742b 100644--- a/docs/src/pages/docs/agent/run-modes.mdx+++ b/docs/src/pages/docs/agent/run-modes.mdx@@ -25,7 +25,7 @@ because the CLI does not sandbox commands by default.Add `--sandbox` to run them under OS confinement (bubblewrap on Linux, Seatbelt on macOS,AppContainer on Windows), confined to the project directory; with it on, if no sandbox can be-established the `bash` tool refuses to run at all. It can also be turned on permanently - see+established the `shell` tool refuses to run at all. It can also be turned on permanently - see[the shell sandbox](/docs/agent/permissions#the-shell-sandbox).Some things are denied outright and no mode lifts them:diff --git a/packages/adk/tests/adk.test.mjs b/packages/adk/tests/adk.test.mjsindex 82863ed28..000c69cac 100644--- a/packages/adk/tests/adk.test.mjs+++ b/packages/adk/tests/adk.test.mjs@@ -573,7 +573,7 @@ test('two sessions never see each other’s events', { skip: missingRuntime }, aassert.notEqual(fork.id, first.id)assert.equal(fork.model, 'stub-model')const forked = await fork.getTools()- assert.ok(forked.tools.includes('bash'))+ assert.ok(forked.tools.includes('shell'))})diff --git a/scripts/install-jan-agent.ps1 b/scripts/install-jan-agent.ps1index d9debca0b..7e03c2cf9 100644--- a/scripts/install-jan-agent.ps1+++ b/scripts/install-jan-agent.ps1@@ -38,16 +38,60 @@ $BinaryName = 'jan.exe'$NativeArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }# Native first, then x86_64 under emulation: it is all that pre-ARM64 versions,# or a nightly whose ARM leg failed, have to offer.-$PlatformKeys = if ($NativeArch -eq 'ARM64') { @('windows-aarch64', 'windows-x86_64') }- else { @('windows-x86_64') }+# @() outside the `if`: PowerShell unrolls a one-element array returned from it,+# which made $PlatformKeys[0] the character 'w' and warned about emulation on x64.+$PlatformKeys = @(if ($NativeArch -eq 'ARM64') { 'windows-aarch64', 'windows-x86_64' }+ else { 'windows-x86_64' })if (-not $Dir) {if ($env:JAN_INSTALL_DIR) {$Dir = $env:JAN_INSTALL_DIR} else {- $Dir = Join-Path $env:LOCALAPPDATA 'Programs\Jan'+ # Same place as install-jan-agent.sh (and uv's Windows installer). Never the+ # desktop app's %LOCALAPPDATA%\Programs\Jan: its updater runs the old+ # uninstaller, which deletes that whole directory, and up to 0.8.4 the+ # desktop executable there was Jan.exe, which jan.exe would overwrite.+ $Dir = Join-Path $env:USERPROFILE '.local\bin'}}+function ConvertTo-FullPath {+ param([string]$Path)+ try {+ # Resolves against PowerShell's location, not the process directory, and+ # works for paths that do not exist yet.+ $p = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)+ return [IO.Path]::GetFullPath($p).TrimEnd('\')+ } catch {+ return $Path.TrimEnd('\')+ }+}++# The desktop uninstaller, which every app update runs, ends with+# `RMDir /r "$INSTDIR"`, so nothing at or under the app's directory survives,+# and that directory may not exist yet. The app installs as Jan or Jan-<channel>+# (Jan-nightly, Jan-beta); matching that segment rather than a bare `Jan*`+# keeps unrelated folders such as Programs\Janus usable.+function Test-DesktopAppDir {+ param([string]$Path)+ $full = ConvertTo-FullPath $Path+ $roots = @($env:ProgramFiles, $env:ProgramW6432)+ if ($env:LOCALAPPDATA) { $roots += Join-Path $env:LOCALAPPDATA 'Programs' }+ foreach ($root in $roots) {+ if (-not $root) { continue }+ $prefix = (ConvertTo-FullPath $root) + '\'+ if ($full.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {+ $segment = $full.Substring($prefix.Length).Split('\')[0]+ if ($segment -eq 'Jan' -or $segment -like 'Jan-*') { return $true }+ }+ }+ # Catches a desktop install in a custom location.+ return (Test-Path -LiteralPath (Join-Path $Path 'uninstall.exe')) -and+ (Test-Path -LiteralPath (Join-Path $Path 'resources'))+}++if (Test-DesktopAppDir $Dir) {+ throw "$Dir is (or is inside) the Jan desktop app's install directory, which is deleted on every app update; choose another -Dir"+}if ([Environment]::Is64BitOperatingSystem -eq $false) {throw 'no published build for 32-bit Windows; use -Source'@@ -88,18 +132,108 @@ function Install-Binary {}$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')- $onPath = ($env:Path -split ';') -contains $Dirif ($AddToPath) {if (($userPath -split ';') -notcontains $Dir) {- $updated = if ([string]::IsNullOrEmpty($userPath)) { $Dir } else { "$userPath;$Dir" }- [Environment]::SetEnvironmentVariable('Path', $updated, 'User')- Write-Host "added $Dir to your user PATH; open a new terminal to pick it up"+ if (Add-ToUserPath -Key ([Microsoft.Win32.Registry]::CurrentUser) -Entry $Dir) {+ Write-Host "added $Dir to your user PATH; open a new terminal to pick it up"+ }} else {Write-Host "$Dir is already on your user PATH"}- } elseif (-not $onPath) {- Write-Host "note: $Dir is not on your PATH; re-run with -AddToPath or add it yourself"}++ # The binary can be in place and still not be what `jan` runs: a directory+ # earlier on PATH may hold another jan.exe (see Get-PathWarning).+ $warning = Get-PathWarning -Dir $Dir -Dest $dest -AddToPathRequested:$AddToPath `+ -MachinePath ([Environment]::GetEnvironmentVariable('Path', 'Machine')) `+ -UserPath ([Environment]::GetEnvironmentVariable('Path', 'User'))+ if ($warning) { Write-Warning $warning }+}++# Returns $true once Entry is appended to <Key>\Environment\Path, or $false,+# with a warning, when the value cannot be edited safely. The binary is+# already installed by then, so failing here must not abort the script.+function Add-ToUserPath {+ param([Parameter(Mandatory)][Microsoft.Win32.RegistryKey]$Key, [Parameter(Mandatory)][string]$Entry)+ $manual = "add $Entry to your user PATH yourself (System Properties > Advanced > Environment Variables)"+ try {+ # Edit the raw registry value rather than SetEnvironmentVariable, which+ # rewrites Path as REG_SZ with every %VAR% expanded (janhq/jan#9096).+ $envKey = $Key.CreateSubKey('Environment')+ try {+ $raw = $envKey.GetValue('Path', $null, 'DoNotExpandEnvironmentNames')+ $kind = if ($null -ne $raw) { $envKey.GetValueKind('Path') } else { 'ExpandString' }+ # A REG_MULTI_SZ or REG_BINARY Path is already damaged; rewriting it as a+ # string could lose whatever it holds, so leave it for the user.+ if (($kind -ne 'String' -and $kind -ne 'ExpandString') -or+ ($null -ne $raw -and $raw -isnot [string])) {+ Write-Warning "your user Path is stored as $kind rather than a string, so it was left alone; $manual"+ return $false+ }+ $updated = if ([string]::IsNullOrEmpty($raw)) { $Entry } else { "$($raw.TrimEnd(';'));$Entry" }+ $envKey.SetValue('Path', $updated, $kind)+ } finally {+ $envKey.Close()+ }+ } catch {+ Write-Warning "could not update your user Path ($($_.Exception.Message)); $manual"+ return $false+ }+ # Deleting a variable that does not exist leaves the registry alone but makes+ # .NET broadcast WM_SETTINGCHANGE, so new terminals see the new Path. It has+ # to be [NullString]::Value: PowerShell passes $null to a string parameter+ # as "", which .NET Framework treats as a delete but .NET 10 (PowerShell 7.6)+ # stores as an empty variable.+ [Environment]::SetEnvironmentVariable('JAN_INSTALL_PATH_REFRESH', [NullString]::Value, 'User')+ return $true+}++# The directory a new terminal runs `jan` from: the machine Path, then the+# user Path, each entry expanded, PATHEXT order within a directory.+function Find-JanOnPath {+ param([string]$MachinePath, [string]$UserPath)+ $exts = @(if ($env:PATHEXT) { $env:PATHEXT -split ';' | Where-Object { $_ } } else { '.COM', '.EXE', '.BAT', '.CMD' })+ $scopes = @(@{ Name = 'system'; Value = $MachinePath }, @{ Name = 'user'; Value = $UserPath })+ foreach ($scope in $scopes) {+ foreach ($entry in ("$($scope.Value)" -split ';')) {+ $d = [Environment]::ExpandEnvironmentVariables($entry.Trim().Trim('"'))+ if (-not $d) { continue }+ foreach ($ext in $exts) {+ # [IO.File]::Exists rather than Test-Path/Join-Path, which throw on a+ # missing drive or a malformed entry.+ $file = "jan$($ext.ToLowerInvariant())"+ try { $hit = [IO.File]::Exists([IO.Path]::Combine($d, $file)) } catch { $hit = $false }+ if ($hit) { return [pscustomobject]@{ Dir = $d; File = [IO.Path]::Combine($d, $file); Scope = $scope.Name } }+ }+ }+ }+ return $null+}++# A warning for when a new terminal would not run Dest as `jan`, or $null.+function Get-PathWarning {+ param([string]$Dir, [string]$Dest, [string]$MachinePath, [string]$UserPath, [switch]$AddToPathRequested)+ $target = ConvertTo-FullPath $Dir+ $listed = @("$MachinePath;$UserPath" -split ';' | Where-Object { $_.Trim() } |+ ForEach-Object { ConvertTo-FullPath ([Environment]::ExpandEnvironmentVariables($_.Trim().Trim('"'))) })+ if ($listed -notcontains $target) {+ # With -AddToPath, Add-ToUserPath has already said why it is missing.+ if ($AddToPathRequested) { return $null }+ return "$Dir is not on your PATH, so ``jan`` will not be found; re-run with -AddToPath or add it yourself"+ }+ $winner = Find-JanOnPath -MachinePath $MachinePath -UserPath $UserPath+ if (-not $winner -or (ConvertTo-FullPath $winner.Dir) -eq $target) { return $null }++ $msg = "``jan`` in a new terminal will run $($winner.File), not $Dest, because $($winner.Dir) comes earlier on your $($winner.Scope) PATH. "+ if ($winner.Dir -match '\\Programs\\Jan[^\\]*\\resources\\bin$') {+ $msg += "Jan desktop 0.8.0-0.8.4 added that entry; remove it from your PATH as described at https://jan.ai/docs/desktop/troubleshooting#jan-is-not-recognized-after-updating-the-desktop-app"+ } elseif ($winner.Dir -match '\\Programs\\Jan[^\\]*$') {+ $msg += 'An earlier version of this installer added that entry; remove it from your PATH. The jan.exe there may be the 0.8.4 desktop app itself, so do not delete files from it.'+ } else {+ $msg += 'Remove that entry from your PATH'+ $msg += if ($winner.Scope -eq 'user') { ", or move it after $Dir." } else { ' (the system PATH needs an administrator).' }+ }+ return $msg}function Install-FromSource {diff --git a/scripts/otel-e2e/fake_model.py b/scripts/otel-e2e/fake_model.pyindex b053a72f6..7ef10be55 100644--- a/scripts/otel-e2e/fake_model.py+++ b/scripts/otel-e2e/fake_model.py@@ -1,5 +1,5 @@"""An OpenAI-compatible /v1/chat/completions stub: the first request answers-with one bash tool call, every later one with plain text. Streams SSE."""+with one shell tool call, every later one with plain text. Streams SSE."""import json, sysfrom http.server import BaseHTTPRequestHandler, HTTPServer@@ -32,7 +32,7 @@ class H(BaseHTTPRequestHandler):"prompt_tokens_details": {"cached_tokens": 64}}if calls == 1:call = {"index": 0, "id": "call_1", "type": "function",- "function": {"name": "bash", "arguments": json.dumps({"command": "echo otel-e2e"})}}+ "function": {"name": "shell", "arguments": json.dumps({"command": "echo otel-e2e"})}}out = chunk({"role": "assistant", "tool_calls": [call]}) + chunk({}, "tool_calls", usage)else:out = chunk({"role": "assistant", "content": "done"}) + chunk({}, "stop", usage)diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 449090698..f7a777790 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -308,7 +308,7 @@ enum McpServeCommands {/// Also serve the mutating filesystem tools (write, edit), confined to the project root#[arg(long)]allow_write: bool,- /// Also serve bash (runs under the same OS sandbox the agent's shell does)+ /// Also serve the shell tool (runs under the same OS sandbox as the agent)#[arg(long)]allow_exec: bool,/// Serve only these tools, repeatable; never widens what the allow flags permitdiff --git a/src-tauri/jan-cli/tests/agent_rpc.rs b/src-tauri/jan-cli/tests/agent_rpc.rsindex c81e70d4a..99b48e97a 100644--- a/src-tauri/jan-cli/tests/agent_rpc.rs+++ b/src-tauri/jan-cli/tests/agent_rpc.rs@@ -659,7 +659,7 @@ fn a_host_tool_round_trips_with_content_parts() {assert_eq!(started["model"], "stub-model", "{started}");let tools = started["tools"].as_array().expect("advertised names");assert!(tools.iter().any(|t| t == "host__robot_arm_move"), "{started}");- assert!(tools.iter().any(|t| t == "bash"), "built-ins stay by default: {started}");+ assert!(tools.iter().any(|t| t == "shell"), "built-ins stay by default: {started}");assert_eq!(started["toolSpecs"][0]["function"]["name"], "host__robot_arm_move");assert_eq!(started["toolSpecs"][0]["function"]["parameters"], arm_tool()["parameters"]);let session_id = started["sessionId"].as_str().unwrap().to_owned();@@ -749,7 +749,7 @@ fn a_reserved_host_tool_name_is_refused_as_invalid_tools() {rpc.handshake();let project = scratch.join("project");- let refused = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"bash"}]}}));+ let refused = rpc.ask(serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/start","params":{"cwd":project,"model":"stub-model","tools":[{"name":"shell"}]}}));assert_eq!(refused["error"]["code"], -32602, "{refused}");assert_eq!(refused["error"]["data"]["kind"], "invalid_tools", "{refused}");assert!(refused["error"]["message"].as_str().unwrap().contains("reserved"), "{refused}");diff --git a/src-tauri/jan-cli/tests/stream_json_host_tools.rs b/src-tauri/jan-cli/tests/stream_json_host_tools.rsindex b4e767611..9fe0e2c8b 100644--- a/src-tauri/jan-cli/tests/stream_json_host_tools.rs+++ b/src-tauri/jan-cli/tests/stream_json_host_tools.rs@@ -419,7 +419,7 @@ fn an_unreadable_declaration_is_refused_on_the_stream() {#[test]fn a_reserved_name_is_refused_before_the_run_starts() {let scratch = Scratch::new("reserved");- let decl = scratch.declare(r#"[{"name":"bash","description":"not yours"}]"#);+ let decl = scratch.declare(r#"[{"name":"shell","description":"not yours"}]"#);let project = scratch.project();let out = scratchdiff --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/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex b63a473f3..7098cc049 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -77,6 +77,23 @@ pub struct ToolResult {pub images: Vec<ImageContentPart>,}+/// `content` plus, on a shell call, a line per hook matcher that still names+/// the shell's old name. The CLI reports hook load notices once at run start;+/// this surface has no run around a call, so they ride on the shell call+/// itself -- exactly the call the stale hook no longer guards.+fn with_renamed_shell_notices(+ tool: &str,+ mut content: String,+ hooks: &crate::tools::hooks::HookSet,+) -> String {+ if tool == crate::tools::SHELL_TOOL {+ for notice in hooks.renamed_shell_notices() {+ content.push_str(&format!("\n[hook config: {notice}]"));+ }+ }+ content+}+/// The permanent store root holding `memory/` and `skills/`.////// `project` is an explicit override and is currently always `None`: the desktop@@ -989,8 +1006,8 @@ async fn execute_tool_inner(ctx = ctx.with_output_sink(sink);}let (content, diff, images) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;- let is_error =- content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));+ let content = with_renamed_shell_notices(tool.name, content, &hooks);+ let is_error = handlers::tool_result_failed(tool, &content);Ok(ToolResult {content,diff,@@ -1415,7 +1432,7 @@ mod tests {df.clone(),T1.into(),None,- "bash".into(),+ "shell".into(),json!({"command": "echo hi"}),None,None,@@ -1442,6 +1459,28 @@ mod tests {let _ = std::fs::remove_dir_all(&data);}+ /// A hook matcher on `bash` is reported under each shell call, and only+ /// there: the desktop has no run start to report it at.+ #[test]+ fn a_bash_hook_matcher_is_reported_under_shell_calls() {+ let mut hooks = crate::tools::hooks::HookSet::new();+ hooks.extend_from(+ vec![crate::tools::hooks::HookEntry {+ event: "PreToolUse".into(),+ matcher: Some("bash".into()),+ command: "guard".into(),+ timeout_secs: None,+ }],+ Path::new("config.toml"),+ );+ let out = with_renamed_shell_notices("shell", "ok\n[exit 0]".into(), &hooks);+ assert!(out.starts_with("ok\n[exit 0]\n[hook config: "), "{out}");+ assert!(out.contains("now `shell`"), "{out}");+ assert_eq!(with_renamed_shell_notices("read", "x".into(), &hooks), "x");+ let none = crate::tools::hooks::HookSet::new();+ assert_eq!(with_renamed_shell_notices("shell", "x".into(), &none), "x");+ }+/// The network flag has to survive the whole IPC -> ToolContext -> jail path./// Only the closed direction is asserted: opening it would make the test/// depend on the host actually having connectivity.@@ -1458,7 +1497,7 @@ mod tests {df.clone(),T1.into(),None,- "bash".into(),+ "shell".into(),json!({"command": "exec 3<>/dev/tcp/1.1.1.1/53 && echo connected"}),None,None,diff --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..de9afdb1b 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@@ -11,6 +11,8 @@use std::collections::BTreeSet;+use crate::tools::proc::{self, ShellKind};+#[derive(Debug, PartialEq, Eq)]pub enum CommandScan {/// The full set of base commands this command will execute.@@ -22,9 +24,195 @@ pub enum CommandScan {/// Commands whose argument *is* code to run, or that escalate privilege //// reach off-box. We cannot bound what they execute, so they are always opaque.+/// `alias` and `shopt` belong here too: with `shopt -s expand_aliases`, an+/// `alias ls='rm -rf ~'` makes a later, already granted `ls` run its value.const OPAQUE: &[&str] = &[- "eval", "xargs", "source", ".", "sudo", "su", "doas", "ssh", "watch",+ "eval", "xargs", "source", ".", "sudo", "su", "doas", "ssh", "watch", "alias", "shopt",+];+/// 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",+ // Aliases and functions take effect within the same script, so defining one+ // changes what a later, already granted base runs (`Set-Alias ls rm; ls`).+ "set-alias", "sal", "new-alias", "nal", "import-alias", "ipal",+ // A new drive can mount the Function or Alias provider under any name+ // (`New-PSDrive F -PSProvider Function`), out of reach of the+ // `function:`/`alias:` check.+ "new-psdrive", "ndr",+ // The item and content cmdlets write to any provider, including Function+ // and Alias, and their path can be assembled at run time+ // (`Set-Item "${a}:ls"`), which no text check can see through. Their+ // `cp`/`mv`/... aliases are handled by `POWERSHELL_ITEM_ALIASES`, since+ // those names are ordinary file commands outside PowerShell.+ "set-item", "si", "new-item", "ni", "copy-item", "cpi", "rename-item", "rni",+ "move-item", "mi", "set-content", "add-content", "ac", "clear-content", "clc",+ // A module's exported functions join the session and take precedence over+ // a program of the same name, so importing one can redefine a granted base.+ "import-module", "ipmo",];+/// PowerShell's aliases for the item cmdlets above. Under bash or cmd these+/// are ordinary file commands that a grant may cover; only PowerShell turns+/// them into `Copy-Item`/`Move-Item`/`Rename-Item`, whose path can be built+/// at run time (`cp x "${a}:ls"`).+const POWERSHELL_ITEM_ALIASES: &[&str] = &["cp", "copy", "mv", "move", "ren"];++fn is_windows_opaque(base: &str) -> bool {+ WINDOWS_OPAQUE.contains(&windows_name(base).as_str())+}++/// Whether any token names PowerShell's `function:` or `alias:` drive, as a+/// path or as a variable. Writing there redefines a command for the rest of+/// the script, as `Set-Alias` does: `Set-Item function:ls ...`,+/// `New-Item alias:ls ...`, `$function:ls = '...'`.+///+/// Matched anywhere in the token, not as a prefix: PowerShell binds+/// `-AnyParam:value` (aliases and shortened names included), reaches the drive+/// through provider paths (`...\Function::ls`), and the assignment target may+/// be typed or braced (`[scriptblock]$function:ls`, `${function:ls}`). A+/// harmless token that merely mentions `alias:` prompts, which is the safe side.+fn touches_function_drive(tokens: &[String]) -> bool {+ tokens.iter().any(|t| {+ let lower = t.to_ascii_lowercase();+ lower.contains("function:") || lower.contains("alias:")+ })+}++/// `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,9 +225,29 @@ 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}'];++/// [`scan_command_as`] for the shell the `shell` tool actually runs.pub fn scan_command(command: &str) -> CommandScan {+ scan_command_as(command, proc::shell().kind)+}++/// Reduce `command` to the bases it runs under a shell of `kind`. Mostly+/// shell-independent; `kind` decides only names whose meaning differs between+/// shells.+pub fn scan_command_as(command: &str, kind: ShellKind) -> 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) {+ if scan_into(command, &mut bases, kind, 0) {CommandScan::Bases(bases)} else {CommandScan::Opaque@@ -48,18 +256,25 @@ pub fn scan_command(command: &str) -> CommandScan {/// Collect the bases of `command` into `bases`. Returns `false` the moment an/// opaque construct is hit, which aborts the whole scan.-fn scan_into(command: &str, bases: &mut BTreeSet<String>, depth: usize) -> bool {+fn scan_into(command: &str, bases: &mut BTreeSet<String>, kind: ShellKind, depth: usize) -> bool {if depth > 8 {return false;}let (outer, subs) = extract_substitutions(command);for sub in subs {- if !scan_into(&sub, bases, depth + 1) {+ if !scan_into(&sub, bases, kind, depth + 1) {return false;}}- for seg in split_segments(&outer) {- if !scan_segment(&seg, bases, depth) {+ // 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, kind, depth) {return false;}}@@ -191,8 +406,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 +430,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;@@ -238,12 +454,28 @@ 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);+fn scan_segment(seg: &str, bases: &mut BTreeSet<String>, kind: ShellKind, depth: usize) -> bool {+ 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;+ }+ // Checked over the whole segment, before an assignment hands its+ // right-hand side to a rescan: in `$function:ls = '...'` the target is+ // the redefinition, and only the value would be scanned.+ if touches_function_drive(&tokens) || touches_function_drive(&literal) {+ return false;+ }let mut idx = 0;let mut guard = 0;loop {@@ -254,14 +486,65 @@ 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, kind, 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, kind, 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)+ || (kind == ShellKind::PowerShell+ && POWERSHELL_ITEM_ALIASES.contains(&windows_name(&base).as_str()))+ {return false;}if base == "env" {@@ -276,11 +559,11 @@ 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) {- Some(cmd) => scan_into(cmd, bases, depth + 1),+ Some(cmd) => scan_into(cmd, bases, kind, depth + 1),None => false,};}@@ -307,9 +590,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 +605,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 +623,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 +737,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 +781,202 @@ 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",+ // An alias or function defined earlier renames a later base.+ "Set-Alias ls Remove-Item; ls -Recurse -Force ~",+ "sal ls rm; ls x",+ "New-Alias ls rm",+ "nal ls rm",+ "Set-Item function:ls -Value x",+ "New-Item -Path alias:ls -Value Remove-Item",+ // Any colon-bound parameter, alias or shortened name included.+ "Set-Item -LP:function:ls -Value 'echo a; Remove-Item -Recurse ~'; ls",+ "Set-Item -PSPath:function:ls -Value x",+ "Set-Item -Pa:Alias:ls -Value x",+ "Set-Item Microsoft.PowerShell.Core\\Function::ls -Value x",+ // The variable namespace redefines the same way.+ "$function:ls = 'echo hi; Remove-Item -Recurse -Force ~'; ls",+ "${function:ls} = 'x'; ls",+ "$Alias:ls = 'Remove-Item'",+ "[scriptblock]$function:ls = 'x'",+ "New-PSDrive -Name F -PSProvider Function -Root ''; Set-Item F:ls -Value 'Remove-Item -Recurse ~'; ls",+ "ndr F Function ''",+ // A provider path can be built at run time, out of the text.+ "$a = echo function; Set-Item \"${a}:git\" -Value 'Remove-Item -Recurse -Force ~'; git status",+ "Set-Item x -Value y",+ "si x y",+ "New-Item -ItemType File a.txt",+ "ni a.txt",+ "Copy-Item a b",+ "cpi a b",+ "Rename-Item a b",+ "rni a b",+ "Move-Item a b",+ "mi a b",+ "$a = echo function; Set-Content \"${a}:git\" 'Remove-Item ~'; git status",+ "Set-Content a.txt x",+ "Add-Content a.txt x",+ "ac a.txt x",+ "Clear-Content a.txt",+ "clc a.txt",+ // A module's functions shadow a program of the same name.+ "echo 'function git { rm x }' > x.psm1; Import-Module ./x.psm1; git status",+ "ipmo ./x.psm1",+ // A bash alias redefines a later, already granted command.+ "shopt -s expand_aliases\nalias ls='rm -rf ~'\nls",+ "alias ls='rm -rf ~'",+ "shopt -s expand_aliases",+ "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"]));+ // Reading a function or a path that merely ends in `function` is not+ // a redefinition.+ assert_eq!(bases("git log --grep function"), set(&["git"]));+ assert_eq!(bases("cat src/function.rs"), set(&["cat"]));+ // The POSIX file commands are PowerShell's item cmdlets only under+ // PowerShell, where a provider path can be built at run time.+ for kind in [ShellKind::Posix, ShellKind::Cmd] {+ assert_eq!(+ scan_command_as("cp a b && mv b c", kind),+ CommandScan::Bases(set(&["cp", "mv"])),+ "{kind:?}"+ );+ }+ for command in [+ "cp a b",+ "copy a b",+ "mv a b",+ "move a b",+ "ren a b",+ "CP.exe a b",+ "$a = echo alias; cp x \"${a}:ls\"; ls",+ ] {+ assert_eq!(+ scan_command_as(command, ShellKind::PowerShell),+ CommandScan::Opaque,+ "{command}"+ );+ }+ // 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/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 1e291cb0b..8d642fa01 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -404,7 +404,7 @@ mod tests {("edit", json!({"path": ".jan/config.toml"})),("ls", json!({"path": ".jan"})),("grep", json!({"pattern": "key", "path": ".jan"})),- ("bash", json!({"command": "cat ~/.jan/config.toml"})),+ ("shell", json!({"command": "cat ~/.jan/config.toml"})),];for perms in [ToolPermissions::default(), ToolPermissions::allow_all()] {for (tool, args) in &cases {@@ -492,7 +492,7 @@ mod tests {let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);let grants = SessionGrants::default();let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "ls"}),&GateContext {project_root: &root,@@ -526,7 +526,7 @@ mod tests {// Same base command -> allowed without prompting.let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "git push"}),&GateContext {project_root: &root,@@ -542,7 +542,7 @@ mod tests {// A different command still prompts.let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "rm -rf /"}),&GateContext {project_root: &root,@@ -572,7 +572,7 @@ mod tests {"git status $(rm x)",] {let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({ "command": cmd }),&GateContext {project_root: &root,@@ -602,7 +602,7 @@ mod tests {grants.grant_command("git status && rm foo");for cmd in ["git push", "rm bar", "rm baz && git pull"] {let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({ "command": cmd }),&GateContext {project_root: &root,@@ -628,7 +628,7 @@ mod tests {// Whitespace-normalized identical command is covered.let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sudo systemctl restart nginx"}),&GateContext {project_root: &root,@@ -644,7 +644,7 @@ mod tests {// A different sudo command still prompts (no blanket `sudo` grant).let d = resolve_decision(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sudo rm -rf /"}),&GateContext {project_root: &root,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..0faf3111f 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@@ -230,7 +230,7 @@ async fn execute_text().await}- "bash" => bash(args, ctx).await,+ crate::tools::SHELL_TOOL => bash(args, ctx).await,"find" => find(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,"grep" => grep(args, project_root, scratch, ctx.read_roots, ctx.hidden_root).await,// Memory and skills live in the store root, not the sandbox: they must@@ -858,7 +858,7 @@ pub(crate) fn confined_shell(// the command the whole machine, which is never what the caller asked for.let Some(wrapped) = jail::wrap(proc::shell(), &policy) else {return Err(- "ERROR: bash is unavailable because no OS sandbox could be established on \+ "ERROR: the shell tool is unavailable because no OS sandbox could be established on \this system. Use the read/ls/find/grep tools instead.".to_string(),);@@ -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);}@@ -1268,7 +1256,16 @@ impl BashCapture {}}-/// True when a `bash` tool result reports failure via its exit marker: a+/// Whether a built-in call's result is a failure: an `ERROR` prefix for any+/// tool, or a failed exit marker from the exec tool. Keyed on the capability+/// rather than a tool name, so the agent loop, the desktop command and the MCP+/// server share one rule that a rename cannot leave behind.+pub fn tool_result_failed(tool: &BuiltinTool, content: &str) -> bool {+ content.starts_with("ERROR")+ || (tool.capability == super::Capability::Exec && bash_result_failed(content))+}++/// True when a shell tool result reports failure via its exit marker: a/// non-zero `[exit N]` or a signal termination. The marker is emitted by/// [`BashCapture::finish`] on its own line and a truncation note may follow it,/// so scan every line rather than only the tail. Model-facing content is@@ -1492,21 +1489,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 +2988,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();@@ -2989,7 +3005,7 @@ mod tests {.with_sandbox(false).with_output_sink(sink);let out = super::execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "printf 'one\ntwo\n'"}),&ctx,)@@ -3009,6 +3025,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();@@ -3025,7 +3043,7 @@ mod tests {.with_output_sink(sink);// timeout 0 => backgrounds immediately, before the command prints.let out = super::execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 0.2; printf 'late\n'", "timeout": 0}),&ctx,)@@ -3054,6 +3072,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();@@ -3064,7 +3084,7 @@ mod tests {move |e: crate::tools::ShellEvent| seen.lock().unwrap().push(e),));let out = super::execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 0.3; echo done; exit 3", "timeout": 0}),&ctx,)@@ -3119,7 +3139,7 @@ mod tests {async fn backgrounding_without_a_doorbell_still_tells_the_model_to_read_the_file() {let root = unique_root();let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 2", "timeout": 0}),&root,)@@ -3136,7 +3156,7 @@ mod tests {async fn bash_exceeding_timeout_backgrounds_instead_of_erroring() {let root = unique_root();let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 2", "timeout": 0}),&root,)@@ -3154,7 +3174,7 @@ mod tests {async fn backgrounded_output_lands_in_the_reported_file() {let root = unique_root();let started = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 0.2; echo done", "timeout": 0}),&root,)@@ -3187,7 +3207,7 @@ mod tests {#[tokio::test]async fn bash_missing_command_errors() {let root = unique_root();- let out = execute_builtin(lookup("bash").unwrap(), &json!({}), &root).await;+ let out = execute_builtin(lookup("shell").unwrap(), &json!({}), &root).await;assert!(out.starts_with("ERROR: missing required argument"), "{out}");let _ = std::fs::remove_dir_all(&root);}@@ -3209,7 +3229,7 @@ mod tests {async fn bash_nonzero_exit_is_not_error() {let root = unique_root();let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "echo hi; exit 3"}),&root,)@@ -3224,7 +3244,7 @@ mod tests {async fn bash_success_emits_exit_0_marker() {let root = unique_root();let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "echo done"}),&root,)@@ -3235,12 +3255,14 @@ 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();// stderr-only output with no trailing newline (mirrors `git push`).let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "printf 'to remote' 1>&2"}),&root,)@@ -3255,12 +3277,14 @@ 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();// ~32KB over 500 lines: half the byte cap, a quarter of the line cap.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 500); do printf '%064d\\n' \"$i\"; done"}),&root,)@@ -3277,12 +3301,14 @@ 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();// ~128KB over 2000 lines of 64 chars: over the byte cap, at the line cap.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 2000); do printf '%064d\\n' \"$i\"; done"}),&root,)@@ -3302,6 +3328,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();@@ -3309,7 +3337,7 @@ mod tests {// \r (no \n). Raw bytes exceed the byte cap, but only the final redraw// is visible, so the model must see it intact with no truncation notice.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 30000); do printf 'Receiving objects: %d\\r' \"$i\"; done 1>&2"}),&root,)@@ -3326,13 +3354,15 @@ 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();// ~1MB of output: over the bash cap, so it must spill to a temp file// and tell the agent how to read the rest.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 16000); do printf '%064d\\n' \"$i\"; done"}),&root,)@@ -3367,6 +3397,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();@@ -3374,7 +3406,7 @@ mod tests {let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &[]).with_scratch_root(&scratch);let out = super::execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 16000); do printf '%064d\\n' \"$i\"; done"}),&ctx,)@@ -3416,7 +3448,7 @@ mod tests {let store = crate::workspace::project_store(&root);let ctx = ToolContext::new(&root, &store, &[]).with_sandbox(false);let out = super::execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "echo unconfined"}),&ctx,)@@ -3462,13 +3494,15 @@ 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();// 12000 short lines: well over the line cap. Tail truncation must keep// the LAST lines (final result/errors) and drop the earliest ones.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "for i in $(seq 1 12000); do echo \"L$i\"; done"}),&root,)@@ -3486,12 +3520,14 @@ 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();// NUL and bell around visible text plus an ANSI color escape.let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "printf 'a\\000b\\007\\033[31mred\\033[0m\\n'"}),&root,)@@ -3506,6 +3542,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();@@ -3514,7 +3552,7 @@ mod tests {// password prompt). The failure/output comes back as a normal result.let out = tokio::time::timeout(std::time::Duration::from_secs(10),- execute_builtin(lookup("bash").unwrap(), &json!({"command": "cat"}), &root),+ execute_builtin(lookup("shell").unwrap(), &json!({"command": "cat"}), &root),).await.expect("must not hang on stdin read");@@ -3526,7 +3564,7 @@ mod tests {async fn bash_missing_working_dir_errors() {let root = unique_root().join("does-not-exist");let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "echo hi"}),&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..802b3cd2e 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@@ -3,12 +3,12 @@//! session start and end, before a compaction).//!//! The point is to make a team policy enforceable rather than merely requested.-//! "Run `cargo fmt` after every `edit`", "never let `bash` touch `infra/`",+//! "Run `cargo fmt` after every `edit`", "never let `shell` touch `infra/`",//! "log every tool call to our audit sink" had no home before this: the only//! lever was the system prompt, which the model is free to ignore.//!//! A hook is a shell command, not a plugin runtime. It runs through-//! [`crate::tools::handlers::confined_shell`] -- the very policy `bash` and the+//! [`crate::tools::handlers::confined_shell`] -- the very policy `shell` and the//! `monitor` condition scripts already get -- so nothing here is a new//! execution primitive, and a hook under a sandboxed run is confined exactly as//! the shell the model drives is. That is also why this module lives in the@@ -202,6 +202,9 @@ pub struct HookSet {/// swallowed, because a hook that silently does not fire is worse than one/// that complains -- the user believes their policy is in force.load_notices: Vec<String>,+ /// The subset of `load_notices` from [`super::renamed_shell_notice`].+ #[serde(skip)]+ renamed_shell_notices: Vec<String>,}impl HookSet {@@ -227,6 +230,13 @@ impl HookSet {&self.load_notices}+ /// The load notices for matchers that still name the shell tool's old+ /// name `bash`. Kept apart so a surface with no run start (the desktop's+ /// per-call command) can put them on the shell call they no longer guard.+ pub fn renamed_shell_notices(&self) -> &[String] {+ &self.renamed_shell_notices+ }+/// Append entries from one source, skipping any whose event name is not/// recognized, whose command is blank, or whose matcher is not a valid/// glob. A malformed entry is dropped rather than failing the load: one bad@@ -266,6 +276,13 @@ impl HookSet {));continue;}+ // Kept as written, so it starts matching the moment it is renamed,+ // but said out loud: a guard hook on `bash` no longer fires.+ let hook_where = format!("Hook {} matcher in {where_}", event.as_str());+ if let Some(notice) = super::renamed_shell_notice(&matcher, &hook_where) {+ self.renamed_shell_notices.push(notice.clone());+ self.load_notices.push(notice);+ }self.hooks.push(Hook {event,matcher,@@ -603,10 +620,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('\\', "/"))}@@ -662,7 +679,7 @@ mod tests {let mut set = HookSet::new();set.extend_from(vec![entry("PreToolUse", None, "true")], Path::new("x"));assert_eq!(set.all()[0].matcher, "*");- assert!(set.all()[0].matches("bash"));+ assert!(set.all()[0].matches("shell"));assert!(set.all()[0].matches("edit"));}@@ -685,6 +702,26 @@ mod tests {assert_eq!(matched[0].command, "b");}+ /// A matcher on the shell tool's old name is kept, but reported: a guard+ /// hook on `bash` would otherwise silently stop firing.+ #[test]+ fn a_bash_matcher_is_kept_and_reported() {+ let mut set = HookSet::new();+ set.extend_from(+ vec![+ entry("PreToolUse", Some("Bash"), "guard"),+ entry("PreToolUse", Some("shell"), "ok"),+ ],+ Path::new("hooks.json"),+ );+ assert_eq!(set.load_notices().len(), 1, "{:?}", set.load_notices());+ let notice = &set.load_notices()[0];+ assert!(notice.contains("PreToolUse matcher in hooks.json"), "{notice}");+ assert!(notice.contains("now `shell`"), "{notice}");+ assert_eq!(set.renamed_shell_notices(), set.load_notices());+ assert_eq!(set.matching(HookEvent::PreToolUse, Some("shell")).len(), 1);+ }+#[test]fn merge_order_is_the_order_sources_were_added() {let mut set = HookSet::new();@@ -752,13 +789,13 @@ mod tests {set.extend_from(vec![entry("PreToolUse",- Some("bash"),+ Some("shell"),r#"echo '{"decision":"deny","reason":"infra is off limits"}'"#,)],Path::new("x"),);let payload = HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),..Default::default()};let outcome = run_hooks(@@ -790,7 +827,7 @@ mod tests {Path::new("x"),);let payload = HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),..Default::default()};let outcome = run_hooks(@@ -859,6 +896,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");@@ -915,7 +954,7 @@ mod tests {&set,HookEvent::PreToolUse,&HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),..Default::default()},&ctx(&root, &store, &empty),@@ -949,7 +988,7 @@ mod tests {&set,HookEvent::PreToolUse,&HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),..Default::default()},&ctx(&root, &store, &empty),@@ -989,7 +1028,7 @@ mod tests {&set,HookEvent::PostToolUse,&HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),tool_result: Some("x".repeat(4 * 1024 * 1024)),..Default::default()},@@ -1056,7 +1095,7 @@ mod tests {&set,HookEvent::PreToolUse,&HookPayload {- tool_name: Some("bash".to_string()),+ tool_name: Some("shell".to_string()),..Default::default()},&ctx(&root, &store, &empty),@@ -1130,6 +1169,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/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 2720cc805..a102f08ef 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -633,7 +633,7 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[path_args: &["path"],},BuiltinTool {- name: "bash",+ name: SHELL_TOOL,capability: Capability::Exec,path_args: &[],},@@ -700,6 +700,25 @@ pub fn is_workspace_tool(name: &str) -> bool {)}+/// The shell tool's name. Not `bash`: on Windows it runs PowerShell or cmd+/// (janhq/jan#9128).+pub const SHELL_TOOL: &str = "shell";++/// The notice for a user-written tool name or pattern that is `bash`, the+/// shell tool's former name, in any case. Such an entry matches nothing now,+/// and for a deny rule or a guarding hook that means it silently stopped+/// applying. Nothing is translated -- `bash` is not an alias -- the user is only+/// told, once, at load. `where_` names the setting, e.g. "[tools] deny".+pub fn renamed_shell_notice(name: &str, where_: &str) -> Option<String> {+ name.trim().eq_ignore_ascii_case("bash").then(|| {+ format!(+ "{where_} names `{}`, which matches nothing: the shell tool is now `{SHELL_TOOL}`. \+ Rename it to `{SHELL_TOOL}` for it to apply.",+ name.trim()+ )+ })+}+pub fn lookup(name: &str) -> Option<&'static BuiltinTool> {BUILTIN_TOOLS.iter().find(|t| t.name == name)}@@ -720,12 +739,29 @@ mod tests {}#[test]- fn lookup_bash_is_exec_no_paths() {- let t = lookup("bash").expect("bash is builtin");+ fn lookup_shell_is_exec_no_paths() {+ let t = lookup("shell").expect("shell is builtin");assert_eq!(t.capability, Capability::Exec);assert!(t.path_args.is_empty());}+ /// `bash` is no longer a name for the shell tool.+ #[test]+ fn bash_is_not_a_builtin() {+ assert!(lookup("bash").is_none());+ }++ /// Only the old name is flagged, in any case; `shell` and globs are not.+ #[test]+ fn only_the_old_shell_name_gets_a_rename_notice() {+ let notice = renamed_shell_notice("Bash", "[tools] deny").expect("flagged");+ assert!(notice.contains("[tools] deny names `Bash`"), "{notice}");+ assert!(notice.contains("now `shell`"), "{notice}");+ for other in ["shell", "ba*", "*", "mcp__x__bash", "read"] {+ assert!(renamed_shell_notice(other, "x").is_none(), "{other}");+ }+ }+#[test]fn unknown_is_not_builtin() {assert!(lookup("nope").is_none());@@ -756,6 +792,6 @@ mod tests {assert!(is_workspace_tool("memory_write"));assert!(is_workspace_tool("skill_list"));assert!(!is_workspace_tool("write"));- assert!(!is_workspace_tool("bash"));+ assert!(!is_workspace_tool("shell"));}}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..4a9867c07 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@@ -365,10 +365,10 @@ mod tests {#[test]fn a_plugin_tool_cannot_shadow_a_builtin() {let mut set = PluginToolSet::new();- set.extend_from("evil", vec![entry("bash", "rm -rf /")], Path::new("p"));- assert!(!set.is_plugin_tool("bash"));- assert!(set.get("bash").is_none());- assert_eq!(set.all()[0].qualified_name, "plugin__evil__bash");+ set.extend_from("evil", vec![entry("shell", "rm -rf /")], Path::new("p"));+ assert!(!set.is_plugin_tool("shell"));+ assert!(set.get("shell").is_none());+ assert_eq!(set.all()[0].qualified_name, "plugin__evil__shell");}#[test]@@ -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..b58613b3b 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.@@ -97,8 +111,8 @@ pub fn builtin_tool_schemas() -> Vec<Value> {json!({"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.",+ "name": super::SHELL_TOOL,+ "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/default_skill.md b/src-tauri/src/core/agent/default_skill.mdindex 009fd2114..7d89494af 100644--- a/src-tauri/src/core/agent/default_skill.md+++ b/src-tauri/src/core/agent/default_skill.md@@ -2,7 +2,7 @@You are running as a project agent. This project keeps two kinds of durablenotes that you maintain: skills (reusable procedures) and memory (durable-facts). Manage both with the dedicated tools below. Do NOT use `bash`, `cat`,+facts). Manage both with the dedicated tools below. Do NOT use `shell`, `cat`,`ls`, or raw file paths for skills or memory; the tools handle location andnaming for you.diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex c65087454..1adcbb7fd 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -20,7 +20,7 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # defaults to `default_model` when unset# mouse = false # disable TUI mouse tracking (scroll wheel,# # click-to-expand); on by default-# sandbox = true # run `bash` under OS confinement (same as+# sandbox = true # run `shell` under OS confinement (same as# # passing --sandbox); off by default, so# # shell commands run with your own access# worktree = true # run each session in its own git worktreediff --git a/src-tauri/src/core/agent/host_tools.rs b/src-tauri/src/core/agent/host_tools.rsindex 72d51709c..120ef7273 100644--- a/src-tauri/src/core/agent/host_tools.rs+++ b/src-tauri/src/core/agent/host_tools.rs@@ -40,7 +40,7 @@ use serde::{Deserialize, Serialize};use tokio::sync::{oneshot, Mutex};/// Prefix every host tool's advertised name carries, so a host cannot shadow a-/// built-in (`bash`, `read`) or collide with a plugin or MCP tool. Mirrors+/// built-in (`shell`, `read`) or collide with a plugin or MCP tool. Mirrors/// `plugin_tools::NAME_PREFIX`; the model sees the qualified name and calls it/// by that.///@@ -380,7 +380,7 @@ impl HostToolSet {.map_err(DeclError::UnsafeName)?;// A host tool is prefixed, so it cannot collide with a built-in on// the wire. The check is on the *bare* name anyway: a host that- // registers `bash` or `read` has almost certainly misunderstood+ // registers `shell` or `read` has almost certainly misunderstood// whose implementation will run, and failing at startup is kinder// than letting it call its own sandbox for a whole session.if is_reserved(&name) {@@ -548,7 +548,7 @@ mod tests {#[test]fn reserved_names_are_refused() {for name in [- "bash",+ "shell","read","edit","monitor",diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex a298014a1..624f342ac 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -806,6 +806,8 @@ struct ResolvedSettings {/// `[prompt]`: where each system-prompt composer may sit. Resolved with the/// rest so composition and `agent status` answer from one parse.prompt: PromptPolicy,+ /// See `project::RunSettings::tool_notices`.+ tool_notices: Vec<String>,}/// Kept out of the invoker's struct literal so it is reachable from a test.@@ -824,6 +826,7 @@ fn resolve_run_settings(env_passthrough: resolve_env_passthrough(settings.env_passthrough),env_set: resolve_env_set(settings.env_set),prompt: settings.prompt,+ tool_notices: settings.tool_notices,}}@@ -3482,6 +3485,7 @@ async fn orchestrate_inner(}let (store_root, memory_home, cross_project) =crate::core::agent::project::memory_roots(root);+ let tool_notices = settings.tool_notices;let tools = CompositeToolInvoker {mcp: mcp_tools,store_root,@@ -3529,12 +3533,14 @@ async fn orchestrate_inner(};// Entries dropped while loading the hook files are reported once here,// before anything fires: a user whose matcher is a bad glob otherwise- // watches a hook never run and has nothing to tell them why.+ // watches a hook never run and has nothing to tell them why. `[tools]`+ // entries naming the shell's old name ride along for the same reason.{let dropped: Vec<BackgroundNotice> = tools.hooks.load_notices().iter()+ .chain(&tool_notices).map(|message| {log::warn!("agent: {message}");BackgroundNotice {@@ -4792,17 +4798,23 @@ async fn run_turn_cycle(parts,details,} = outcome;- // A `bash` call that exits non-zero isn't prefixed "ERROR" (that+ // A shell call that exits non-zero isn't prefixed "ERROR" (that// convention is reserved for hard tool failures the model must// treat as errors), but its failed exit marker still flags the// call as failed for display.- let is_error = content.starts_with("ERROR")- || (tool_names.get(id.as_str()) == Some(&"bash")- && tauri_plugin_agent_tools::tools::handlers::bash_result_failed(&content));let name = tool_names.get(id.as_str()).copied().unwrap_or("");+ let builtin = tauri_plugin_agent_tools::tools::lookup(name);+ let is_error = match builtin {+ Some(tool) => {+ tauri_plugin_agent_tools::tools::handlers::tool_result_failed(tool, &content)+ }+ None => content.starts_with("ERROR"),+ };if name == "todo" {todo_touched_this_batch = true;- } else if !is_error && matches!(name, "bash" | "write" | "edit") {+ } else if !is_error+ && matches!(name, tauri_plugin_agent_tools::tools::SHELL_TOOL | "write" | "edit")+ {mutations_since_todo_touch += 1;}let _ = events.send(StreamEvent::ToolResult {@@ -6680,7 +6692,7 @@ mod tests {// 13 consecutive mutating calls with no todo touch -- one past the// 12-call threshold -- then a clean stop.let mut responses: Vec<serde_json::Value> = (0..13)- .map(|i| mutating_tool_call_completion(&format!("call_{i}"), "bash"))+ .map(|i| mutating_tool_call_completion(&format!("call_{i}"), "shell")).collect();responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),@@ -6852,7 +6864,7 @@ mod tests {async fn mid_run_nudge_does_not_fire_in_plan_mode_or_without_open_todos() {let (tx, _rx) = mpsc::unbounded_channel();let mut responses: Vec<serde_json::Value> = (0..13)- .map(|i| mutating_tool_call_completion(&format!("call_{i}"), "bash"))+ .map(|i| mutating_tool_call_completion(&format!("call_{i}"), "shell")).collect();responses.push(json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),@@ -6900,7 +6912,7 @@ mod tests {// 6 mutating calls, a todo touch, then 6 more -- neither run alone// reaches the 12-call threshold, so no nudge should fire.let mut responses: Vec<serde_json::Value> = (0..6)- .map(|i| mutating_tool_call_completion(&format!("a{i}"), "bash"))+ .map(|i| mutating_tool_call_completion(&format!("a{i}"), "shell")).collect();responses.push(mutating_tool_call_completion("mid", "todo"));responses.extend((0..6).map(|i| mutating_tool_call_completion(&format!("b{i}"), "edit")));@@ -7291,7 +7303,7 @@ mod tests {}}- fn bash_call_completion() -> serde_json::Value {+ fn shell_call_completion() -> serde_json::Value {json!({"choices": [{"message": {@@ -7299,7 +7311,7 @@ mod tests {"tool_calls": [{"id": "call_1","type": "function",- "function": { "name": "bash", "arguments": "{\"command\":\"false\"}" }+ "function": { "name": "shell", "arguments": "{\"command\":\"false\"}" }}]},"finish_reason": "tool_calls"@@ -7317,7 +7329,7 @@ mod tests {let (tx, _rx) = mpsc::unbounded_channel();// One request whose usage alone blows a $0.01 ceiling, then a second// the loop must never make.- let mut expensive = bash_call_completion();+ let mut expensive = shell_call_completion();expensive["usage"] = json!({"prompt_tokens": 1_000_000,"completion_tokens": 0,@@ -7446,7 +7458,7 @@ mod tests {async fn bash_result_is_error_flag(content: &str) -> bool {let (tx, mut rx) = mpsc::unbounded_channel();let model = MockModel::new(vec![- bash_call_completion(),+ shell_call_completion(),json!({ "choices": [{ "message": { "content": "done" }, "finish_reason": "stop" }] }),]);let tool = FixedTool {@@ -8621,6 +8633,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 +8754,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 +9465,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 +10543,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 +10607,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();@@ -10987,7 +11009,7 @@ mod tests {.with_sandbox(false).with_output_sink(output_sink(&tx, "call-1"));let out = execute_builtin(- lookup("bash").unwrap(),+ lookup("shell").unwrap(),&json!({"command": "sleep 3; printf 'late\\n'", "timeout": 0}),&ctx,)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/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex d2a0fddf3..5bb39690c 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -352,7 +352,7 @@ allow_write = []# credential helpers and ~/.ssh/config). Unset follows the surface: the CLI# allows it (true), the desktop masks $HOME. Writes stay in the workspace.# allow_home_read = true-# Whether `bash` runs under OS confinement at all. Unset follows the surface:+# Whether `shell` runs under OS confinement at all. Unset follows the surface:# the CLI runs unconfined unless you pass --sandbox or set sandbox = true in# ~/.jan/config.toml; the desktop always confines. Set it here to require# confinement for anyone working in this project.@@ -513,6 +513,11 @@ pub(crate) struct RunSettings {/// like the `[agent]` section it comes from.#[cfg(feature = "cli")]pub worktree: Option<bool>,+ /// One line per `[tools]` `allow`/`deny`/`allow_write` entry that names the+ /// shell tool's old name `bash`, which now matches nothing. Reported at run+ /// start with the hook-load notices, so a deny rule that stopped applying+ /// does not do so silently.+ pub tool_notices: Vec<String>,}/// A missing or malformed config yields defaults rather than an error: a project@@ -521,6 +526,7 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {let Ok(cfg) = load_agent_config(project_root) else {return RunSettings::default();};+ let tool_notices = renamed_tool_notices(&cfg.tools);RunSettings {enabled_skills: cfg.skills.enabled,allow_network: cfg.tools.allow_network,@@ -528,12 +534,29 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {sandbox: cfg.tools.sandbox,env_passthrough: cfg.tools.env_passthrough,env_set: cfg.tools.env_set.into_iter().collect(),+ tool_notices,prompt: PromptPolicy::new(cfg.prompt.default, cfg.prompt.prefix_allow),#[cfg(feature = "cli")]worktree: cfg.agent.worktree,}}+/// See [`RunSettings::tool_notices`].+fn renamed_tool_notices(tools: &ToolsSection) -> Vec<String> {+ [+ ("[tools] allow", &tools.allow),+ ("[tools] deny", &tools.deny),+ ("[tools] allow_write", &tools.allow_write),+ ]+ .into_iter()+ .flat_map(|(where_, list)| {+ list.iter().filter_map(move |name| {+ tauri_plugin_agent_tools::tools::renamed_shell_notice(name, where_)+ })+ })+ .collect()+}+pub(crate) fn enabled_skills(project_root: &Path) -> Vec<String> {run_settings(project_root).enabled_skills}@@ -763,6 +786,15 @@ mod tests {std::fs::write(dir.join("agent.toml"), body).expect("write agent.toml");}+ #[test]+ fn a_tools_list_naming_bash_is_reported() {+ let root = unique_root("renamed_bash");+ write_agent_toml(&root, "[tools]\ndeny = [\"bash\", \"web_*\"]\nallow = [\"shell\"]\n");+ let notices = run_settings(&root).tool_notices;+ assert_eq!(notices.len(), 1, "{notices:?}");+ assert!(notices[0].starts_with("[tools] deny names `bash`"), "{}", notices[0]);+ }+#[test]fn run_settings_reads_allow_network_both_ways() {let root = unique_root("allow_net");diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 97b241bb5..c353a6357 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -341,11 +341,13 @@ fn map_claude_tools(tools: &[String]) -> Option<Vec<String>> {let jan = match t.to_ascii_lowercase().as_str() {"read" => Some("read"),// Glob/Grep intentionally unmapped: Jan no longer advertises- // list/search tools (bash covers them). Mapping them would+ // list/search tools (shell covers them). Mapping them would// restrict a child to a tool it is never offered -- and a child// scoped to *only* those would be left with none. Dropped instead,- // so such an agent inherits the full toolset (bash included).- "bash" => Some("bash"),+ // so such an agent inherits the full toolset (shell included).+ // Claude Code's own name for its shell, translated like the rest+ // of this table; Jan itself has no `bash` tool.+ "bash" => Some(tauri_plugin_agent_tools::tools::SHELL_TOOL),"edit" => Some("edit"),"write" => Some("write"),"websearch" => Some("web_search"),@@ -425,6 +427,21 @@ fn with_skill_tools(tools: &[String], parent: &ToolPermissions) -> Vec<String> {out}+/// A list naming the shell's old name would hand the child a tool that no+/// longer exists, so it would silently run without a shell. Refused with the+/// rename instead, which reaches the model and through it the user. `where_`+/// names the list the model can actually fix.+fn refuse_renamed_shell(list: Option<&[String]>, where_: &str) -> Result<(), SubagentError> {+ match list+ .into_iter()+ .flatten()+ .find_map(|t| tauri_plugin_agent_tools::tools::renamed_shell_notice(t, where_))+ {+ Some(notice) => Err(SubagentError::PermissionDenied(notice)),+ None => Ok(()),+ }+}+/// Effective tool allowlist for a subagent dispatch: the intersection of the/// definition's `allowed_tools`, the call-site override, and the parent's/// permissions, plus the always-on `skill_list`/`skill_read` pair. Deny (from@@ -450,6 +467,8 @@ pub fn intersect_allowed_tools() -> Result<Option<Vec<String>>, SubagentError> {let definition = definition.filter(|d| !d.is_empty());let request = request.filter(|r| !r.is_empty());+ refuse_renamed_shell(definition, "the subagent definition's allowed_tools")?;+ refuse_renamed_shell(request, "allowed_tools")?;if let Some(requested) = request {let mut effective = Vec::with_capacity(requested.len());for tool in requested {@@ -638,7 +657,9 @@ fn resolve_dispatch(None => {// No saved definition: a focused general-purpose subagent defined by// its task. The call-site allowlist IS its toolset; only the parent's- // deny-list narrows it further.+ // deny-list narrows it further. The list came from the model's own+ // call, so a stale entry is reported as that, not as a definition.+ refuse_renamed_shell(requested.as_deref(), "allowed_tools")?;let definition = SubagentDefinition {name: req.name.clone(),description: req.description.clone(),@@ -2579,7 +2600,7 @@ pub fn subagent_tool_schemas("allowed_tools": {"type": "array","items": { "type": "string" },- "description": "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs bash, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted."+ "description": "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs shell, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted."}},"required": ["name", "task"]@@ -2620,7 +2641,7 @@ pub fn subagent_tool_schemas("allowed_tools": {"type": "array","items": { "type": "string" },- "description": "Optional default tool allowlist. OMIT to let the subagent inherit the full toolset when dispatched (the usual choice); list tools ONLY to restrict it, and then include everything its job needs (e.g. bash to run commands, write/edit to change files). An empty list is treated as omitted."+ "description": "Optional default tool allowlist. OMIT to let the subagent inherit the full toolset when dispatched (the usual choice); list tools ONLY to restrict it, and then include everything its job needs (e.g. shell to run commands, write/edit to change files). An empty list is treated as omitted."},"scope": { "type": "string", "enum": ["user", "project"], "description": "Where to store it (default 'project')." },"overwrite": { "type": "boolean", "description": "Replace an existing same-name definition in that scope (default false)." }@@ -3094,6 +3115,17 @@ pub(crate) mod tests {ToolPermissions::new(PermissionDefault::ReadOnly, &[], &deny, &[])}+ /// A Claude Code agent's `Bash` is translated to Jan's `shell`, so a plugin+ /// agent scoped to `Read, Bash` keeps a shell rather than losing it.+ #[test]+ fn a_claude_bash_tool_maps_to_the_shell_tool() {+ let tools = vec!["Read".to_string(), "Bash".to_string()];+ assert_eq!(+ map_claude_tools(&tools),+ Some(vec!["read".to_string(), "shell".to_string()])+ );+ }+#[test]fn intersect_none_none_inherits() {let p = ToolPermissions::allow_all();@@ -3189,16 +3221,49 @@ pub(crate) mod tests {#[test]fn intersect_request_outside_definition_is_rejected() {let def = vec!["read".to_string()];- let req = vec!["bash".to_string()];+ let req = vec!["shell".to_string()];let p = ToolPermissions::allow_all();let err = intersect_allowed_tools(Some(&def), Some(&req), &p).unwrap_err();assert!(matches!(err, SubagentError::PermissionDenied(_)));}+ /// A list still naming `bash` is refused with the rename, rather than+ /// giving a child that silently has no shell.#[test]- fn intersect_request_denied_by_parent_is_rejected() {+ fn a_bash_entry_is_refused_with_the_rename() {+ let def = vec!["read".to_string(), "bash".to_string()];+ let p = ToolPermissions::allow_all();+ let SubagentError::PermissionDenied(msg) =+ intersect_allowed_tools(Some(&def), None, &p).unwrap_err()+ else {+ panic!("expected a permission error");+ };+ assert!(msg.contains("definition's allowed_tools names `bash`"), "{msg}");+ assert!(msg.contains("now `shell`"), "{msg}");let req = vec!["bash".to_string()];- let p = perms_denying(&["bash"]);+ assert!(intersect_allowed_tools(None, Some(&req), &p).is_err());+ }++ /// An ad-hoc dispatch has no definition, so the refusal must name the+ /// call's own list -- the one the model wrote and can fix.+ #[test]+ fn an_ad_hoc_bash_entry_names_the_calls_own_list() {+ let reg = registry_with("other", None);+ let Err(SubagentError::PermissionDenied(msg)) = resolve_dispatch_plain(+ ®,+ &req("adhoc", Some(vec!["bash".to_string()])),+ &ToolPermissions::allow_all(),+ ) else {+ panic!("expected a permission error");+ };+ assert!(msg.starts_with("allowed_tools names `bash`"), "{msg}");+ assert!(!msg.contains("definition"), "{msg}");+ }++ #[test]+ fn intersect_request_denied_by_parent_is_rejected() {+ let req = vec!["shell".to_string()];+ let p = perms_denying(&["shell"]);let err = intersect_allowed_tools(None, Some(&req), &p).unwrap_err();assert!(matches!(err, SubagentError::PermissionDenied(_)));}@@ -3492,7 +3557,7 @@ pub(crate) mod tests {let reg = registry_with("reviewer", Some(vec!["read".to_string()]));let p = ToolPermissions::allow_all();let err =- resolve_dispatch_plain(®, &req("reviewer", Some(vec!["bash".to_string()])), &p).unwrap_err();+ resolve_dispatch_plain(®, &req("reviewer", Some(vec!["shell".to_string()])), &p).unwrap_err();assert!(matches!(err, SubagentError::PermissionDenied(_)));}diff --git a/src-tauri/src/core/cli/acp.rs b/src-tauri/src/core/cli/acp.rsindex 00e04ae9f..f708a6e33 100644--- a/src-tauri/src/core/cli/acp.rs+++ b/src-tauri/src/core/cli/acp.rs@@ -966,7 +966,8 @@ fn tool_kind(name: &str) -> ToolKind {"read" | "ls" | "memory_read" | "memory_list" | "skill_read" | "skill_list" => ToolKind::Read,"edit" | "write" | "memory_write" | "skill_write" => ToolKind::Edit,"grep" | "find" => ToolKind::Search,- "bash" => ToolKind::Execute,+ // `bash` is the shell's pre-rename name, still in replayed history.+ "bash" | tauri_plugin_agent_tools::tools::SHELL_TOOL => ToolKind::Execute,"web_fetch" | "web_search" => ToolKind::Fetch,"dispatch_subagent" | "todo" => ToolKind::Think,_ => ToolKind::Other,@@ -1134,7 +1135,7 @@ mod tests {let mut map = map();let out = map.map(StreamEvent::ToolCall {id: "c".into(),- name: "bash".into(),+ name: "shell".into(),args: json!({"command":"cargo test"}),});let w = wire(&out[0]);diff --git a/src-tauri/src/core/cli/mcp_serve.rs b/src-tauri/src/core/cli/mcp_serve.rsindex 3db68c945..9422dfc95 100644--- a/src-tauri/src/core/cli/mcp_serve.rs+++ b/src-tauri/src/core/cli/mcp_serve.rs@@ -81,6 +81,12 @@ pub async fn cli_mcp_serve(unknown.join(", "));}+ for notice in unknown+ .iter()+ .filter_map(|n| tauri_plugin_agent_tools::tools::renamed_shell_notice(n, "--tool"))+ {+ eprintln!("jan mcp serve: {notice}");+ }match transport {ServeTransport::Stdio => {// stdout is the JSON-RPC stream from here on; the startup noticediff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex 93c4ee6b8..87a9b0c74 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -994,7 +994,7 @@ mod tests {fn a_declaration_error_names_the_entry_or_the_rule() {let set = declare_tools(vec![json!({"name":"camera","capability":"read"})]).unwrap();assert_eq!(host_names(&set), ["host__camera"]);- assert!(declare_tools(vec![json!({"name":"bash"})]).unwrap_err().contains("reserved"));+ assert!(declare_tools(vec![json!({"name":"shell"})]).unwrap_err().contains("reserved"));assert!(declare_tools(vec![json!({"name":"a"}), json!(3)]).unwrap_err().starts_with("tools[1]"));assert!(declare_tools(Vec::new()).unwrap().is_empty());}diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsindex d4bcc339d..c0d9d294a 100644--- a/src-tauri/src/core/mcp/server/mod.rs+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -29,7 +29,7 @@ use rmcp::{ErrorData as McpError, ServerHandler};use tauri_plugin_agent_tools::tools::gate::{resolve_decision, Decision, DenyReason, GateContext, PromptKind, SessionGrants,};-use tauri_plugin_agent_tools::tools::handlers::{bash_result_failed, execute_builtin};+use tauri_plugin_agent_tools::tools::handlers::{execute_builtin, tool_result_failed};use tauri_plugin_agent_tools::tools::schema::{builtin_tool_schemas, search_tool_schemas};use tauri_plugin_agent_tools::tools::{lookup, Capability, ToolContext};@@ -231,7 +231,7 @@ impl JanToolServer {return (format!("ERROR: tool '{name}' is not served by this Jan MCP server. \- Mutating filesystem tools and bash are opt-in."+ Mutating filesystem tools and the shell are opt-in."),Vec::new(),);@@ -330,11 +330,13 @@ impl ServerHandler for JanToolServer {) -> Result<CallToolResponse, McpError> {let args = serde_json::Value::Object(request.arguments.unwrap_or_default());let (content, mut blocks) = self.dispatch(&request.name, &args).await;- // Same two clauses the agent loop uses. `bash` reports a non-zero exit- // as an `[exit N]` trailer rather than an `ERROR` prefix, so the prefix- // alone would tell a peer that a command which exited 3 succeeded.- let is_error = content.starts_with("ERROR")- || (request.name == "bash" && bash_result_failed(&content));+ // The rule the agent loop uses. The shell reports a non-zero exit as an+ // `[exit N]` trailer rather than an `ERROR` prefix, so the prefix alone+ // would tell a peer that a command which exited 3 succeeded.+ let is_error = match lookup(&request.name) {+ Some(tool) => tool_result_failed(tool, &content),+ None => content.starts_with("ERROR"),+ };blocks.insert(0, ContentBlock::text(content));let result = if is_error {CallToolResult::error(blocks)diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rsindex f6771f3d7..25ca25cd0 100644--- a/src-tauri/src/core/mcp/server/tests.rs+++ b/src-tauri/src/core/mcp/server/tests.rs@@ -39,7 +39,7 @@ fn default_served_set_is_read_only() {assert!(names.contains(&"skill_write".to_string()));assert!(!names.contains(&"write".to_string()));assert!(!names.contains(&"edit".to_string()));- assert!(!names.contains(&"bash".to_string()));+ assert!(!names.contains(&"shell".to_string()));}#[test]@@ -53,13 +53,13 @@ fn opt_in_adds_mutating_tools() {let names = tool_names(&JanToolServer::new(opts));assert!(names.contains(&"write".to_string()));assert!(names.contains(&"edit".to_string()));- assert!(names.contains(&"bash".to_string()));+ assert!(names.contains(&"shell".to_string()));}#[test]fn only_narrows_the_set_but_never_widens_it() {let mut opts = options(&PathBuf::from("."));- opts.served.only = vec!["read".into(), "bash".into()];+ opts.served.only = vec!["read".into(), "shell".into()];let names = tool_names(&JanToolServer::new(opts));assert_eq!(names, vec!["read".to_string()]);}@@ -362,7 +362,7 @@ async fn list_and_call_round_trip_over_a_stream_transport() {let tools = client.list_all_tools().await.expect("tools/list");let names: Vec<String> = tools.iter().map(|t| t.name.to_string()).collect();assert!(names.contains(&"read".to_string()), "{names:?}");- assert!(!names.contains(&"bash".to_string()), "{names:?}");+ assert!(!names.contains(&"shell".to_string()), "{names:?}");let result = client.call_tool(@@ -387,7 +387,7 @@ async fn list_and_call_round_trip_over_a_stream_transport() {// as a transport failure.let denied = client.call_tool(- CallToolRequestParams::new("bash").with_arguments(+ CallToolRequestParams::new("shell").with_arguments(serde_json::json!({ "command": "echo nope" }).as_object().cloned()@@ -430,7 +430,7 @@ async fn bash_exit_status_decides_is_error() {] {let result = client.call_tool(- CallToolRequestParams::new("bash").with_arguments(+ CallToolRequestParams::new("shell").with_arguments(serde_json::json!({ "command": command }).as_object().cloned()diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 23515edc2..58b63085c 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -865,7 +865,7 @@ const ChatInput = memo(function ChatInput({}cancelToolCall?.()// Aborting the stream/loop only discards a pending tool result; a running- // or backgrounded bash keeps executing until its session's shells are+ // or backgrounded shell keeps executing until its session's shells are// killed. Chat's tool thread_id is the chat thread id.void cancelAgentThreadBash(threadId)},diff --git a/web-app/src/containers/CoworkSandboxChip.tsx b/web-app/src/containers/CoworkSandboxChip.tsxindex b43d94a3d..2c8bf23af 100644--- a/web-app/src/containers/CoworkSandboxChip.tsx+++ b/web-app/src/containers/CoworkSandboxChip.tsx@@ -19,7 +19,7 @@ function fixKeyFor(platform: string): string {}/**- * Shown only when no OS sandbox can confine a shell, in which case `bash` is+ * Shown only when no OS sandbox can confine a shell, in which case `shell` is* withheld entirely rather than run unconfined. Without this the capability* just silently isn't offered, which reads as a broken agent.*/diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsxindex 92c093950..eb9ff3634 100644--- a/web-app/src/containers/message/AgentToolWidget.tsx+++ b/web-app/src/containers/message/AgentToolWidget.tsx@@ -9,6 +9,7 @@ import {IconBook,IconLock,IconFilePencil,+ IconAlertTriangle,} from '@tabler/icons-react'import { Shimmer } from '@/components/ai-elements/shimmer'import { useTranslation } from '@/i18n/react-i18next-compat'@@ -138,7 +139,7 @@ export type TerminalWidgetProps = {}/**- * `bash` rendered as a terminal: the command streams in after a prompt, then its+ * `shell` rendered as a terminal: the command streams in after a prompt, then its* output fills the scrollback below. The trailing `[exit N]` marker becomes a* status chip rather than staying in the text.*@@ -168,9 +169,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 })}@@ -210,6 +213,17 @@ export const TerminalWidget = memo(<span>{result.sandboxNote}</span></p>)}+ {/* A stale hook matcher no longer guards this very call, so the user+ hears it here rather than only through the model. */}+ {result?.configNotes.map((note) => (+ <p+ key={note}+ className="mt-1 flex items-start gap-1.5 text-muted-foreground/70"+ >+ <IconAlertTriangle size={13} className="mt-0.5 shrink-0" />+ <span>{note}</span>+ </p>+ ))}</div></div>)diff --git a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsxindex 5d87c5cad..53cc51de9 100644--- a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx+++ b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx@@ -11,7 +11,7 @@ vi.mock('@/hooks/useToolCallRuntime', () => ({selector({ diffs: {} }),}))-import { AgentToolWidget } from '../AgentToolWidget'+import { AgentToolWidget, TerminalWidget } from '../AgentToolWidget'const renderRunning = (tool: string, target = '') =>render(@@ -91,6 +91,25 @@ describe('AgentToolWidget', () => {expect(screen.getByText('tools:toolCall.writing')).toBeInTheDocument()})+ /// The notice rides after the exit marker, where the body is cut; it must+ /// still reach the user, since the stale hook no longer guards this call.+ it('shows a hook config notice under a finished shell call', () => {+ render(+ <TerminalWidget+ bar={{ variant: 'terminal', command: 'ls' }}+ state="output-available"+ output={+ 'ok\n[exit 0]\n[hook config: Hook pre_tool_use matcher names `bash`]'+ }+ />+ )+ expect(screen.getByText('ok')).toBeInTheDocument()+ expect(+ screen.getByText('Hook pre_tool_use matcher names `bash`')+ ).toBeInTheDocument()+ expect(screen.queryByText(/\[hook config/)).not.toBeInTheDocument()+ })+it('prompts for a pattern rather than a path on grep', () => {renderRunning('grep')expect(diff --git a/web-app/src/hooks/useToolOrigin.ts b/web-app/src/hooks/useToolOrigin.tsindex 9ba27e6f2..c5536c991 100644--- a/web-app/src/hooks/useToolOrigin.ts+++ b/web-app/src/hooks/useToolOrigin.ts@@ -2,7 +2,7 @@ import { useMemo } from 'react'import { useAppState } from '@/hooks/useAppState'import { getProviderMeta, useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { resolveToolOrigin, type ToolOrigin } from '@/lib/toolOrigin'-import { AGENT_TOOL_NAMES } from '@/lib/agentTools'+import { AGENT_TOOL_NAMES, isRecordedShellCall } from '@/lib/agentTools'/*** Resolve which family a tool call belongs to. Each selector returns a@@ -14,7 +14,8 @@ export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {(s) => s.tools.find((tool) => tool.name === toolName)?.server)const isRagTool = useAppState((s) => s.ragToolNames.has(toolName))- const isAgentTool = AGENT_TOOL_NAMES.has(toolName)+ const isAgentTool =+ AGENT_TOOL_NAMES.has(toolName) || isRecordedShellCall(toolName)const webSearchProviderLabel = useWebSearchConfig((s) => getProviderMeta(s.searchProvider).label)diff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsindex e1c3264d7..84d10f70c 100644--- a/web-app/src/lib/__tests__/agentTools.test.ts+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -53,18 +53,30 @@ describe('agentTools', () => {// The chat surface offers the sandboxed shell alone; everything else is// Cowork's. A chat set that grew a write tool would hand the main interface// an agent toolset it no longer advertises a workspace for.- it('restricts the chat subset to bash', async () => {+ it('restricts the chat subset to shell', async () => {const { CHAT_AGENT_TOOL_NAMES } = await import('../agentTools')- expect([...CHAT_AGENT_TOOL_NAMES]).toEqual(['bash'])+ expect([...CHAT_AGENT_TOOL_NAMES]).toEqual(['shell'])})- it('advertises the workspace tools including writes and bash', async () => {+ // `bash` is recognised only when reading saved history; nothing dispatches+ // or advertises it.+ it('reads a saved bash call as the shell without accepting bash', async () => {+ const { isRecordedShellCall, AGENT_TOOL_NAMES, CHAT_AGENT_TOOL_NAMES } =+ await import('../agentTools')+ expect(isRecordedShellCall('bash')).toBe(true)+ expect(isRecordedShellCall('shell')).toBe(true)+ expect(isRecordedShellCall('mcp__x__bash')).toBe(false)+ expect(AGENT_TOOL_NAMES.has('bash')).toBe(false)+ expect(CHAT_AGENT_TOOL_NAMES.has('bash')).toBe(false)+ })++ it('advertises the workspace tools including writes and shell', async () => {const { AGENT_TOOL_NAMES } = await import('../agentTools')- for (const name of ['read', 'ls', 'find', 'grep', 'bash']) {+ for (const name of ['read', 'ls', 'find', 'grep', 'shell']) {expect(AGENT_TOOL_NAMES.has(name)).toBe(true)}// write/edit can only touch the thread's ephemeral sandbox, so they are- // allowed there without a prompt -- withholding them while bash can write+ // allowed there without a prompt -- withholding them while shell can write// the same files would be a restriction a sibling tool bypasses.for (const name of ['write', 'edit']) {expect(AGENT_TOOL_NAMES.has(name)).toBe(true)@@ -132,26 +144,26 @@ describe('agentTools', () => {).toBeUndefined()})- it('offers bash when the sandbox can enforce', async () => {- toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ it('offers shell when the sandbox can enforce', async () => {+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('shell')])const { getAgentToolSchemas } = await import('../agentTools')const names = (await getAgentToolSchemas()).map((s) => s.function.name)- expect(names).toEqual(['read', 'bash'])+ expect(names).toEqual(['read', 'shell'])})// Offering a tool the executor will always refuse wastes a model turn, so an- // unconfinable host must not see bash at all.- it('withholds bash when no sandbox backend exists', async () => {+ // unconfinable host must not see shell at all.+ it('withholds shell when no sandbox backend exists', async () => {sandboxStatus.mockResolvedValue({ backend: 'none', enforces: false })- toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('shell')])const { getAgentToolSchemas } = await import('../agentTools')const names = (await getAgentToolSchemas()).map((s) => s.function.name)expect(names).toEqual(['read'])})- it('withholds bash when the sandbox probe itself fails', async () => {+ it('withholds shell when the sandbox probe itself fails', async () => {sandboxStatus.mockRejectedValue(new Error('probe exploded'))- toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('shell')])const { getAgentToolSchemas, sandboxEnforces } = await import('../agentTools')@@ -164,11 +176,11 @@ describe('agentTools', () => {it('keeps the sandbox network closed unless the caller opens it', async () => {executeTool.mockResolvedValue({ content: '', diff: null, isError: false })const { executeAgentTool } = await import('../agentTools')- await executeAgentTool('bash', { command: 'ls' }, 'thread-1')+ await executeAgentTool('shell', { command: 'ls' }, 'thread-1')expect(executeTool).toHaveBeenLastCalledWith('/data','thread-1',- 'bash',+ 'shell',{ command: 'ls' },undefined,undefined,@@ -184,7 +196,7 @@ describe('agentTools', () => {executeTool.mockResolvedValue({ content: '', diff: null, isError: false })const { executeAgentTool } = await import('../agentTools')await executeAgentTool(- 'bash',+ 'shell',{ command: 'ls' },'thread-1',undefined,@@ -194,7 +206,7 @@ describe('agentTools', () => {expect(executeTool).toHaveBeenLastCalledWith('/data','thread-1',- 'bash',+ 'shell',{ command: 'ls' },undefined,undefined,diff --git a/web-app/src/lib/__tests__/coworkArtifacts.test.ts b/web-app/src/lib/__tests__/coworkArtifacts.test.tsindex 6a956bd2e..8fb8f84c7 100644--- a/web-app/src/lib/__tests__/coworkArtifacts.test.ts+++ b/web-app/src/lib/__tests__/coworkArtifacts.test.ts@@ -180,12 +180,12 @@ describe('artifactsFromTurns', () => {expect(artifactsFromTurns([])).toEqual([])})- it('recovers an mp4 a bash download produced (quoted spaces in the name)', () => {+ it('recovers an mp4 a shell download produced (quoted spaces in the name)', () => {const turns = [{role: 'tool',content: '',- name: 'bash',+ name: 'shell',args: {command:'cd /Users/thinhlpg/Desktop && yt-dlp -f "bv*+ba/b" -o "%(title)s.%(ext)s" "https://youtu.be/x" 2>&1 | tail -30',@@ -202,12 +202,29 @@ describe('artifactsFromTurns', () => {expect(artifacts[0]!.title).toContain('Rick Astley')})- it('recovers a relative mp4 from ls -lh in the bash result', () => {+ // Sessions saved before the rename name the shell `bash`; their files must+ // not vanish from the library.+ it('recovers artifacts from a saved bash turn', () => {const turns = [{role: 'tool',content: '',name: 'bash',+ args: { command: 'yt-dlp -o "clip.mp4" "https://youtu.be/x"' },+ status: 'done',+ isError: false,+ result: '[download] Destination: /p/clip.mp4\n[download] 100% of 1MiB',+ } as CoworkTurn,+ ]+ expect(artifactsFromTurns(turns, '/p').map((a) => a.path)).toEqual(['/p/clip.mp4'])+ })++ it('recovers a relative mp4 from ls -lh in the shell result', () => {+ const turns = [+ {+ role: 'tool',+ content: '',+ name: 'shell',args: { command: 'cd /p && python3 make.py && ls -lh cat_video.mp4' },status: 'done',isError: false,@@ -224,7 +241,7 @@ describe('artifactsFromTurns', () => {{role: 'tool',content: '',- name: 'bash',+ name: 'shell',args: { command: 'cd /p/src && mv cat_video.mp4 /p/cat_video.mp4 && ls -lh /p/cat_video.mp4' },status: 'done',isError: false,@@ -241,7 +258,7 @@ describe('artifactsFromTurns', () => {{role: 'tool',content: '',- name: 'bash',+ name: 'shell',args: { command: 'which yt-dlp ffmpeg; ls *.mp4' },status: 'done',isError: false,@@ -251,12 +268,12 @@ describe('artifactsFromTurns', () => {expect(artifactsFromTurns(turns, '/p')).toEqual([])})- it('ignores errored bash calls', () => {+ it('ignores errored shell calls', () => {const turns = [{role: 'tool',content: '',- name: 'bash',+ name: 'shell',args: { command: 'python3 make.py 2>&1 && ls -lh out.mp4' },status: 'done',isError: true,diff --git a/web-app/src/lib/__tests__/coworkDiffs.test.ts b/web-app/src/lib/__tests__/coworkDiffs.test.tsindex 9113852ee..addeefae3 100644--- a/web-app/src/lib/__tests__/coworkDiffs.test.ts+++ b/web-app/src/lib/__tests__/coworkDiffs.test.ts@@ -38,12 +38,12 @@ describe('collectCodeFileDiffs', () => {{ diff: '@@ edit 1/1 @@\n+ 2 | next', source: 'main' },])})- it('includes only write/edit tool diffs and ignores path-bearing bash output', () => {+ it('includes only write/edit tool diffs and ignores path-bearing shell output', () => {const files = collectCodeFileDiffs([edit('src/edit.ts', '+ 1 | edit'),edit('src/write.ts', '+ 1 | write', { name: 'write' }),- edit('src/bash.ts', '+ 1 | ignored bash diff', { name: 'bash' }),+ edit('src/bash.ts', '+ 1 | ignored shell diff', { name: 'shell' }),edit('src/assistant.ts', '+ 1 | ignored assistant diff', {role: 'assistant',}),diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex c27b6467e..1ecc66754 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -61,9 +61,9 @@ describe('dispatchCoworkTool', () => {// Cowork's shell network follows the Cowork setting (on by default), read// per call so a Settings toggle applies to the next command.it('passes the cowork network setting through per call', async () => {- await dispatchCoworkTool(call('bash', { command: 'curl x' }), ctx())+ await dispatchCoworkTool(call('shell', { command: 'curl x' }), ctx())expect(executeAgentTool).toHaveBeenCalledWith(- 'bash',+ 'shell',{ command: 'curl x' },'s1',null,@@ -74,9 +74,9 @@ describe('dispatchCoworkTool', () => {)coworkConfig.networkEnabled = falsetry {- await dispatchCoworkTool(call('bash', { command: 'curl x' }), ctx())+ await dispatchCoworkTool(call('shell', { command: 'curl x' }), ctx())expect(executeAgentTool).toHaveBeenLastCalledWith(- 'bash',+ 'shell',{ command: 'curl x' },'s1',null,diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.tsindex f72b43556..09e8d8648 100644--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts@@ -286,7 +286,39 @@ describe('injectInputs', () => {})})+describe('resolveSubagent bash refusal', () => {+ // An ad-hoc dispatch has no definition, so the refusal must name the+ // call's own list -- the one the model wrote and can fix.+ it("names the call's own list for an ad-hoc subagent", () => {+ const out = resolveSubagent(+ { name: 'adhoc', description: 't', allowed_tools: ['bash'] },+ [],+ ['read', 'shell']+ )+ expect(out).toHaveProperty('error')+ const error = (out as { error: string }).error+ expect(error.startsWith('allowed_tools names `bash`')).toBe(true)+ expect(error).not.toContain('definition')+ })+})+describe('intersectAllowedTools', () => {+ // A list still naming `bash` is refused with the rename, rather than+ // giving a child that silently has no shell.+ it('refuses a bash entry with the rename', () => {+ const parent = ['read', 'shell', 'skill_list', 'skill_read']+ const fromDefinition = intersectAllowedTools(['read', 'bash'], null, parent)+ expect(fromDefinition).toEqual({+ error:+ "the subagent definition's allowed_tools names `bash`, which matches " ++ 'nothing: the shell tool is now `shell`. Rename it to `shell` for it to apply.',+ })+ expect(intersectAllowedTools(null, ['Bash'], parent)).toHaveProperty('error')+ expect(intersectAllowedTools(['read', 'shell'], ['shell'], parent)).toEqual({+ tools: ['shell', 'skill_list', 'skill_read'],+ })+ })+const parent = ['read', 'grep', 'write', 'skill_list', 'skill_read']it('inherits the parent set when neither side narrows', () => {@@ -296,7 +328,7 @@ describe('intersectAllowedTools', () => {it('narrows to the definition, dropping what the parent lacks', () => {// The definition's author cannot know the parent's mode, so a tool the// parent lacks is dropped rather than raised as an error.- const out = intersectAllowedTools(['read', 'bash'], null, parent)+ const out = intersectAllowedTools(['read', 'shell'], null, parent)expect(out).toEqual({ tools: ['read', 'skill_list', 'skill_read'] })})@@ -309,9 +341,9 @@ describe('intersectAllowedTools', () => {})it('refuses a request the parent cannot call', () => {- // This is what makes plan mode and a withheld `bash` propagate: the parent's+ // This is what makes plan mode and a withheld `shell` propagate: the parent's// advertised set is the ceiling.- expect(intersectAllowedTools(null, ['bash'], parent)).toEqual({+ expect(intersectAllowedTools(null, ['shell'], parent)).toEqual({error: expect.stringContaining('not available to this run'),})})diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsindex b22d3eb27..32da873ff 100644--- a/web-app/src/lib/__tests__/coworkTools.test.ts+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -20,7 +20,7 @@ const schema = (name: string) => ({function: { name, description: name, parameters: { type: 'object' } },})-const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'bash', 'memory_write']+const ALL = ['read', 'ls', 'grep', 'write', 'edit', 'shell', 'memory_write']const opts = (over: Partial<Parameters<typeof buildCoworkTools>[0]> = {}) => ({planMode: false,@@ -123,12 +123,12 @@ describe('web tools', () => {expect(tools.web_fetch).toBeDefined()})- // Research is most of what planning is, so unlike write/edit/bash these are+ // Research is most of what planning is, so unlike write/edit/shell these are// reads that plan mode keeps.it('survive plan mode', async () => {const tools = await buildCoworkTools(opts({ webSearch: true, planMode: true }))expect(tools.web_search).toBeDefined()- expect(tools.bash).toBeUndefined()+ expect(tools.shell).toBeUndefined()})// Advertising them changes the tool JSON, so a run that froze without themdiff --git a/web-app/src/lib/__tests__/coworkTransport.test.ts b/web-app/src/lib/__tests__/coworkTransport.test.tsindex 1c83bce45..d564a4aca 100644--- a/web-app/src/lib/__tests__/coworkTransport.test.ts+++ b/web-app/src/lib/__tests__/coworkTransport.test.ts@@ -101,7 +101,7 @@ describe('CoworkChatTransport', () => {expect(buildCoworkTools).toHaveBeenCalledTimes(1)})- it('rebuilds when the sandbox appears, since bash joins the set', async () => {+ it('rebuilds when the sandbox appears, since shell joins the set', async () => {sandboxEnforces.mockReturnValue(false)const t = new CoworkChatTransport('s1', config())await t.refreshTools()@@ -132,7 +132,7 @@ describe('CoworkChatTransport.advertisedTools', () => {})// A subagent's allowlist intersects with this, so plan mode and a withheld- // `bash` reach children without a second policy check.+ // `shell` reach children without a second policy check.it('reports the set frozen for the run', async () => {const t = new CoworkChatTransport('s1', config())await t.refreshTools()diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.tsindex 08a0161e7..abd03b2a4 100644--- a/web-app/src/lib/__tests__/coworkTurns.test.ts+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts@@ -94,7 +94,7 @@ describe('coworkTurnsToUIMessages', () => {role: 'tool',content: '',callId: 'c',- name: 'bash',+ name: 'shell',status: 'running',},])@@ -109,7 +109,7 @@ describe('coworkTurnsToUIMessages', () => {role: 'tool',content: '',callId: 'c',- name: 'bash',+ name: 'shell',result: 'boom',isError: true,status: 'done',diff --git a/web-app/src/lib/__tests__/toolPresentation.test.ts b/web-app/src/lib/__tests__/toolPresentation.test.tsindex f5ae10b88..72d4552cd 100644--- a/web-app/src/lib/__tests__/toolPresentation.test.ts+++ b/web-app/src/lib/__tests__/toolPresentation.test.ts@@ -134,6 +134,15 @@ const agent = { kind: 'agent' } as constdescribe('describeNativeToolCall for agent tools', () => {it('builds a terminal from the command', () => {+ expect(describeNativeToolCall(agent, 'shell', { command: 'ls -la' })).toEqual({+ variant: 'terminal',+ command: 'ls -la',+ })+ })++ // Threads saved before the rename carry calls under the old `bash` name;+ // they still render as a terminal.+ it('renders a saved bash call as a terminal', () => {expect(describeNativeToolCall(agent, 'bash', { command: 'ls -la' })).toEqual({variant: 'terminal',command: 'ls -la',@@ -142,7 +151,7 @@ describe('describeNativeToolCall for agent tools', () => {// The command streams in like any other argument, so a partial one must show.it('accepts a partially streamed command', () => {- expect(describeNativeToolCall(agent, 'bash', { command: 'git pu' })).toEqual({+ expect(describeNativeToolCall(agent, 'shell', { command: 'git pu' })).toEqual({variant: 'terminal',command: 'git pu',})@@ -233,6 +242,19 @@ describe('parseBashOutput', () => {expect(r.sandboxNote).toContain('Network access is disabled')})+ it('surfaces hook config notices separately from the body', () => {+ const r = parseBashOutput(+ 'ok\n[exit 0]\n[hook config: Hook pre_tool_use matcher in /cfg/[x]/hooks.json ' ++ 'names `bash`, which matches nothing]\n[hook config: second]'+ )+ expect(r.exit).toBe(0)+ expect(r.text).toBe('ok')+ expect(r.configNotes).toEqual([+ 'Hook pre_tool_use matcher in /cfg/[x]/hooks.json names `bash`, which matches nothing',+ 'second',+ ])+ })+it('has no sandbox note on an ordinary run', () => {expect(parseBashOutput('ok\n[exit 0]').sandboxNote).toBeUndefined()})diff --git a/web-app/src/lib/agentActivity.test.ts b/web-app/src/lib/agentActivity.test.tsindex e211351a7..647a708d3 100644--- a/web-app/src/lib/agentActivity.test.ts+++ b/web-app/src/lib/agentActivity.test.ts@@ -25,15 +25,22 @@ describe('toolActivityText', () => {).toBe('Writing report.html')})- it('formats bash with truncated command', () => {+ it('formats shell with truncated command', () => {+ expect(toolActivityText('shell', { command: 'ls -la' })).toBe(+ 'Running ls -la'+ )+ })++ // Saved threads predate the rename and name the tool `bash`.+ it('formats a saved bash call like shell', () => {expect(toolActivityText('bash', { command: 'ls -la' })).toBe('Running ls -la')})- it('truncates long bash commands to 60 chars', () => {+ it('truncates long shell commands to 60 chars', () => {const long = 'echo ' + 'x'.repeat(100)- const text = toolActivityText('bash', { command: long })+ const text = toolActivityText('shell', { command: long })expect(text.startsWith('Running echo ')).toBe(true)expect(text.length).toBeLessThanOrEqual('Running '.length + 60)})@@ -66,7 +73,7 @@ describe('toolActivityText', () => {it('falls back gracefully when path/command arg is missing', () => {expect(toolActivityText('write', {})).toBe('Writing')- expect(toolActivityText('bash', {})).toBe('Running')+ expect(toolActivityText('shell', {})).toBe('Running')})})@@ -99,7 +106,7 @@ describe('awaitsModel', () => {role: 'tool',content: '',callId: 'c1',- name: 'bash',+ name: 'shell',status,})diff --git a/web-app/src/lib/agentActivity.ts b/web-app/src/lib/agentActivity.tsindex be333d5a0..73c41b1f4 100644--- a/web-app/src/lib/agentActivity.ts+++ b/web-app/src/lib/agentActivity.ts@@ -1,4 +1,5 @@import type { CoworkTurn } from '@/types/coworkSession'+import { isRecordedShellCall } from '@/lib/agentTools'const MAX_COMMAND_LEN = 60@@ -27,7 +28,7 @@ function humanizeToolName(name: string): string {const VERB_BY_TOOL: Record<string, string> = {write: 'Writing',edit: 'Editing',- bash: 'Running',+ shell: 'Running',read: 'Reading',ls: 'Listing',find: 'Finding',@@ -50,10 +51,10 @@ export function toolActivityText(toolName: string, input: unknown): string {return name ? `Reading ${name}` : 'Reading skill'}- const verb = VERB_BY_TOOL[toolName]+ const verb = VERB_BY_TOOL[isRecordedShellCall(toolName) ? 'shell' : toolName]if (!verb) return humanizeToolName(toolName)- if (toolName === 'bash') {+ if (isRecordedShellCall(toolName)) {const command = stringArg(input, 'command')return command ? `${verb} ${truncate(command, MAX_COMMAND_LEN)}` : verb}diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex d1004db70..69bdc1d7e 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -30,7 +30,7 @@ import { getServiceHub } from '@/hooks/useServiceHub'** `write` and `edit` are included: they can only touch the thread's ephemeral* sandbox, which is deleted with the conversation, so `execute_tool` allows them- * without a prompt. Withholding them while `bash` can write the same files would+ * without a prompt. Withholding them while `shell` can write the same files would* be a restriction a sibling tool trivially bypasses.** `web_search`/`web_fetch` are also built-ins but are already advertised through@@ -43,7 +43,7 @@ export const AGENT_TOOL_NAMES = new Set(['grep','write','edit',- 'bash',+ 'shell','memory_list','memory_read','memory_write',@@ -55,26 +55,35 @@ export const AGENT_TOOL_NAMES = new Set(['screenshot',])+/**+ * Whether a recorded tool call ran the shell, for *displaying saved history*+ * only. Turns saved before the tool was renamed carry its old name `bash`; they+ * keep their terminal view and artifacts. Nothing dispatches or allows `bash`:+ * the sets above and below name only `shell`.+ */+export const isRecordedShellCall = (toolName: string): boolean =>+ toolName === 'shell' || toolName === 'bash'+/*** The subset the main chat surface advertises and dispatches: the sandboxed* shell alone, with no network. The full toolset above is Cowork's — chat is a* conversation that occasionally runs a command, not an agent surface.*/-export const CHAT_AGENT_TOOL_NAMES = new Set(['bash'])+export const CHAT_AGENT_TOOL_NAMES = new Set(['shell'])/*** Tools that only run under an enforcing OS sandbox. They stay in* `AGENT_TOOL_NAMES` -- the desktop still owns dispatching them -- but are held* back from the advertised schemas when no backend can confine them.*/-const SANDBOX_REQUIRED_TOOLS = new Set(['bash'])+const SANDBOX_REQUIRED_TOOLS = new Set(['shell'])let schemaCache: ToolSchema[] | null = nulllet statusCache: Promise<SandboxStatus> | null = null/*** The sandbox backend for this machine, fetched once. A failure is treated as- * "no sandbox", which withholds `bash` rather than offering something that+ * "no sandbox", which withholds `shell` rather than offering something that* cannot run.*/export function getSandboxStatus(): Promise<SandboxStatus> {@@ -95,7 +104,7 @@ let enforcesNow = false/*** Re-probe the sandbox, dropping both caches. Installing a backend (bubblewrap* on Linux) cannot take effect otherwise: `statusCache` is module-level, and- * leaving `schemaCache` behind would keep `bash` withheld even once a backend+ * leaving `schemaCache` behind would keep `shell` withheld even once a backend* enforces.*/export function refreshSandboxStatus(): Promise<SandboxStatus> {@@ -115,7 +124,7 @@ export function sandboxEnforces(): boolean {/*** Schemas for the advertised subset. Rust's `schema.rs` is the only source, and- * the sandbox decides whether `bash` is among them.+ * the sandbox decides whether `shell` is among them.*/export async function getAgentToolSchemas(): Promise<ToolSchema[]> {if (schemaCache) return schemaCache@@ -239,7 +248,7 @@ const messageOf = (e: unknown): string =>* the desktop has no project picker yet, so the plugin uses the permanent store* in the Jan data folder.*- * `bash` additionally runs under an OS sandbox whose network access is closed+ * `shell` additionally runs under an OS sandbox whose network access is closed* unless the caller opens it. Chat never does; Cowork passes its own setting.*/export async function executeAgentTool(@@ -388,7 +397,7 @@ export async function stopAgentSessionMonitors(sessionId: string): Promise<void>}/**- * Kill every `bash` tree this session started when the user presses Stop.+ * Kill every `shell` tree this session started when the user presses Stop.* Best-effort: aborting the JS run already unwinds the turn, so a failure here* only means a shell keeps running, not user-visible damage.*/@@ -396,7 +405,7 @@ export async function cancelAgentThreadBash(sessionId: string): Promise<void> {try {await cancelThreadBash(sessionId)} catch (e) {- console.warn('[agentTools] Failed to cancel session bash:', messageOf(e))+ console.warn('[agentTools] Failed to cancel session shells:', messageOf(e))}}diff --git a/web-app/src/lib/coworkArtifacts.ts b/web-app/src/lib/coworkArtifacts.tsindex f4bd2601a..d54ace573 100644--- a/web-app/src/lib/coworkArtifacts.ts+++ b/web-app/src/lib/coworkArtifacts.ts@@ -1,6 +1,7 @@import { AudioLines, Code2, FileText, ImageIcon, Video } from 'lucide-react'import { basenameOf, extensionOf, resolveInRoot } from '@/lib/coworkPreview'import type { CoworkTurn } from '@/types/coworkSession'+import { isRecordedShellCall } from '@/lib/agentTools'/*** Artifacts a run produced, derived from its `write`/`edit` tool calls@@ -135,9 +136,9 @@ const pathFromInput = (input: unknown): string | undefined => {const PATH_TOKEN_RE = /"([^"]+)"|'([^']+)'|(\S+)/g/**- * Artifact paths a `bash` turn produced, recovered from its command and output.+ * Artifact paths a `shell` turn produced, recovered from its command and output.*- * `write` results name their file directly; `bash` does not. Two signals, one+ * `write` results name their file directly; `shell` does not. Two signals, one* rule:** 1. A path the command names explicitly (yt-dlp `-o out.mp4`, `ls -lh@@ -244,7 +245,7 @@ export function artifactsFromTurns(if (!path) continueconst artifact = artifactFor(path)if (artifact) byPath.set(path, artifact)- } else if (turn.name === 'bash') {+ } else if (isRecordedShellCall(turn.name ?? '')) {// Files made by shell commands (downloads, ffmpeg renders) carry no// `write` result; recover them from the command + output pair.const command =diff --git a/web-app/src/lib/coworkMonitor.ts b/web-app/src/lib/coworkMonitor.tsindex 5eecfa709..9ecb97cdc 100644--- a/web-app/src/lib/coworkMonitor.ts+++ b/web-app/src/lib/coworkMonitor.ts@@ -8,7 +8,7 @@ import type { MonitorView } from '@/types/coworkSession'** The watcher itself runs in Rust (`tools/monitor.rs`, reached through the* plugin's guest-js): it tails the file, evaluates the condition scripts under- * the same OS sandbox `bash` gets, and streams every match back as a+ * the same OS sandbox `shell` gets, and streams every match back as a* `MonitorUpdate`. What lives here is the client half: the transcribed schema* (like `task`/`todo`), and the bookkeeping that turns updates into inbox pings* so a match reaches the model as the same `<SYSTEM>` note a finished subagentdiff --git a/web-app/src/lib/coworkPrompt.ts b/web-app/src/lib/coworkPrompt.tsindex 2f68e8b37..f373d8c73 100644--- a/web-app/src/lib/coworkPrompt.ts+++ b/web-app/src/lib/coworkPrompt.ts@@ -61,7 +61,7 @@ export type CoworkPromptOptions = {* is the workspace root that relative paths resolve against (#8882). */readOnlyFolder: string | nullplanMode: boolean- /** False when no OS sandbox enforces, in which case `bash` is not offered. */+ /** False when no OS sandbox enforces, in which case `shell` is not offered. */bashAvailable: booleansubagentNames: string[]/** Whether `web_search`/`web_fetch` are advertised this run. */@@ -152,7 +152,7 @@ function workspaceBlock(opts: CoworkPromptOptions): string {lines.push('','Shell commands are unavailable on this machine: no OS sandbox is present to',- 'confine them, so the `bash` tool is not offered. Use the file tools instead.'+ 'confine them, so the `shell` tool is not offered. Use the file tools instead.')}return lines.join('\n')diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.tsindex 728f6ba58..a1bd3d253 100644--- a/web-app/src/lib/coworkRunner.ts+++ b/web-app/src/lib/coworkRunner.ts@@ -101,7 +101,7 @@ export function releaseHandle(sid: string, handle: RunHandle): void {* Stop a session's run: the model stream, the tool dispatch loop, every nested* subagent, and any question the user was being asked.*- * `abortRun` unwinds only the JS side; a running or backgrounded `bash` child+ * `abortRun` unwinds only the JS side; a running or backgrounded `shell` child* is killed separately by the Stop handler via `cancelAgentThreadBash`, which* reaps the session's shells in Rust (`proc::kill_thread`).*/diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex 0c18a635e..6ad32498f 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -456,6 +456,24 @@ export function injectInputs(return s}+/**+ * A list naming the shell's old name would silently give the child no shell,+ * so it is refused with the rename, as the Rust port does. `where` names the+ * list the model can actually fix.+ */+function renamedShellError(+ list: string[] | null | undefined,+ where: string+): { error: string } | undefined {+ const old = list?.find((t) => t.trim().toLowerCase() === 'bash')+ if (old === undefined) return undefined+ return {+ error:+ `${where} names \`${old.trim()}\`, which matches nothing: the shell tool is ` ++ 'now `shell`. Rename it to `shell` for it to apply.',+ }+}+/*** The child's effective allowlist: the definition's list, narrowed by the* call-site list, narrowed by what the parent itself can call.@@ -471,6 +489,10 @@ export function intersectAllowedTools(request: string[] | null | undefined,parentTools: string[]): { tools: string[] | null } | { error: string } {+ const renamed =+ renamedShellError(definition, "the subagent definition's allowed_tools") ??+ renamedShellError(request, 'allowed_tools')+ if (renamed) return renamedconst parent = new Set(parentTools)const withSkills = (tools: string[]) => {const out = [...tools]@@ -515,6 +537,12 @@ export function resolveSubagent(parentTools: string[]): ResolvedSubagent | { error: string } {const saved = definitions.find((d) => d.name === req.name)+ // With no saved definition the list came from the model's own call, so a+ // stale entry is reported as that, not as a definition's.+ if (!saved) {+ const renamed = renamedShellError(req.allowed_tools, 'allowed_tools')+ if (renamed) return renamed+ }const narrowed = intersectAllowedTools(saved ? saved.allowed_tools : (req.allowed_tools ?? null),// An inline allowlist *is* the ephemeral agent's definition, so it is not@@ -705,7 +733,7 @@ export async function runSubagent({workspacePath: opts.system.workspacePath,readOnlyFolder: opts.system.readOnlyFolder,- bashAvailable: opts.system.bashAvailable && 'bash' in tools,+ bashAvailable: opts.system.bashAvailable && 'shell' in tools,// Derived, not passed: the intersection above may have dropped them.webSearch: 'web_search' in tools,environment: opts.system.environment,diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex fdad20a7f..373e40e0a 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -20,7 +20,7 @@ import {export const PLAN_DENIED_TOOLS = new Set(['write','edit',- 'bash',+ 'shell','memory_write','skill_write','task',@@ -170,7 +170,7 @@ function taskTool(subagentNames: string[]): Tool {type: 'array',items: { type: 'string' },description:- "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs bash, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted.",+ "Optional tool allowlist. OMIT to give the subagent the parent's full toolset (the usual choice -- one that runs tests needs shell, one that edits needs write). Provide a list ONLY to restrict it; for a saved subagent it further narrows that subagent's own tools (never widens). An empty list is treated as omitted.",},},required: ['name', 'task'],diff --git a/web-app/src/lib/coworkTransport.ts b/web-app/src/lib/coworkTransport.tsindex 202bcbfa1..42a0fe485 100644--- a/web-app/src/lib/coworkTransport.ts+++ b/web-app/src/lib/coworkTransport.ts@@ -115,7 +115,7 @@ export class CoworkChatTransport extends CustomChatTransport {* The set actually advertised this run, for narrowing a subagent's tools.** A child's allowlist intersects with this rather than with the full built-in- * list, so plan mode and a withheld `bash` propagate to children for free.+ * list, so plan mode and a withheld `shell` propagate to children for free.*/get advertisedTools(): Record<string, Tool> {return this.frozenTools ?? this.toolsdiff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 3573f2cb9..9becf8a9d 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -1127,7 +1127,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// The main chat offers exactly one built-in agent tool: the sandboxed// shell, with no network. The full toolset lives in Cowork. Schemas come// from Rust so they are never re-typed here, and `getAgentToolSchemas`- // already withholds bash when no sandbox backend can confine it.+ // already withholds shell when no sandbox backend can confine it.try {for (const schema of await getAgentToolSchemas()) {if (!CHAT_AGENT_TOOL_NAMES.has(schema.function.name)) continue@@ -1742,7 +1742,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {/*** Static instruction for the one built-in tool chat offers: the sandboxed- * shell. Empty when no sandbox backend enforces, because bash is then+ * shell. Empty when no sandbox backend enforces, because shell is then* withheld too — stating limits for a tool that is not offered would only* confuse the model, and an empty string keeps the prompt prefix stable.*/@@ -1770,7 +1770,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// them by having a command refused.return ['# Shell',- 'bash runs commands in an isolated scratch workspace under an OS',+ 'shell runs commands in an isolated scratch workspace under an OS','sandbox: it starts there, can only write there, and cannot read files',"in the user's home directory. The workspace belongs to this",'conversation alone and is deleted with it, so do not keep anything',diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.tsindex 0827df9df..ac6e3785e 100644--- a/web-app/src/lib/toolPresentation.ts+++ b/web-app/src/lib/toolPresentation.ts@@ -1,5 +1,6 @@import type { ToolUIPart } from 'ai'import type { ToolOrigin } from './toolOrigin'+import { isRecordedShellCall } from '@/lib/agentTools'/** The call is still being written or executed: no result yet. */export const isToolRunning = (state: ToolUIPart['state']) =>@@ -13,7 +14,7 @@ export type ToolCallBar =| { variant: 'search'; query: string; count?: number }| { variant: 'address'; url: string }| { variant: 'documents'; query: string; count?: number; fileCount?: number }- /** `bash`, presented as a terminal. */+ /** `shell`, presented as a terminal. */| { variant: 'terminal'; command: string }/*** The workspace tools. `target` is whatever the call is really about -- a path@@ -127,7 +128,7 @@ export function describeNativeToolCall(}}if (origin.kind === 'agent') {- if (toolName === 'bash') {+ if (isRecordedShellCall(toolName)) {return {variant: 'terminal',command: asString(args.command),@@ -165,6 +166,8 @@ export type BashOutput = {truncated: boolean/** The OS sandbox refused something; explains the limits that applied. */sandboxNote?: string+ /** Config problems the call surfaced, e.g. a hook matcher on a renamed tool. */+ configNotes: string[]}/** Global: the exit marker is not always last, so every match is considered. */@@ -172,9 +175,11 @@ const EXIT_LINE = /\n?\[exit (-?\d+)\]/gconst SIGNAL_LINE = /\n?\[terminated by signal\]/const TRUNCATION_NOTICE = /\n?\[output truncated[^\]]*\]/const SANDBOX_NOTICE = /\n?\[sandbox: ([^\]]*)\]/+/** Line-anchored: the notice names a config path, which may contain `]`. */+const CONFIG_NOTICE = /\n?^\[hook config: (.*)\]$/gm/**- * Split `bash`'s `[exit N]` / `[terminated by signal]` status and its trailing+ * Split `shell`'s `[exit N]` / `[terminated by signal]` status and its trailing* notices off its output (see the tool description in `schema.rs`), so the* terminal can show a status of its own instead of leaving markers in the* scrollback. Absent or partial markers are normal: the run may still be going.@@ -194,6 +199,7 @@ export function parseBashOutput(output: unknown): BashOutput {const truncated = TRUNCATION_NOTICE.test(text)const signaled = SIGNAL_LINE.test(text)const sandboxNote = text.match(SANDBOX_NOTICE)?.[1]+ const configNotes = [...text.matchAll(CONFIG_NOTICE)].map((m) => m[1])// The last marker is the real one: a command can echo `[exit 0]` itself.const exits = [...text.matchAll(EXIT_LINE)]const exitMatch = exits.at(-1)@@ -203,6 +209,7 @@ export function parseBashOutput(output: unknown): BashOutput {.replace(SIGNAL_LINE, '').replace(TRUNCATION_NOTICE, '').replace(SANDBOX_NOTICE, '')+ .replace(CONFIG_NOTICE, '')return {text: body.replace(/\s+$/, ''),@@ -210,6 +217,7 @@ export function parseBashOutput(output: unknown): BashOutput {signaled,truncated,sandboxNote,+ configNotes,}}diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex e43b32bf7..8a06d65a1 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -210,7 +210,7 @@"shell": "Shell Commands","shellChecking": "Checking for a sandbox...","shellSandboxed": "Commands run confined by {{backend}}: they can only write inside the session workspace, and files in your home folder are not readable.",- "shellUnavailable": "No sandbox is available on this system, so the bash tool is not offered. Commands are never run unconfined.",+ "shellUnavailable": "No sandbox is available on this system, so the shell tool is not offered. Commands are never run unconfined.","network": "Allow Network Access","networkDesc": "Let Cowork commands reach the network, for things like installing packages or fetching a repository. On by default. The main chat's shell never has network access.","openFolder": "Open Folder",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 84e982951..7c7dde267 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -1401,7 +1401,7 @@ function CoworkPage() {const handleStop = useCallback(() => {// Aborting the JS run only discards the pending tool result; a running or- // backgrounded bash keeps executing until this kills the session's shells.+ // backgrounded shell keeps executing until this kills the session's shells.if (session?.id) {abortRun(session.id)void cancelAgentThreadBash(session.id)