Skip to content

Commit c5524e5

Browse files
author
macmini
committed
fix(core): preserve env by defaulting shell tools to non-login
1 parent 25fbd7e commit c5524e5

11 files changed

Lines changed: 127 additions & 40 deletions

File tree

‎codex-rs/core/config.schema.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1903,7 +1903,7 @@
19031903
"description": "Agent-related settings (thread limits, etc.)."
19041904
},
19051905
"allow_login_shell": {
1906-
"description": "Whether the model may request a login shell for shell-based tools. Default to `true`\n\nIf `true`, the model may request a login shell (`login = true`), and omitting `login` defaults to using a login shell. If `false`, the model can never use a login shell: `login = true` requests are rejected, and omitting `login` defaults to a non-login shell.",
1906+
"description": "Whether the model may request a login shell for shell-based tools. Default to `true`\n\nIf `true`, the model may request a login shell (`login = true`), but omitting `login` defaults to a non-login shell so Codex preserves the caller's environment ordering. If `false`, the model can never use a login shell: `login = true` requests are rejected, and omitting `login` still defaults to a non-login shell.",
19071907
"type": "boolean"
19081908
},
19091909
"analytics": {

‎codex-rs/core/src/codex_tests.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4374,6 +4374,29 @@ async fn run_user_shell_command_does_not_set_reference_context_item() {
43744374
);
43754375
}
43764376

