Use turn environments as shell authority

This commit is contained in:
pakrym-oai
2026-06-15 22:19:53 -07:00
parent 1e015884c5
commit 8060476514
22 changed files with 163 additions and 168 deletions
@@ -1,6 +1,5 @@
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
use codex_protocol::models::ManagedFileSystemPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
@@ -29,11 +28,11 @@ pub(crate) struct EnvironmentContext {
pub(crate) struct EnvironmentContextEnvironment {
pub(crate) id: String,
pub(crate) cwd: AbsolutePathBuf,
pub(crate) shell: String,
pub(crate) shell: Option<String>,
}
impl EnvironmentContextEnvironment {
fn legacy(cwd: AbsolutePathBuf, shell: String) -> Self {
fn legacy(cwd: AbsolutePathBuf, shell: Option<String>) -> Self {
Self {
id: String::new(),
cwd,
@@ -41,7 +40,7 @@ impl EnvironmentContextEnvironment {
}
}
fn from_turn_environments(environments: &[TurnEnvironment], shell: &Shell) -> Vec<Self> {
fn from_turn_environments(environments: &[TurnEnvironment]) -> Vec<Self> {
environments
.iter()
.map(|environment| Self {
@@ -50,8 +49,7 @@ impl EnvironmentContextEnvironment {
shell: environment
.shell
.as_ref()
.map(|shell| shell.name().to_string())
.unwrap_or_else(|| shell.name().to_string()),
.map(|shell| shell.name().to_string()),
})
.collect()
}
@@ -418,11 +416,10 @@ impl EnvironmentContext {
)
}
pub(crate) fn from_turn_context(turn_context: &TurnContext, shell: &Shell) -> Self {
pub(crate) fn from_turn_context(turn_context: &TurnContext) -> Self {
let mut context = Self::new(
EnvironmentContextEnvironment::from_turn_environments(
&turn_context.environments.turn_environments,
shell,
),
turn_context.current_date.clone(),
turn_context.timezone.clone(),
@@ -436,17 +433,14 @@ impl EnvironmentContext {
context
}
pub(crate) fn from_turn_context_item(
turn_context_item: &TurnContextItem,
shell: String,
) -> Self {
pub(crate) fn from_turn_context_item(turn_context_item: &TurnContextItem) -> Self {
let cwd = match AbsolutePathBuf::try_from(turn_context_item.cwd.clone()) {
Ok(cwd) => cwd,
Err(_) => AbsolutePathBuf::resolve_path_against_base(&turn_context_item.cwd, "/"),
};
Self::new_with_environments(
EnvironmentContextEnvironments::from_vec(vec![EnvironmentContextEnvironment::legacy(
cwd, shell,
cwd, None,
)]),
turn_context_item.current_date.clone(),
turn_context_item.timezone.clone(),
@@ -547,7 +541,9 @@ impl ContextualUserFragment for EnvironmentContext {
" <cwd>{}</cwd>",
environment.cwd.to_string_lossy()
));
lines.push(format!(" <shell>{}</shell>", environment.shell));
if let Some(shell) = &environment.shell {
lines.push(format!(" <shell>{shell}</shell>"));
}
}
EnvironmentContextEnvironments::Multiple(environments) => {
lines.push(" <environments>".to_string());
@@ -557,7 +553,9 @@ impl ContextualUserFragment for EnvironmentContext {
" <cwd>{}</cwd>",
environment.cwd.to_string_lossy()
));
lines.push(format!(" <shell>{}</shell>", environment.shell));
if let Some(shell) = &environment.shell {
lines.push(format!(" <shell>{shell}</shell>"));
}
lines.push(" </environment>".to_string());
}
lines.push(" </environments>".to_string());
@@ -37,7 +37,7 @@ fn serialize_workspace_write_environment_context() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: cwd.abs(),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
Some("2026-02-26".to_string()),
Some("America/Los_Angeles".to_string()),
@@ -68,7 +68,7 @@ fn serialize_environment_context_with_network() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_path_buf("/repo").abs(),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
Some("2026-02-26".to_string()),
Some("America/Los_Angeles".to_string()),
@@ -130,7 +130,7 @@ fn serialize_environment_context_with_full_filesystem_profile() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_path_buf("/repo").abs(),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -186,7 +186,7 @@ fn turn_context_item_filesystem_uses_workspace_roots_instead_of_cwd() {
summary: codex_protocol::config_types::ReasoningSummary::Auto,
};
let context = EnvironmentContext::from_turn_context_item(&item, fake_shell_name()).render();
let context = EnvironmentContext::from_turn_context_item(&item).render();
assert!(
context.contains(&format!(
@@ -235,7 +235,7 @@ fn equals_except_shell_compares_cwd() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_abs_path("/repo"),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -246,7 +246,7 @@ fn equals_except_shell_compares_cwd() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_abs_path("/repo"),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -262,7 +262,7 @@ fn equals_except_shell_compares_cwd_differences() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_abs_path("/repo1"),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -273,7 +273,7 @@ fn equals_except_shell_compares_cwd_differences() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_abs_path("/repo2"),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -290,7 +290,7 @@ fn equals_except_shell_ignores_shell() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_abs_path("/repo"),
shell: "bash".to_string(),
shell: Some("bash".to_string()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -301,7 +301,7 @@ fn equals_except_shell_ignores_shell() {
vec![EnvironmentContextEnvironment {
id: "other".to_string(),
cwd: test_abs_path("/repo"),
shell: "zsh".to_string(),
shell: Some("zsh".to_string()),
}],
/*current_date*/ None,
/*timezone*/ None,
@@ -318,7 +318,7 @@ fn serialize_environment_context_with_subagents() {
vec![EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: test_path_buf("/repo").abs(),
shell: fake_shell_name(),
shell: Some(fake_shell_name()),
}],
Some("2026-02-26".to_string()),
Some("America/Los_Angeles".to_string()),
@@ -352,12 +352,12 @@ fn serialize_environment_context_with_multiple_selected_environments() {
EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: local_cwd.abs(),
shell: "bash".to_string(),
shell: Some("bash".to_string()),
},
EnvironmentContextEnvironment {
id: "remote".to_string(),
cwd: remote_cwd.abs(),
shell: "bash".to_string(),
shell: Some("bash".to_string()),
},
],
Some("2026-02-26".to_string()),
@@ -397,12 +397,12 @@ fn serialize_environment_context_prefers_environment_shell_when_present() {
EnvironmentContextEnvironment {
id: "local".to_string(),
cwd: local_cwd.abs(),
shell: "powershell".to_string(),
shell: Some("powershell".to_string()),
},
EnvironmentContextEnvironment {
id: "remote".to_string(),
cwd: remote_cwd.abs(),
shell: "cmd".to_string(),
shell: Some("cmd".to_string()),
},
],
/*current_date*/ None,
+3 -6
View File
@@ -9,7 +9,6 @@ use crate::context::RealtimeStartInstructions;
use crate::context::RealtimeStartWithInstructions;
use crate::session::PreviousTurnSettings;
use crate::session::turn_context::TurnContext;
use crate::shell::Shell;
use codex_execpolicy::Policy;
use codex_features::Feature;
use codex_protocol::config_types::Personality;
@@ -21,15 +20,14 @@ use codex_protocol::protocol::TurnContextItem;
fn build_environment_update_item(
previous: Option<&TurnContextItem>,
next: &TurnContext,
shell: &Shell,
) -> Option<ResponseItem> {
if !next.config.include_environment_context {
return None;
}
let prev = previous?;
let prev_context = EnvironmentContext::from_turn_context_item(prev, shell.name().to_string());
let next_context = EnvironmentContext::from_turn_context(next, shell);
let prev_context = EnvironmentContext::from_turn_context_item(prev);
let next_context = EnvironmentContext::from_turn_context(next);
if prev_context.equals_except_shell(&next_context) {
return None;
}
@@ -211,7 +209,6 @@ pub(crate) fn build_settings_update_items(
previous: Option<&TurnContextItem>,
previous_turn_settings: Option<&PreviousTurnSettings>,
next: &TurnContext,
shell: &Shell,
exec_policy: &Policy,
personality_feature_enabled: bool,
) -> Vec<ResponseItem> {
@@ -219,7 +216,7 @@ pub(crate) fn build_settings_update_items(
// model-visible item emitted by build_initial_context. Persist the remaining
// inputs or add explicit replay events so fork/resume can diff everything
// deterministically.
let contextual_user_message = build_environment_update_item(previous, next, shell);
let contextual_user_message = build_environment_update_item(previous, next);
let developer_update_sections = [
// Keep model-switch instructions first so model-specific guidance is read before
// any other context diffs on this turn.
+1 -8
View File
@@ -1628,13 +1628,11 @@ impl Session {
let state = self.state.lock().await;
state.previous_turn_settings()
};
let shell = self.user_shell();
let exec_policy = self.services.exec_policy.current();
crate::context_manager::updates::build_settings_update_items(
reference_context_item,
previous_turn_settings.as_ref(),
current_context,
shell.as_ref(),
exec_policy.as_ref(),
self.features.enabled(Feature::Personality),
)
@@ -2991,14 +2989,13 @@ impl Session {
);
}
if turn_context.config.include_environment_context {
let shell = self.user_shell();
let subagents = self
.services
.agent_control
.format_environment_context_subagents(self.thread_id)
.await;
contextual_user_sections.push(
crate::context::EnvironmentContext::from_turn_context(turn_context, shell.as_ref())
crate::context::EnvironmentContext::from_turn_context(turn_context)
.with_subagents(subagents)
.render(),
);
@@ -3454,10 +3451,6 @@ impl Session {
self.services.hooks.load_full()
}
pub(crate) fn user_shell(&self) -> Arc<shell::Shell> {
Arc::clone(&self.services.user_shell)
}
pub(crate) async fn current_rollout_path(&self) -> anyhow::Result<Option<PathBuf>> {
let Some(live_thread) = self.live_thread() else {
return Ok(None);
+12 -6
View File
@@ -31,12 +31,18 @@ pub(super) async fn spawn_review_thread(
.models_manager
.list_models(RefreshStrategy::OnlineIfUncached)
.await;
let unified_exec_shell_mode = UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(review_features.get()),
crate::tools::tool_user_shell_type(sess.services.user_shell.as_ref()),
sess.services.shell_zsh_path.as_ref(),
sess.services.main_execve_wrapper_exe.as_ref(),
);
let unified_exec_shell_mode = parent_turn_context
.environments
.local()
.and_then(|environment| environment.shell.as_ref())
.map_or(UnifiedExecShellMode::Direct, |shell| {
UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(review_features.get()),
crate::tools::tool_shell_type(shell),
sess.services.shell_zsh_path.as_ref(),
sess.services.main_execve_wrapper_exe.as_ref(),
)
});
let review_prompt = resolved.prompt.clone();
let provider = parent_turn_context.provider.clone();
+1 -2
View File
@@ -813,7 +813,7 @@ impl Session {
};
let turn_environments = Arc::new(ThreadEnvironments::new(
environment_manager,
default_shell.clone(),
default_shell,
shell_snapshot,
inherited_environments.unwrap_or_default(),
));
@@ -989,7 +989,6 @@ impl Session {
analytics_events_client,
hooks: arc_swap::ArcSwap::from_pointee(hooks),
rollout_thread_trace,
user_shell: Arc::new(default_shell),
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
exec_policy,
auth_manager: Arc::clone(&auth_manager),
+13 -23
View File
@@ -4993,7 +4993,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
..HooksConfig::default()
})),
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
user_shell: Arc::new(default_user_shell()),
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
exec_policy,
auth_manager: auth_manager.clone(),
@@ -5062,7 +5061,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
session_configuration.provider.clone(),
&session_configuration,
config.multi_agent_version_from_features(),
services.user_shell.as_ref(),
services.shell_zsh_path.as_ref(),
services.main_execve_wrapper_exe.as_ref(),
per_turn_config,
@@ -7037,7 +7035,6 @@ where
..HooksConfig::default()
})),
rollout_thread_trace: codex_rollout_trace::ThreadTraceContext::disabled(),
user_shell: Arc::new(default_user_shell()),
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
exec_policy,
auth_manager: Arc::clone(&auth_manager),
@@ -7106,7 +7103,6 @@ where
session_configuration.provider.clone(),
&session_configuration,
config.multi_agent_version_from_features(),
services.user_shell.as_ref(),
services.shell_zsh_path.as_ref(),
services.main_execve_wrapper_exe.as_ref(),
per_turn_config,
@@ -7301,24 +7297,16 @@ async fn build_settings_update_items_emits_environment_item_for_network_changes(
}
#[tokio::test]
async fn environment_context_uses_session_shell_when_environment_shell_is_absent() {
let (mut session, mut turn_context) = make_session_and_context().await;
session.services.user_shell = Arc::new(crate::shell::Shell {
shell_type: crate::shell::ShellType::PowerShell,
shell_path: PathBuf::from("powershell"),
});
async fn environment_context_omits_shell_when_environment_shell_is_absent() {
let (_session, mut turn_context) = make_session_and_context().await;
for environment in &mut turn_context.environments.turn_environments {
environment.shell = None;
}
let session_shell = session.user_shell();
let environment_context = crate::context::EnvironmentContext::from_turn_context(
&turn_context,
session_shell.as_ref(),
)
.render();
let environment_context =
crate::context::EnvironmentContext::from_turn_context(&turn_context).render();
assert!(
environment_context.contains("<shell>powershell</shell>"),
!environment_context.contains("<shell>"),
"{environment_context}"
);
@@ -7332,11 +7320,8 @@ async fn environment_context_uses_session_shell_when_environment_shell_is_absent
shell_path: PathBuf::from("cmd"),
});
let environment_context = crate::context::EnvironmentContext::from_turn_context(
&turn_context,
session_shell.as_ref(),
)
.render();
let environment_context =
crate::context::EnvironmentContext::from_turn_context(&turn_context).render();
assert!(
environment_context.contains("<shell>cmd</shell>"),
"{environment_context}"
@@ -9888,7 +9873,12 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() {
let turn_context_mut = Arc::get_mut(&mut turn_context).expect("unique thread settings Arc");
turn_context_mut.permission_profile = PermissionProfile::Disabled;
let command = session.user_shell().derive_exec_args(
let shell = turn_context
.environments
.single_local_environment()
.and_then(|environment| environment.shell.as_ref())
.expect("local environment shell");
let command = shell.derive_exec_args(
command_script,
turn_context.config.permissions.allow_login_shell,
);
+13 -8
View File
@@ -527,7 +527,6 @@ impl Session {
provider: ModelProviderInfo,
session_configuration: &SessionConfiguration,
multi_agent_version: MultiAgentVersion,
user_shell: &shell::Shell,
shell_zsh_path: Option<&PathBuf>,
main_execve_wrapper_exe: Option<&PathBuf>,
per_turn_config: Config,
@@ -552,12 +551,19 @@ impl Session {
let provider_for_context = create_model_provider(provider, auth_manager);
let session_telemetry_for_context = session_telemetry;
let available_models = models_manager.try_list_models().unwrap_or_default();
let unified_exec_shell_mode = UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(per_turn_config.features.get()),
crate::tools::tool_user_shell_type(user_shell),
shell_zsh_path,
main_execve_wrapper_exe,
);
let unified_exec_shell_mode = environments
.local()
.and_then(|environment| environment.shell.as_ref())
.map_or(UnifiedExecShellMode::Direct, |shell| {
UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(
per_turn_config.features.get(),
),
crate::tools::tool_shell_type(shell),
shell_zsh_path,
main_execve_wrapper_exe,
)
});
let mut per_turn_config = per_turn_config;
let tool_mode = model_info.tool_mode.unwrap_or_else(|| {
@@ -805,7 +811,6 @@ impl Session {
session_configuration.provider.clone(),
&session_configuration,
multi_agent_version,
self.services.user_shell.as_ref(),
self.services.shell_zsh_path.as_ref(),
self.services.main_execve_wrapper_exe.as_ref(),
per_turn_config,
-1
View File
@@ -51,7 +51,6 @@ pub(crate) struct SessionServices {
pub(crate) analytics_events_client: AnalyticsEventsClient,
pub(crate) hooks: ArcSwap<Hooks>,
pub(crate) rollout_thread_trace: ThreadTraceContext,
pub(crate) user_shell: Arc<crate::shell::Shell>,
pub(crate) show_raw_agent_reasoning: bool,
pub(crate) exec_policy: Arc<ExecPolicyManager>,
pub(crate) auth_manager: Arc<AuthManager>,
+1 -1
View File
@@ -127,7 +127,7 @@ pub(crate) async fn execute_user_shell_command(
let Some((turn_environment, environment_shell)) = turn_context
.environments
.local()
.single_local_environment()
.and_then(|environment| environment.shell.as_ref().map(|shell| (environment, shell)))
else {
send_user_shell_error(
+4 -10
View File
@@ -8,7 +8,7 @@ use crate::exec::ExecParams;
use crate::exec_policy::ExecApprovalRequest;
use crate::function_tool::FunctionCallError;
use crate::session::turn_context::TurnContext;
use crate::shell::ShellType;
use crate::session::turn_context::TurnEnvironment;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolPayload;
use crate::tools::events::ToolEmitter;
@@ -45,9 +45,9 @@ fn shell_command_payload_command(payload: &ToolPayload) -> Option<String> {
struct RunExecLikeArgs {
tool_name: ToolName,
exec_params: ExecParams,
turn_environment: TurnEnvironment,
cancellation_token: CancellationToken,
hook_command: String,
shell_type: Option<ShellType>,
additional_permissions: Option<AdditionalPermissionProfile>,
prefix_rule: Option<Vec<String>>,
session: Arc<crate::session::session::Session>,
@@ -61,9 +61,9 @@ async fn run_exec_like(args: RunExecLikeArgs) -> Result<FunctionToolOutput, Func
let RunExecLikeArgs {
tool_name,
exec_params,
turn_environment,
cancellation_token,
hook_command,
shell_type,
additional_permissions,
prefix_rule,
session,
@@ -73,11 +73,6 @@ async fn run_exec_like(args: RunExecLikeArgs) -> Result<FunctionToolOutput, Func
shell_runtime_backend,
} = args;
let Some(turn_environment) = turn.environments.primary() else {
return Err(FunctionCallError::RespondToModel(
"shell is unavailable in this session".to_string(),
));
};
let fs = turn_environment.environment.get_filesystem();
let explicit_env_overrides = turn.shell_environment_policy.r#set.clone();
@@ -179,8 +174,7 @@ async fn run_exec_like(args: RunExecLikeArgs) -> Result<FunctionToolOutput, Func
let req = ShellRequest {
command: exec_params.command.clone(),
turn_environment: turn_environment.clone(),
shell_type,
turn_environment,
hook_command,
cwd: exec_params.cwd.clone(),
timeout_ms: exec_params.expiration.timeout_ms(),
@@ -9,6 +9,7 @@ use crate::exec_env::create_env;
use crate::function_tool::FunctionCallError;
use crate::maybe_emit_implicit_skill_invocation;
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::shell::Shell;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
@@ -84,16 +85,19 @@ impl ShellCommandHandler {
pub(super) fn to_exec_params(
params: &ShellCommandToolCallParams,
session: &crate::session::session::Session,
turn_environment: &TurnEnvironment,
turn_context: &TurnContext,
thread_id: ThreadId,
cwd: codex_utils_absolute_path::AbsolutePathBuf,
allow_login_shell: bool,
) -> Result<ExecParams, FunctionCallError> {
let shell = session.user_shell();
let Some(shell) = turn_environment.shell.as_ref() else {
return Err(FunctionCallError::RespondToModel(
"shell is unavailable in this session".to_string(),
));
};
let use_login_shell = Self::resolve_use_login_shell(params.login, allow_login_shell)?;
let command = Self::base_command(shell.as_ref(), &params.command, use_login_shell);
#[allow(deprecated)]
let cwd = turn_context.resolve_path(params.workdir.clone());
let command = Self::base_command(shell, &params.command, use_login_shell);
Ok(ExecParams {
command,
@@ -167,33 +171,35 @@ impl ShellCommandHandler {
)));
};
#[allow(deprecated)]
let cwd = resolve_workdir_base_path(&arguments, &turn.cwd)?;
let Some(turn_environment) = turn.environments.single_local_environment().cloned() else {
return Err(FunctionCallError::RespondToModel(
"shell is unavailable in this session".to_string(),
));
};
let cwd = resolve_workdir_base_path(&arguments, turn_environment.cwd())?;
let params: ShellCommandToolCallParams = parse_arguments_with_base_path(&arguments, &cwd)?;
#[allow(deprecated)]
let workdir = turn.resolve_path(params.workdir.clone());
maybe_emit_implicit_skill_invocation(
session.as_ref(),
turn.as_ref(),
&params.command,
&workdir,
&cwd,
)
.await;
let prefix_rule = params.prefix_rule.clone();
let exec_params = Self::to_exec_params(
&params,
session.as_ref(),
&turn_environment,
turn.as_ref(),
session.thread_id,
cwd,
turn.config.permissions.allow_login_shell,
)?;
let shell_type = Some(session.user_shell().shell_type);
run_exec_like(RunExecLikeArgs {
tool_name,
exec_params,
turn_environment,
cancellation_token,
hook_command: params.command,
shell_type,
additional_permissions: params.additional_permissions.clone(),
prefix_rule,
session,
@@ -67,8 +67,12 @@ fn assert_safe(shell: &Shell, command: &str) {
}
#[tokio::test]
async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_context() {
async fn shell_command_handler_to_exec_params_uses_environment_shell_and_turn_context() {
let (session, turn_context) = make_session_and_context().await;
let turn_environment = turn_context
.environments
.single_local_environment()
.expect("single local environment");
let command = "echo hello".to_string();
let workdir = Some("subdir".to_string());
@@ -77,11 +81,14 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
let sandbox_permissions = SandboxPermissions::RequireEscalated;
let justification = Some("because tests".to_string());
let expected_command = session
.user_shell()
let expected_command = turn_environment
.shell
.as_ref()
.expect("environment shell")
.derive_exec_args(&command, /*use_login_shell*/ true);
#[allow(deprecated)]
let expected_cwd = turn_context.resolve_path(workdir.clone());
let expected_cwd = turn_environment
.cwd()
.join(workdir.as_deref().expect("workdir"));
let expected_env = create_env(
&turn_context.shell_environment_policy,
Some(session.thread_id),
@@ -100,9 +107,10 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
let exec_params = ShellCommandHandler::to_exec_params(
&params,
&session,
turn_environment,
&turn_context,
session.thread_id,
expected_cwd.clone(),
/*allow_login_shell*/ true,
)
.expect("login shells should be allowed");
@@ -149,6 +157,10 @@ fn shell_command_handler_respects_explicit_login_flag() {
#[tokio::test]
async fn shell_command_handler_defaults_to_non_login_when_disallowed() {
let (session, turn_context) = make_session_and_context().await;
let turn_environment = turn_context
.environments
.single_local_environment()
.expect("single local environment");
let params = ShellCommandToolCallParams {
command: "echo hello".to_string(),
workdir: None,
@@ -162,17 +174,20 @@ async fn shell_command_handler_defaults_to_non_login_when_disallowed() {
let exec_params = ShellCommandHandler::to_exec_params(
&params,
&session,
turn_environment,
&turn_context,
session.thread_id,
turn_environment.cwd().clone(),
/*allow_login_shell*/ false,
)
.expect("non-login shells should still be allowed");
assert_eq!(
exec_params.command,
session
.user_shell()
turn_environment
.shell
.as_ref()
.expect("environment shell")
.derive_exec_args("echo hello", /*use_login_shell*/ false)
);
}
@@ -12,7 +12,6 @@ use codex_protocol::models::AdditionalPermissionProfile;
use codex_tools::UnifiedExecShellMode;
use serde::Deserialize;
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(test)]
use crate::tools::handlers::parse_arguments;
@@ -96,7 +95,7 @@ fn post_unified_exec_tool_use_payload(
pub(crate) fn get_command(
args: &ExecCommandArgs,
session_shell: Arc<Shell>,
environment_shell: Option<&Shell>,
shell_mode: &UnifiedExecShellMode,
allow_login_shell: bool,
) -> Result<ResolvedCommand, String> {
@@ -116,7 +115,10 @@ pub(crate) fn get_command(
.shell
.as_ref()
.map(|shell_str| get_shell_by_model_provided_path(&PathBuf::from(shell_str)));
let shell = model_shell.as_ref().unwrap_or(session_shell.as_ref());
let shell = model_shell
.as_ref()
.or(environment_shell)
.ok_or_else(|| "shell is unavailable in this environment".to_string())?;
Ok(ResolvedCommand {
command: shell.derive_exec_args(&args.cmd, use_login_shell),
shell_type: shell.shell_type,
@@ -151,16 +151,9 @@ impl ExecCommandHandler {
let process_id = manager.allocate_process_id().await;
let shell_mode =
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
// Remote environments may use a different OS and must build commands with their native
// shell; fall back to the session shell when the environment did not report one.
let shell = turn_environment
.shell
.clone()
.map(Arc::new)
.unwrap_or_else(|| session.user_shell());
let resolved_command = get_command(
&args,
shell,
turn_environment.shell.as_ref(),
&shell_mode,
turn.config.permissions.allow_login_shell,
)
@@ -40,7 +40,7 @@ async fn invocation_for_payload(
}
#[test]
fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()> {
fn test_get_command_uses_environment_shell_when_unspecified() -> anyhow::Result<()> {
let json = r#"{"cmd": "echo hello"}"#;
let args: ExecCommandArgs = parse_arguments(json)?;
@@ -49,7 +49,7 @@ fn test_get_command_uses_default_shell_when_unspecified() -> anyhow::Result<()>
let resolved = get_command(
&args,
Arc::new(default_user_shell()),
Some(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ true,
)
@@ -71,7 +71,7 @@ fn test_get_command_respects_explicit_bash_shell() -> anyhow::Result<()> {
let resolved = get_command(
&args,
Arc::new(default_user_shell()),
Some(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ true,
)
@@ -112,7 +112,7 @@ fn test_get_command_respects_explicit_powershell_shell() -> anyhow::Result<()> {
let resolved = get_command(
&args,
Arc::new(default_user_shell()),
Some(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ true,
)
@@ -134,7 +134,7 @@ fn test_get_command_respects_explicit_cmd_shell() -> anyhow::Result<()> {
let resolved = get_command(
&args,
Arc::new(default_user_shell()),
Some(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ true,
)
@@ -152,7 +152,7 @@ fn test_get_command_rejects_explicit_login_when_disallowed() -> anyhow::Result<(
let args: ExecCommandArgs = parse_arguments(json)?;
let err = get_command(
&args,
Arc::new(default_user_shell()),
Some(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ false,
)
@@ -183,13 +183,8 @@ fn test_get_command_rejects_explicit_shell_in_zsh_fork_mode() -> anyhow::Result<
})?,
});
let err = get_command(
&args,
Arc::new(default_user_shell()),
&shell_mode,
/*allow_login_shell*/ true,
)
.expect_err("explicit shell should be rejected");
let err = get_command(&args, None, &shell_mode, /*allow_login_shell*/ true)
.expect_err("explicit shell should be rejected");
assert!(
err.contains("`shell` is not supported for local zsh-fork exec"),
+2 -4
View File
@@ -45,10 +45,8 @@ pub(crate) fn flat_tool_name(tool_name: &ToolName) -> Cow<'_, str> {
}
}
pub(crate) fn tool_user_shell_type(
user_shell: &crate::shell::Shell,
) -> codex_tools::ToolUserShellType {
match user_shell.shell_type {
pub(crate) fn tool_shell_type(shell: &crate::shell::Shell) -> codex_tools::ToolUserShellType {
match shell.shell_type {
crate::shell::ShellType::Zsh => codex_tools::ToolUserShellType::Zsh,
crate::shell::ShellType::Bash => codex_tools::ToolUserShellType::Bash,
crate::shell::ShellType::PowerShell => codex_tools::ToolUserShellType::PowerShell,
+4 -4
View File
@@ -226,12 +226,12 @@ pub(crate) fn disable_powershell_profile_for_elevated_windows_sandbox(
/// POSIX-only helper: for commands produced by `Shell::derive_exec_args`
/// for Bash/Zsh/sh of the form `[shell_path, "-lc", "<script>"]`, and
/// when a snapshot is configured on the session shell, rewrite the argv
/// when a snapshot is configured on the environment shell, rewrite the argv
/// to a single non-login shell that sources the snapshot before running
/// the original script:
///
/// shell -lc "<script>"
/// => user_shell -c ". SNAPSHOT (best effort); exec shell -c <script>"
/// => environment_shell -c ". SNAPSHOT (best effort); exec shell -c <script>"
///
/// This wrapper script uses POSIX constructs (`if`, `.`, `exec`) so it can
/// be run by Bash/Zsh/sh. On non-matching commands, or when command cwd does
@@ -249,7 +249,7 @@ pub(crate) fn disable_powershell_profile_for_elevated_windows_sandbox(
/// PATH unless the user explicitly overrides `PATH`.
pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
command: &[String],
session_shell: &Shell,
shell: &Shell,
shell_snapshot: Option<&AbsolutePathBuf>,
explicit_env_overrides: &HashMap<String, String>,
env: &HashMap<String, String>,
@@ -277,7 +277,7 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
}
let snapshot_path = snapshot.to_string_lossy();
let shell_path = session_shell.shell_path.to_string_lossy();
let shell_path = shell.shell_path.to_string_lossy();
let original_shell = shell_single_quote(&command[0]);
let original_script = shell_single_quote(&command[2]);
let snapshot_path = shell_single_quote(snapshot_path.as_ref());
+6 -8
View File
@@ -55,7 +55,6 @@ use tokio_util::sync::CancellationToken;
pub struct ShellRequest {
pub command: Vec<String>,
pub turn_environment: TurnEnvironment,
pub shell_type: Option<ShellType>,
pub hook_command: String,
pub cwd: AbsolutePathBuf,
pub timeout_ms: Option<u64>,
@@ -241,12 +240,11 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
attempt: &SandboxAttempt<'_>,
ctx: &ToolCtx,
) -> Result<ExecToolCallOutput, ToolError> {
let session_shell = ctx.session.user_shell();
let shell = req
.turn_environment
.shell
.as_ref()
.unwrap_or(session_shell.as_ref());
let Some(shell) = req.turn_environment.shell.as_ref() else {
return Err(ToolError::Rejected(
"shell is unavailable in this session".to_string(),
));
};
let shell_snapshot_location = req.turn_environment.shell_snapshot(&req.cwd);
let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions();
let sandbox_permissions = sandbox_permissions_preserving_denied_reads(
@@ -284,7 +282,7 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
);
let command = disable_powershell_profile_for_elevated_windows_sandbox(
&command,
req.shell_type.as_ref(),
Some(&shell.shell_type),
attempt.sandbox,
attempt.windows_sandbox_level,
);
@@ -116,8 +116,14 @@ pub(super) async fn try_run_zsh_fork(
tracing::warn!("ZshFork backend specified, but ShellZshFork feature is not enabled.");
return Ok(None);
}
if !matches!(ctx.session.user_shell().shell_type, ShellType::Zsh) {
tracing::warn!("ZshFork backend specified, but user shell is not Zsh.");
if !matches!(
req.turn_environment
.shell
.as_ref()
.map(|shell| shell.shell_type),
Some(ShellType::Zsh)
) {
tracing::warn!("ZshFork backend specified, but environment shell is not Zsh.");
return Ok(None);
}
@@ -528,8 +528,11 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul
.context("build trusted hook state")?,
);
let mut hook_shell_argv = session
.user_shell()
let mut hook_shell_argv = turn_context
.environments
.single_local_environment()
.and_then(|environment| environment.shell.as_ref())
.expect("local environment shell")
.derive_exec_args("", /*use_login_shell*/ false);
let hook_shell_program = hook_shell_argv.remove(0);
let _ = hook_shell_argv.pop();
@@ -262,12 +262,6 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
ctx: &ToolCtx,
) -> Result<UnifiedExecProcess, ToolError> {
let base_command = &req.command;
let session_shell = ctx.session.user_shell();
let shell = req
.turn_environment
.shell
.as_ref()
.unwrap_or(session_shell.as_ref());
let shell_snapshot_location = req.turn_environment.shell_snapshot(&req.cwd);
let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions();
let launch_sandbox_permissions = sandbox_permissions_preserving_denied_reads(
@@ -306,7 +300,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
let runtime_path_prepends = RuntimePathPrepends::default();
let command = if environment_is_remote {
base_command.to_vec()
} else {
} else if let Some(shell) = req.turn_environment.shell.as_ref() {
maybe_wrap_shell_lc_with_snapshot(
base_command,
shell,
@@ -315,6 +309,10 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
&env,
&runtime_path_prepends,
)
} else {
return Err(ToolError::Rejected(
"shell is unavailable in this environment".to_string(),
));
};
let command = disable_powershell_profile_for_elevated_windows_sandbox(
&command,