Windows regression: explicit Git Bash `exec_command.shell` falls back to `cmd.exe`
What version of the Codex App are you using (From “About Codex” dialog)?
26.818.41509 / codex-cli 0.149.1
What subscription do you have?
Pro 20x
What platform is your computer?
Microsoft Windows NT 10.0.26100.0 x64
What issue are you seeing?
This is a regression in the CLI core embedded in Codex Desktop on native Windows. An exec_command call can provide an absolute Git Bash executable in the shell field, but with embedded CLI 0.149.0-alpha.4.1 the command is executed by cmd.exe instead.
The same absolute shell path worked in a closer rollout using embedded CLI 0.148.0-alpha.21:
| Rollout evidence | Embedded CLI | Result |
|---|---|---|
rollout-2026-08-21T16-20-45-01a02368-7ce7-7e90-9487-6630fadf44ad.jsonl |
0.148.0-alpha.21 |
Bash builtin printf, rg, and sed execute successfully through C:\Program Files\Git\bin\bash.exe |
rollout-2026-08-24T11-29-28-01a031d0-e351-7241-80ab-cd8ba21c7709.jsonl |
0.149.0-alpha.4.1 |
The same shell path produces -d was unexpected at this time. from cmd.exe |
rollout-2026-08-24T11-33-24-01a031d4-7e07-7cf2-8e01-66b0cc07cbbf.jsonl |
0.149.0-alpha.4.1 |
Four Git Bash path/login variants all produce 'printf' is not recognized... |
rollout-2026-08-18T09-49-17-01a0128f-01c0-7380-90e5-bd5c2c65a168.jsonl |
0.148.0-alpha.9 |
Earlier corroboration: wc and sed also execute successfully through the same shell path |
For example:
const r = await tools.exec_command({
cmd: "printf 'BASH=%s\\n' \"$BASH_VERSION\"",
workdir: "D:/path/to/repo",
shell: "C:/Program Files/Git/bin/bash.exe",
login: false
});
text(r.output);
Actual output:
'printf' is not recognized as an internal or external command,
operable program or batch file.
A second Bash-only command produces a characteristic cmd.exe parser error:
const r = await tools.exec_command({
cmd: "pwd && if [ -d . ]; then echo MEMORY_PRESENT; else echo MEMORY_MISSING; fi",
workdir: "D:/path/to/repo",
shell: "C:\\Program Files\\Git\\bin\\bash.exe"
});
text(r.output);
Actual output:
-d was unexpected at this time.
Git Bash itself is installed and functional. Both of these files exist:
C:\Program Files\Git\bin\bash.exe
C:\Program Files\Git\usr\bin\bash.exe
Launching the first executable directly from PowerShell with a .sh script succeeds:
BASH_VERSION=5.3.15(1)-release
PWD=/d/path/to/repo
BASH_CONDITIONAL=ok
The problem occurs when bash is not resolvable by bare name from the Codex process PATH; where.exe bash returns no match. The explicit absolute shell path should make that irrelevant, but Codex appears to discard it and silently selects cmd.exe.
The behavior was reproduced with:
- Forward-slash and backslash forms of
C:\Program Files\Git\bin\bash.exe C:\Program Files\Git\usr\bin\bash.exeloginomitted andlogin: false
As a control, an explicit PowerShell path in the same shell field works:
await tools.exec_command({
cmd: "Write-Output SHELL_FIELD_POWERSHELL_OK",
shell: "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
login: false
});
Output:
SHELL_FIELD_POWERSHELL_OK
This breaks repository instructions that require Git Bash syntax and explicitly direct the agent to pass Git Bash through exec_command.shell.
What steps can reproduce the bug?
- Install Codex Desktop and Git for Windows on native Windows.
- Confirm
C:\Program Files\Git\bin\bash.exeexists and can run a.shfile directly. - Ensure Git Bash's
bindirectory is not on the Codex processPATH, sowhere.exe bashreturns no match. Git's normalC:\Program Files\Git\cmddirectory may still be onPATH. - Start a Codex Desktop thread in a Windows-native workspace.
- Ask the agent to execute the first
tools.exec_commandsnippet above, withshellset to the absolute Git Bash path. - Observe that Bash syntax is parsed by
cmd.exeand fails. - Optionally repeat with the PowerShell control. It succeeds, showing that the
shellfield is reaching shell selection but the Git Bash executable path is not being honored.
Reproduction rollout/session IDs:
01a02368-7ce7-7e90-9487-6630fadf44ad(August 21 closest working baseline, embedded CLI0.148.0-alpha.21)01a0128f-01c0-7380-90e5-bd5c2c65a168(August 18 working subagent rollout; parent session01a00eda-0b19-7f92-9ca4-5304a5210b08)01a031d0-e351-7241-80ab-cd8ba21c7709(August 24 original failure; failing turn01a031d0-ed00-7e41-81b5-e0927e37ab6d)01a031d4-7e07-7cf2-8e01-66b0cc07cbbf(August 24 controlled reproduction)
At evidence extraction in the controlled reproduction, the last-turn token usage was 114,174 tokens with a 258,400-token context window (about 44.2%). Reported primary and secondary rate-limit usage was 0%.
What is the expected behavior?
When exec_command.shell identifies an installed and supported shell, Codex should execute the command with that requested shell type.
For the reproduction above, expected output is similar to:
BASH=5.3.15(1)-release
If model-provided executable paths are intentionally not launched for security reasons, Codex should safely discover standard Git for Windows Bash installations or return a clear shell-resolution error. It should not silently fall back to a different shell whose syntax is incompatible with the command.
Additional information
The regression corresponds directly to commit 186b449 / PR #39607, “Resolve model-provided shells by type”. The observed behavioral boundary is embedded CLI 0.148.0-alpha.21 working on August 21 versus 0.149.0-alpha.4.1 failing on August 24; the App package number is not used to identify the responsible core behavior.
In the working 0.148.0-alpha.21 source:
get_shell_pathfirst accepts the supplied path when it is an existing file.get_shell_by_model_provided_pathpasses that path through to shell resolution.
In the failing 0.149.0-alpha.4.1 source:
get_shell_by_model_provided_pathuses the supplied path only to determine a shell type, then rediscovers an executable.- Bash discovery searches for bare
bashand falls back only to/bin/bashand/usr/bin/bash; it has no standard Git for Windows fallback paths. - The Windows ultimate fallback is
cmd.exe.
PR #39607 explains that a model-provided path should select only the shell type and should not determine the executable Codex launches. That security goal is understandable, but on Windows it creates a regression when Git Bash exists at its standard absolute path while bare bash is not on PATH: Bash discovery fails and Codex silently switches to cmd.exe.
Possible fixes that preserve the security goal:
- Add safe Windows Bash discovery for standard Git for Windows locations such as
C:\Program Files\Git\bin\bash.exeandC:\Program Files\Git\usr\bin\bash.exe. - Return an explicit “requested Bash shell is unavailable” error instead of silently falling back to
cmd.exe. - If
shellis intentionally only a shell-type hint, update the tool schema description; it currently describes the field as the shell binary to launch.
I searched existing issues before drafting this report. These are related but appear materially different:
- #13199 broadly reports difficulty running Git Bash commands on Windows with CLI
0.106.0; it predates this regression and does not isolate an explicit absoluteexec_command.shellpath being discarded after PR #39607. - #16579 requests persistent configuration of the default Windows session shell.
- #27474 concerns WSL runner startup and
/bin/bashprocess creation. - #9581 concerns shell-aware command generation and
cmd.exewrapping, not an explicit absoluteshellpath being discarded.
A sanitized JSONL reproduction bundle is available as an attachment. It preserves the original rollout filenames and line numbers for the version metadata, the corroborating success, the failure, and the controlled reproduction without including the full conversations.
The standalone codex --version value is not used as the regression boundary here. Each rollout's own session_meta.cli_version identifies the CLI core actually embedded in Codex Desktop and responsible for that session.
I’d like to work on a narrow fix for this, with implementation and testing performed using Codex under my direction and review.
The proposed approach is to add the standard Git for Windows bash.exe locations to Windows Bash discovery while preserving the security behaviour from #39607: the model-provided path selects only the shell type and is never executed directly.
I’ll include focused codex-shell-command regression coverage and verify the case where Git Bash is installed but bare bash is absent from PATH. I’ll report the exact test results in the PR rather than presenting unverified claims.
Implementation is ready in my fork: https://github.com/TerminalDev-1/codex/commit/b6bde09c2d9033c29eb63e38e05877704a466140
The change adds Windows-only Bash fallback discovery for:
C:\Program Files\Git\bin\bash.exeC:\Program Files\Git\usr\bin\bash.exe
It preserves the security behaviour from #39607: the model-provided path still selects only the shell type and is not executed directly. I also added focused coverage for selecting an existing fallback when the requested shell is not otherwise discoverable.
Validation:
just fmtjust test -p codex-shell-command— 172/172 tests passed- Windows smoke environment matched the report: bare
bashabsent fromPATH, both standard Git Bash executables present, and thebin\bash.exeexecutable successfully ran Bash syntax.
This was an AI-assisted contribution. I directed and reviewed the work; Codex traced the regression, explained the proposed change before implementation, produced the patch, and ran the formatting and tests. I reviewed the scope, diff, and results and take responsibility for the contribution.
GitHub currently reports that only repository collaborators may open pull requests against openai/codex, so I cannot submit the prepared cross-fork PR from this account. The comparison is mergeable and contains one commit touching one file. If a maintainer would like the change, it can be cherry-picked from the commit above, or I would be happy to open the PR if granted the required access.
Implementation is ready in my fork: TerminalDev-1@b6bde09
The change adds Windows-only Bash fallback discovery for:
C:\Program Files\Git\bin\bash.exeC:\Program Files\Git\usr\bin\bash.exeIt preserves the security behaviour from #39607: the model-provided path still selects only the shell type and is not executed directly. I also added focused coverage for selecting an existing fallback when the requested shell is not otherwise discoverable.
Validation:
just fmtjust test -p codex-shell-command— 172/172 tests passed- Windows smoke environment matched the report: bare
bashabsent fromPATH, both standard Git Bash executables present, and thebin\bash.exeexecutable successfully ran Bash syntax.This was an AI-assisted contribution. I directed and reviewed the work; Codex traced the regression, explained the proposed change before implementation, produced the patch, and ran the formatting and tests. I reviewed the scope, diff, and results and take responsibility for the contribution.
GitHub currently reports that only repository collaborators may open pull requests against
openai/codex, so I cannot submit the prepared cross-fork PR from this account. The comparison is mergeable and contains one commit touching one file. If a maintainer would like the change, it can be cherry-picked from the commit above, or I would be happy to open the PR if granted the required access.
Thanks for the detailed report and for the targeted fix in #40328. The proposed addition of the standard Git for Windows paths (C:\Program Files\Git\bin\bash.exe and C:\Program Files\Git\usr\bin\bash.exe) addresses the most common installation scenario and is a good immediate improvement.
However, I think there are a few broader points that might be worth considering alongside or after this fix, to make the behaviour more robust and less surprising for users.
-
User‑customised installation paths
Git for Windows allows users to install to a non‑default location (e.g.,D:\Tools\Git\bin\bash.exe). If a model provides an absolute path that is valid and exists, but it is not in the hard‑coded fallback list, the same regression will occur—Bash discovery fails and execution falls back tocmd.exe.
A more resilient approach would be to treat the supplied path as a candidate when it points to an existing executable file, even if it is not used directly for security reasons. At a minimum, we could check whether the supplied path is executable and, if so, use it as the shell binary (which is what happened before the regression). If the intent is to keep the “type‑only” semantics, then we should at least verify that the supplied path is valid and, if not, surface a clear error instead of silently falling back. -
Explicit error when the requested shell type is unavailable
The current behaviour of falling back tocmd.exewithout warning is very confusing. In the reproduction, the user explicitly asked forbash.exe, but the actual command was run bycmd.exe, producing cryptic errors like-d was unexpected at this time.
I would argue that when the requested shell type (e.g.,bash) cannot be discovered through any of the safe mechanisms, Codex should return a clear error message stating that the requested shell is not available, rather than silently substituting a different shell. This would make the failure obvious and actionable. -
Other popular Bash environments on Windows
While Git Bash is the most common, there are other widely used Bash providers on Windows that developers often rely on:- WSL – with over 5 million monthly active users (per recent reports), WSL is a very popular choice. However, WSL’s Bash is typically invoked via
wsl.exerather than a directbash.exepath, so the discovery logic might need special handling. - Cygwin – often installed at
C:\cygwin\bin\bash.exeorC:\cygwin64\bin\bash.exe. - MSYS2 – the underlying runtime for Git Bash, but also available as a standalone installation (e.g.,
C:\msys2\usr\bin\bash.exe).
Adding fallback paths for these environments (or at least documenting that they are not currently discovered) could improve compatibility for users who rely on them. Even if we don’t add them immediately, it’s worth noting that the current fix only covers Git Bash, and there may be future requests for these other environments.
- WSL – with over 5 million monthly active users (per recent reports), WSL is a very popular choice. However, WSL’s Bash is typically invoked via
-
Update the tool schema description
Theexec_command.shellfield is currently described as “the shell binary to launch.” Since the implementation now treats it as a type hint rather than an executable path, the description should be updated to reflect that reality. This would set correct expectations for users and model authors.
I appreciate that the security considerations behind #39607 are important, and I fully support not blindly executing a model‑provided path. But the current behaviour on Windows introduces a significant regression that can break workflows. The proposed fix is a good first step; I hope we can also address the additional points above to make the experience more reliable and transparent.
It’ll be appreciated if considering this.
Thank you for the detailed reply. I’m glad you took the time to consider the proposed fix and the broader implications.
I’ll definitely take your suggestions into consideration. Supporting non-standard Git installations, returning a clear error instead of silently falling back to cmd.exe, and clarifying the exec_command.shell schema all sound worth investigating. Cygwin, MSYS2, and WSL may also deserve separate follow-up work because they have different discovery and execution models.
For transparency, this is my first time contributing to an open-source project. I work by directing and reviewing Codex rather than writing the implementation by hand, so I genuinely appreciate you engaging constructively with the work and giving me useful technical feedback.
I’d like to keep the initial patch narrowly focused on the standard Git for Windows regression, particularly because accepting arbitrary supplied executable paths would interact with the security boundary introduced in #39607. The additional improvements could then be explored independently without making this first fix significantly harder to review.
Thank you again—I appreciate the thoughtful response.
Confirming this still reproduces on the current build, plus two contributing facts I found while triaging it.
Environment: Codex Desktop 26.1117.3838.0, bundled codex-cli 0.171.0-alpha.13; the standalone codex-cli 0.167.0-alpha.4.1 behaves identically. Windows 11 x64, ANSI code page 936. codex-rs/shell-command/src/shell_detect.rs on main still contains the same code.
1. The substitution is silent and reports success. With no bash on PATH, exec_command({shell: "bash", cmd: "echo BASHOK; uname -s"}) is executed as:
{"type":"item.completed","item":{"id":"item_2","type":"command_execution",
"command":"cmd.exe /c 'echo BASHOK; uname -s'",
"aggregated_output":"BASHOK; uname -s\r\n","exit_code":0,"status":"completed"}}
uname never ran, but the tool result looks successful, so the model keeps building on a wrong result. The code path is get_shell_by_model_provided_path():
detect_shell_type(shell_path).and_then(get_shell)
.unwrap_or_else(ultimate_fallback_shell) // == cmd.exe on Windows
The same happens for any shell value that isn't bash / powershell / cmd / sh (e.g. a model typo such as "powerspace"); there is no validation and no warning in the tool output.
2. A default Git for Windows install still leaves bash unresolvable. BASH_FALLBACK_PATHS is ["/bin/bash", "/usr/bin/bash"], so on Windows bash is only ever found through which("bash"). Git for Windows' default installer option ("Git from the command line and also from 3rd-party software") appends only <Git>\cmd to PATH, while bash.exe lives in <Git>\bin (<Git>\cmd\bash.exe does not exist). Verified on a standard Git 2.55 install: cmd\bash.exe → absent, bin\bash.exe → present.
3. The bundled primary runtime does not fill the gap. dependencies\native\git\ contains cmd, etc, ucrt64, usr — there is no bin directory, and dir /s /b ...\native\git\bash.exe returns nothing; only usr\bin\sh.exe exists. The tool-process PATH that Codex builds adds ...\dependencies\native\git\cmd, but never ...\dependencies\native\git\usr\bin, so even that sh.exe is not discoverable, and shell: "sh" also falls through to cmd.exe.
So the Windows-only fallback paths proposed earlier in this thread fix the standard-install case, and returning a clear error instead of silently falling back would cover the rest (missing/non-standard installs, invalid values). Happy to test a build if that helps.
I reproduced the silent fallback on native Windows with the installed CLI 0.171.0-alpha.13.2. I also tested a patch for the explicit-error case discussed above. It complements the standard Git for Windows discovery proposal by covering requests whose shell still cannot be resolved.
Minimal reproduction
Start a Windows Codex session where bash is not discoverable on the Codex process's PATH. Create a harmless sample.txt in the working directory before making the tool call.
text(await tools.exec_command({
cmd: "Get-Content -LiteralPath 'sample.txt' | Select-Object -First 1",
shell: "bash",
login: false
}));
The mismatched arguments reproduce a call captured in a Desktop session. The installed CLI launches cmd.exe /c, and Get-Content fails. The expected result when Bash cannot be resolved is a tool error before any shell process starts.
Proposed patch
The Windows exec_command handler now rejects unknown explicit shell names and recognized shell types that cannot be discovered. Omitting shell still uses the session default. Explicit cmd remains supported, and Windows shell names are matched case-insensitively. The tool description reflects this behavior. Model-supplied paths continue to select a shell type through Codex discovery, preserving the behavior introduced in #39607.
Verification
I built the patched CLI from rust-v0.171.0-alpha.13 and replayed the same request in two fresh CLI sessions per build. A local mock supplied the tool arguments so both builds received the same input.
| Build | Unavailable bash |
PowerShell control |
|---|---|---|
Installed 0.171.0-alpha.13.2 |
2/2 launched cmd.exe /c and failed |
2/2 passed |
Patched 0.171.0-alpha.13 |
2/2 returned an error identifying Bash as unavailable, with no command-execution event | 2/2 passed |
The PowerShell control explicitly selected powershell and used Write-Output to check that normal execution still worked. These were standalone CLI sessions. The patched Desktop runtime remains untested.
Codex helped prepare the patch and run the verification. Would a focused PR for this guard be useful alongside the Bash discovery change?
Full patch against rust-v0.171.0-alpha.13
diff --git a/codex-rs/core/src/tools/handlers/shell_spec.rs b/codex-rs/core/src/tools/handlers/shell_spec.rs
index 2a58e35..b22dc23 100644
--- a/codex-rs/core/src/tools/handlers/shell_spec.rs
+++ b/codex-rs/core/src/tools/handlers/shell_spec.rs
@@ -45,7 +45,12 @@ pub(crate) fn create_exec_command_tool(options: ExecCommandHandlerOptions) -> To
properties.insert(
"shell".to_string(),
JsonSchema::string(Some(
- "Shell binary to launch. Defaults to the user's default shell.".to_string(),
+ if options.include_windows_shell_guidance {
+ "Shell type to discover and launch. Omit to use the session's default shell. For PowerShell commands use PowerShell. An unsupported or unavailable shell is rejected."
+ } else {
+ "Shell binary to launch. Defaults to the user's default shell."
+ }
+ .to_string(),
)),
);
properties.insert(
diff --git a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs
index 0356201..3809760 100644
--- a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs
+++ b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs
@@ -45,7 +45,12 @@ fn exec_command_tool_matches_expected_spec() {
(
"shell".to_string(),
JsonSchema::string(Some(
- "Shell binary to launch. Defaults to the user's default shell.".to_string(),
+ if cfg!(windows) {
+ "Shell type to discover and launch. Omit to use the session's default shell. For PowerShell commands use PowerShell. An unsupported or unavailable shell is rejected."
+ } else {
+ "Shell binary to launch. Defaults to the user's default shell."
+ }
+ .to_string(),
)),
),
(
diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs
index ec7a7d2..78b7eef 100644
--- a/codex-rs/core/src/tools/handlers/unified_exec.rs
+++ b/codex-rs/core/src/tools/handlers/unified_exec.rs
@@ -3,6 +3,7 @@ use crate::sandboxing::SandboxPermissions;
use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
use crate::shell::ShellInvocation;
+use crate::shell::get_shell;
use crate::shell::get_shell_by_model_provided_path;
use crate::tools::context::ToolEnvironments;
use crate::tools::context::ToolInvocation;
@@ -13,9 +14,11 @@ use crate::tools::handlers::resolve_tool_environment;
use crate::tools::hook_names::HookToolName;
use crate::tools::registry::PostToolUsePayload;
use codex_protocol::models::AdditionalPermissionProfile;
+use codex_shell_command::shell_detect::detect_shell_type;
use codex_utils_path_uri::PathUri;
use futures::future::BoxFuture;
use serde::Deserialize;
+use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
@@ -163,11 +166,25 @@ pub(crate) fn get_command(
None => allow_login_shell,
};
- let shell = args
- .shell
- .as_ref()
- .map(|shell_str| get_shell_by_model_provided_path(&PathBuf::from(shell_str)))
- .unwrap_or_else(|| session_shell.as_ref().clone());
+ let shell = match args.shell.as_deref() {
+ None => session_shell.as_ref().clone(),
+ Some(requested_shell) if cfg!(windows) => {
+ let shell_type = detect_shell_type(Path::new(requested_shell)).ok_or_else(|| {
+ format!(
+ "Unsupported shell {requested_shell:?}. Omit `shell` to use the session's {} shell, or specify an installed shell that matches the command's syntax.",
+ session_shell.name()
+ )
+ })?;
+ get_shell(shell_type).ok_or_else(|| {
+ format!(
+ "Requested shell `{}` is unavailable. Omit `shell` to use the session's {} shell if the command matches its syntax.",
+ shell_type.name(),
+ session_shell.name()
+ )
+ })?
+ }
+ Some(requested_shell) => get_shell_by_model_provided_path(&PathBuf::from(requested_shell)),
+ };
Ok(ResolvedCommand {
command: shell.derive_exec_args(&args.cmd, use_login_shell),
shell: ShellInvocation {
diff --git a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs
index 45bac34..d240c1c 100644
--- a/codex-rs/core/src/tools/handlers/unified_exec_tests.rs
+++ b/codex-rs/core/src/tools/handlers/unified_exec_tests.rs
@@ -7,6 +7,7 @@ use codex_exec_server::Environment;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
+use std::path::PathBuf;
use std::sync::Arc;
use crate::environment_selection::TurnEnvironmentState;
@@ -76,24 +77,44 @@ fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
assert_eq!(args.shell.as_deref(), Some("/bin/bash"));
- let resolved = get_command(
+ let result = get_command(
&args,
Arc::new(default_user_shell()),
/*allow_login_shell*/ true,
- )
- .map_err(anyhow::Error::msg)?;
- let command = resolved.command;
-
- assert_eq!(command.last(), Some(&"echo hello".to_string()));
- if command
- .iter()
- .any(|arg| arg.eq_ignore_ascii_case("-Command"))
- {
- assert!(command.contains(&"-NoProfile".to_string()));
+ );
+ if let Some(bash) = get_shell(ShellType::Bash) {
+ let resolved = result.map_err(anyhow::Error::msg)?;
+ assert_eq!(
+ resolved.command,
+ bash.derive_exec_args("echo hello", /*use_login_shell*/ true)
+ );
+ } else if cfg!(windows) {
+ assert!(
+ result
+ .expect_err("an unavailable Bash must not start a different shell")
+ .contains("Requested shell `bash` is unavailable")
+ );
+ } else {
+ let resolved = result.map_err(anyhow::Error::msg)?;
+ assert_eq!(resolved.command.last().map(String::as_str), Some("echo hello"));
}
Ok(())
}
+#[cfg(windows)]
+#[test]
+fn test_get_command_rejects_unsupported_explicit_shell() -> anyhow::Result<()> {
+ let args = parse_arguments(r#"{"cmd":"echo hello","shell":"unrecognized-shell"}"#)?;
+ let error = get_command(
+ &args,
+ Arc::new(default_user_shell()),
+ /*allow_login_shell*/ true,
+ )
+ .expect_err("an unknown shell must not start a fallback shell");
+ assert!(error.contains("Unsupported shell \"unrecognized-shell\""));
+ Ok(())
+}
+
/// Nested commands must find the first reported tool directory after login startup without duplicating existing entries.
#[cfg(unix)]
#[test]
@@ -275,13 +296,22 @@ fn test_get_command_resolves_powershell_by_type() -> anyhow::Result<()> {
Some(powershell_path.to_string_lossy().as_ref())
);
- let resolved = get_command(
+ let result = get_command(
&args,
Arc::new(default_user_shell()),
/*allow_login_shell*/ true,
- )
- .map_err(anyhow::Error::msg)?;
- let expected_shell = get_shell(ShellType::PowerShell)
+ );
+ let expected_shell = get_shell(ShellType::PowerShell);
+ if cfg!(windows) && expected_shell.is_none() {
+ assert!(
+ result
+ .expect_err("unavailable PowerShell must not start cmd.exe")
+ .contains("Requested shell `powershell` is unavailable")
+ );
+ return Ok(());
+ }
+ let resolved = result.map_err(anyhow::Error::msg)?;
+ let expected_shell = expected_shell
.unwrap_or_else(|| codex_shell_command::shell_detect::ultimate_fallback_shell().into());
assert_eq!(
resolved.command,
@@ -293,11 +323,12 @@ fn test_get_command_resolves_powershell_by_type() -> anyhow::Result<()> {
#[test]
fn test_get_command_respects_explicit_cmd_shell() -> anyhow::Result<()> {
- let json = r#"{"cmd": "echo hello", "shell": "cmd"}"#;
+ let shell = if cfg!(windows) { "CMD.EXE" } else { "cmd" };
+ let json = serde_json::json!({"cmd": "echo hello", "shell": shell}).to_string();
- let args: ExecCommandArgs = parse_arguments(json)?;
+ let args: ExecCommandArgs = parse_arguments(&json)?;
- assert_eq!(args.shell.as_deref(), Some("cmd"));
+ assert_eq!(args.shell.as_deref(), Some(shell));
let resolved = get_command(
&args,
@@ -308,6 +339,9 @@ fn test_get_command_respects_explicit_cmd_shell() -> anyhow::Result<()> {
let command = resolved.command;
assert_eq!(command[2], "echo hello");
+ if cfg!(windows) {
+ assert_eq!(resolved.shell.shell.shell_type, ShellType::Cmd);
+ }
Ok(())
}
diff --git a/codex-rs/shell-command/src/shell_detect.rs b/codex-rs/shell-command/src/shell_detect.rs
index 3aecd03..77cc582 100644
--- a/codex-rs/shell-command/src/shell_detect.rs
+++ b/codex-rs/shell-command/src/shell_detect.rs
@@ -38,7 +38,12 @@ impl DetectedShell {
pub fn detect_shell_type(shell_path: impl AsRef<std::path::Path>) -> Option<ShellType> {
let shell_path = shell_path.as_ref();
- match shell_path.as_os_str().to_str() {
+ let name = shell_path.to_str();
+ #[cfg(windows)]
+ let normalized_name = name.map(str::to_ascii_lowercase);
+ #[cfg(windows)]
+ let name = normalized_name.as_deref();
+ match name {
Some("zsh") => Some(ShellType::Zsh),
Some("sh") => Some(ShellType::Sh),
Some("cmd") => Some(ShellType::Cmd),
@@ -319,10 +324,12 @@ pub fn fallback_powershell_shell_for_windows_sandbox(
fn get_cmd_shell() -> Option<DetectedShell> {
let shell_path = get_shell_path(ShellType::Cmd, "cmd", &[]);
- shell_path.map(|shell_path| DetectedShell {
- shell_type: ShellType::Cmd,
- shell_path,
- })
+ shell_path
+ .map(|shell_path| DetectedShell {
+ shell_type: ShellType::Cmd,
+ shell_path,
+ })
+ .or_else(|| cfg!(windows).then(ultimate_fallback_shell))
}
pub fn ultimate_fallback_shell() -> DetectedShell {