4377+
#[cfg(unix)]
4378+
#[tokio::test]
4379+
async fn run_user_shell_command_uses_non_login_shell_by_default() {
4380+
let (session, _turn_context, rx) = make_session_and_context_with_rx().await;
4381+
4382+
handlers::run_user_shell_command(&session, "sub-id".to_string(), "echo shell".to_string())
4383+
.await;
4384+
4385+
let deadline = StdDuration::from_secs(15);
4386+
let start = std::time::Instant::now();
4387+
loop {
4388+
let remaining = deadline.saturating_sub(start.elapsed());
4389+
let evt = tokio::time::timeout(remaining, rx.recv())
4390+
.await
4391+
.expect("timeout waiting for event")
4392+
.expect("event");
4393+
if let EventMsg::ExecCommandBegin(begin) = evt.msg {
4394+
assert_eq!(begin.command[1], "-c");
4395+
break;
4396+
}
4397+
}
4398+
}
4399+
43774400
#[derive(Clone, Copy)]
43784401
struct NeverEndingTask {
43794402
kind: TaskKind,

‎codex-rs/core/src/config/mod.rs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -197,11 +197,12 @@ pub struct Permissions {
197197
/// Whether the model may request a login shell for shell-based tools.
198198
/// Default to `true`
199199
///
200-
/// If `true`, the model may request a login shell (`login = true`), and
201-
/// omitting `login` defaults to using a login shell.
200+
/// If `true`, the model may request a login shell (`login = true`), but
201+
/// omitting `login` defaults to a non-login shell so Codex preserves the
202+
/// caller's environment ordering.
202203
/// If `false`, the model can never use a login shell: `login = true`
203-
/// requests are rejected, and omitting `login` defaults to a non-login
204-
/// shell.
204+
/// requests are rejected, and omitting `login` still defaults to a
205+
/// non-login shell.
205206
pub allow_login_shell: bool,
206207
/// Policy used to build process environments for shell/unified exec.
207208
pub shell_environment_policy: ShellEnvironmentPolicy,
@@ -1105,11 +1106,12 @@ pub struct ConfigToml {
11051106
/// Whether the model may request a login shell for shell-based tools.
11061107
/// Default to `true`
11071108
///
1108-
/// If `true`, the model may request a login shell (`login = true`), and
1109-
/// omitting `login` defaults to using a login shell.
1109+
/// If `true`, the model may request a login shell (`login = true`), but
1110+
/// omitting `login` defaults to a non-login shell so Codex preserves the
1111+
/// caller's environment ordering.
11101112
/// If `false`, the model can never use a login shell: `login = true`
1111-
/// requests are rejected, and omitting `login` defaults to a non-login
1112-
/// shell.
1113+
/// requests are rejected, and omitting `login` still defaults to a
1114+
/// non-login shell.
11131115
pub allow_login_shell: Option<bool>,
11141116

11151117
/// Sandbox mode to use.

‎codex-rs/core/src/memories/usage.rs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,7 @@ fn shell_command_for_invocation(invocation: &ToolInvocation) -> Option<(Vec<Stri
8787
if !invocation.turn.tools_config.allow_login_shell && params.login == Some(true) {
8888
return (Vec::new(), invocation.turn.resolve_path(params.workdir));
8989
}
90-
let use_login_shell = params
91-
.login
92-
.unwrap_or(invocation.turn.tools_config.allow_login_shell);
90+
let use_login_shell = params.login.unwrap_or(false);
9391
let command = invocation
9492
.session
9593
.user_shell()

‎codex-rs/core/src/tasks/user_shell.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ pub(crate) async fn execute_user_shell_command(
122122
// Execute the user's script under their default shell when known; this
123123
// allows commands that use shell features (pipes, &&, redirects, etc.).
124124
// We do not source rc files or otherwise reformat the script.
125-
let use_login_shell = true;
125+
let use_login_shell = false;
126126
let session_shell = session.user_shell();
127127
let display_command = session_shell.derive_exec_args(&command, use_login_shell);
128128
let exec_command = maybe_wrap_shell_lc_with_snapshot(

‎codex-rs/core/src/tools/handlers/shell.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,13 +125,13 @@ impl ShellCommandHandler {
125125
login: Option<bool>,
126126
allow_login_shell: bool,
127127
) -> Result<bool, FunctionCallError> {
128-
if !allow_login_shell && login == Some(true) {
129-
return Err(FunctionCallError::RespondToModel(
128+
match login {
129+
Some(true) if !allow_login_shell => Err(FunctionCallError::RespondToModel(
130130
"login shell is disabled by config; omit `login` or set it to false.".to_string(),
131-
));
131+
)),
132+
Some(use_login_shell) => Ok(use_login_shell),
133+
None => Ok(false),
132134
}
133-
134-
Ok(login.unwrap_or(allow_login_shell))
135135
}
136136

137137
fn base_command(shell: &Shell, command: &str, use_login_shell: bool) -> Vec<String> {

‎codex-rs/core/src/tools/handlers/shell_tests.rs‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ fn assert_safe(shell: &Shell, command: &str) {
7272
}
7373

7474
#[tokio::test]
75-
async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_context() {
75+
async fn shell_command_handler_to_exec_params_defaults_to_non_login_and_uses_turn_context() {
7676
let (session, turn_context) = make_session_and_context().await;
7777

7878
let command = "echo hello".to_string();
@@ -84,7 +84,7 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
8484

8585
let expected_command = session
8686
.user_shell()
87-
.derive_exec_args(&command, /*use_login_shell*/ true);
87+
.derive_exec_args(&command, /*use_login_shell*/ false);
8888
let expected_cwd = turn_context.resolve_path(workdir.clone());
8989
let expected_env = create_env(
9090
&turn_context.shell_environment_policy,
@@ -122,6 +122,37 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
122122
assert_eq!(exec_params.arg0, None);
123123
}
124124

125+
#[tokio::test]
126+
async fn shell_command_handler_to_exec_params_honors_explicit_login_when_allowed() {
127+
let (session, turn_context) = make_session_and_context().await;
128+
let params = ShellCommandToolCallParams {
129+
command: "echo hello".to_string(),
130+
workdir: None,
131+
login: Some(true),
132+
timeout_ms: None,
133+
sandbox_permissions: None,
134+
additional_permissions: None,
135+
prefix_rule: None,
136+
justification: None,
137+
};
138+
139+
let exec_params = ShellCommandHandler::to_exec_params(
140+
&params,
141+
&session,
142+
&turn_context,
143+
session.conversation_id,
144+
/*allow_login_shell*/ true,
145+
)
146+
.expect("explicit login shells should be allowed");
147+
148+
assert_eq!(
149+
exec_params.command,
150+
session
151+
.user_shell()
152+
.derive_exec_args("echo hello", /*use_login_shell*/ true)
153+
);
154+
}
155+
125156
#[test]
126157
fn shell_command_handler_respects_explicit_login_flag() {
127158
let (_tx, shell_snapshot) = watch::channel(Some(Arc::new(ShellSnapshot {

‎codex-rs/core/src/tools/handlers/unified_exec.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ pub(crate) fn get_command(
387387
);
388388
}
389389
Some(use_login_shell) => use_login_shell,
390-
None => allow_login_shell,
390+
None => false,
391391
};
392392

393393
match shell_mode {

‎codex-rs/core/src/tools/handlers/unified_exec_tests.rs‎

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::*;
22
use crate::shell::default_user_shell;
3+
use crate::shell::get_shell_by_model_provided_path;
34
use crate::tools::handlers::parse_arguments_with_base_path;
45
use crate::tools::handlers::resolve_workdir_base_path;
56
use crate::tools::spec::ZshForkConfig;
@@ -8,6 +9,7 @@ use codex_protocol::models::PermissionProfile;
89
use codex_utils_absolute_path::AbsolutePathBuf;
910
use pretty_assertions::assert_eq;
1011
use std::fs;
12+
use std::path::PathBuf;
1113
use std::sync::Arc;
1214
use tempfile::tempdir;
1315

@@ -24,19 +26,22 @@ fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()>
2426
let json = r#"{"cmd": "echo hello"}"#;
2527

2628
let args: ExecCommandArgs = parse_arguments(json)?;
29+
let session_shell = Arc::new(default_user_shell());
2730

2831
assert!(args.shell.is_none());
2932

3033
let command = get_command(
3134
&args,
32-
Arc::new(default_user_shell()),
35+
session_shell.clone(),
3336
&UnifiedExecShellMode::Direct,
3437
/*allow_login_shell*/ true,
3538
)
3639
.map_err(anyhow::Error::msg)?;
3740

38-
assert_eq!(command.len(), 3);
39-
assert_eq!(command[2], "echo hello");
41+
assert_eq!(
42+
command,
43+
session_shell.derive_exec_args("echo hello", /*use_login_shell*/ false)
44+
);
4045
Ok(())
4146
}
4247

@@ -45,6 +50,7 @@ fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
4550
let json = r#"{"cmd": "echo hello", "shell": "/bin/bash"}"#;
4651

4752
let args: ExecCommandArgs = parse_arguments(json)?;
53+
let shell = get_shell_by_model_provided_path(&PathBuf::from("/bin/bash"));
4854

4955
assert_eq!(args.shell.as_deref(), Some("/bin/bash"));
5056

@@ -56,13 +62,10 @@ fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
5662
)
5763
.map_err(anyhow::Error::msg)?;
5864

59-
assert_eq!(command.last(), Some(&"echo hello".to_string()));
60-
if command
61-
.iter()
62-
.any(|arg| arg.eq_ignore_ascii_case("-Command"))
63-
{
64-
assert!(command.contains(&"-NoProfile".to_string()));
65-
}
65+
assert_eq!(
66+
command,
67+
shell.derive_exec_args("echo hello", /*use_login_shell*/ false)
68+
);
6669
Ok(())
6770
}
6871

@@ -71,6 +74,7 @@ fn test_get_command_respects_explicit_powershell_shell() -> anyhow::Result<()> {
7174
let json = r#"{"cmd": "echo hello", "shell": "powershell"}"#;
7275

7376
let args: ExecCommandArgs = parse_arguments(json)?;
77+
let shell = get_shell_by_model_provided_path(&PathBuf::from("powershell"));
7478

7579
assert_eq!(args.shell.as_deref(), Some("powershell"));
7680

@@ -82,7 +86,10 @@ fn test_get_command_respects_explicit_powershell_shell() -> anyhow::Result<()> {
8286
)
8387
.map_err(anyhow::Error::msg)?;
8488

85-
assert_eq!(command[2], "echo hello");
89+
assert_eq!(
90+
command,
91+
shell.derive_exec_args("echo hello", /*use_login_shell*/ false)
92+
);
8693
Ok(())
8794
}
8895

@@ -91,6 +98,7 @@ fn test_get_command_respects_explicit_cmd_shell() -> anyhow::Result<()> {
9198
let json = r#"{"cmd": "echo hello", "shell": "cmd"}"#;
9299

93100
let args: ExecCommandArgs = parse_arguments(json)?;
101+
let shell = get_shell_by_model_provided_path(&PathBuf::from("cmd"));
94102

95103
assert_eq!(args.shell.as_deref(), Some("cmd"));
96104

@@ -102,7 +110,32 @@ fn test_get_command_respects_explicit_cmd_shell() -> anyhow::Result<()> {
102110
)
103111
.map_err(anyhow::Error::msg)?;
104112

105-
assert_eq!(command[2], "echo hello");
113+
assert_eq!(
114+
command,
115+
shell.derive_exec_args("echo hello", /*use_login_shell*/ false)
116+
);
117+
Ok(())
118+
}
119+
120+
#[test]
121+
fn test_get_command_honors_explicit_login_when_allowed() -> anyhow::Result<()> {
122+
let json = r#"{"cmd": "echo hello", "login": true}"#;
123+
124+
let args: ExecCommandArgs = parse_arguments(json)?;
125+
let session_shell = Arc::new(default_user_shell());
126+
127+
let command = get_command(
128+
&args,
129+
session_shell.clone(),
130+
&UnifiedExecShellMode::Direct,
131+
/*allow_login_shell*/ true,
132+
)
133+
.map_err(anyhow::Error::msg)?;
134+
135+
assert_eq!(
136+
command,
137+
session_shell.derive_exec_args("echo hello", /*use_login_shell*/ true)
138+
);
106139
Ok(())
107140
}
108141

‎codex-rs/tools/src/local_tool.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ pub fn create_exec_command_tool(options: CommandToolOptions) -> ToolSpec {
7373
"login".to_string(),
7474
JsonSchema::Boolean {
7575
description: Some(
76-
"Whether to run the shell with -l/-i semantics. Defaults to true.".to_string(),
76+
"Whether to run the shell with -l/-i semantics. Defaults to false.".to_string(),
7777
),
7878
},
7979
);
@@ -197,7 +197,7 @@ Examples of valid command strings:
197197
)
198198
} else {
199199
r#"Runs a shell command and returns its output.
200-
- The arguments to `shell` will be passed to execvp(). Most terminal commands should be prefixed with ["bash", "-lc"].
200+
- The arguments to `shell` will be passed to execvp(). Most terminal commands should be prefixed with ["bash", "-c"].
201201
- Always set the `workdir` param when using the shell function. Do not use `cd` unless absolutely necessary."#
202202
.to_string()
203203
};
@@ -244,7 +244,7 @@ pub fn create_shell_command_tool(options: CommandToolOptions) -> ToolSpec {
244244
"login".to_string(),
245245
JsonSchema::Boolean {
246246
description: Some(
247-
"Whether to run the shell with login shell semantics. Defaults to true."
247+
"Whether to run the shell with login shell semantics. Defaults to false."
248248
.to_string(),
249249
),
250250
},

0 commit comments

Comments
 (0)