Make turn environment shell access fallible

This commit is contained in:
pakrym-oai
2026-06-15 23:02:12 -07:00
parent 8060476514
commit ef025c5384
21 changed files with 135 additions and 99 deletions
+1 -1
View File
@@ -254,7 +254,7 @@ fn resolved_local_environments<const N: usize>(
.expect("local environment"),
),
cwd,
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
)
})
.collect(),
@@ -47,8 +47,8 @@ impl EnvironmentContextEnvironment {
id: environment.environment_id.clone(),
cwd: environment.cwd().clone(),
shell: environment
.shell
.as_ref()
.shell()
.ok()
.map(|shell| shell.name().to_string()),
})
.collect()
+35 -29
View File
@@ -137,23 +137,16 @@ impl ThreadEnvironments {
})?;
let shell = if environment.is_remote() {
match environment.info().await {
Ok(info) => match Shell::from_environment_shell_info(info.shell) {
Ok(shell) => Some(shell),
Err(err) => {
tracing::warn!(
"failed to resolve shell for environment `{environment_id}`: {err}"
);
None
}
},
Err(err) => {
tracing::warn!("failed to get info for environment `{environment_id}`: {err}");
None
}
Ok(info) => Shell::from_environment_shell_info(info.shell)
.map_err(|err| format!("failed to resolve shell: {err}")),
Err(err) => Err(format!("failed to get environment info: {err}")),
}
} else {
Some(local_shell.clone())
Ok(local_shell.clone())
};
if let Err(reason) = &shell {
tracing::warn!("shell is unavailable for environment `{environment_id}`: {reason}");
}
let mut turn_environment = TurnEnvironment::new(
environment_id,
environment,
@@ -354,7 +347,7 @@ url = "ws://127.0.0.1:8765"
assert_eq!(
snapshot
.primary()
.and_then(|environment| environment.shell.as_ref()),
.and_then(|environment| environment.shell().ok()),
Some(&local_shell)
);
}
@@ -409,19 +402,21 @@ url = "ws://127.0.0.1:8765"
"local"
);
assert_eq!(
resolved.primary().expect("primary environment").shell,
Some(
Shell::from_environment_shell_info(
manager
.get_environment("local")
.expect("local environment")
.info()
.await
.expect("local environment info")
.shell
)
.expect("resolved shell")
resolved
.primary()
.expect("primary environment")
.shell()
.expect("primary environment shell"),
&Shell::from_environment_shell_info(
manager
.get_environment("local")
.expect("local environment")
.info()
.await
.expect("local environment info")
.shell
)
.expect("resolved shell")
);
}
@@ -529,6 +524,17 @@ url = "ws://127.0.0.1:8765"
}]);
let changed_snapshot = initial.snapshot().await;
let shell_error = initial_snapshot
.primary()
.expect("initial environment")
.shell()
.expect_err("unreachable remote shell should be unavailable");
assert!(
shell_error
.to_string()
.contains("failed to get environment info"),
"unexpected shell error: {shell_error}"
);
assert!(Arc::ptr_eq(
&initial_snapshot
.primary()
@@ -574,7 +580,7 @@ url = "ws://127.0.0.1:8765"
REMOTE_ENVIRONMENT_ID.to_string(),
remote_environment.clone(),
cwd.clone(),
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
)],
};
let multiple = TurnEnvironmentSnapshot {
@@ -584,7 +590,7 @@ url = "ws://127.0.0.1:8765"
REMOTE_ENVIRONMENT_ID.to_string(),
remote_environment,
cwd.clone(),
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
),
],
};
+1 -1
View File
@@ -3526,7 +3526,7 @@ async fn build_hooks_for_config(
environment: Option<&TurnEnvironment>,
) -> Hooks {
let (hook_shell_program, hook_shell_argv) = environment
.and_then(|environment| environment.shell.as_ref())
.and_then(|environment| environment.shell().ok())
.map(|shell| {
let mut argv = shell.derive_exec_args("", /*use_login_shell*/ false);
let program = argv.remove(0);
+1 -1
View File
@@ -34,7 +34,7 @@ pub(super) async fn spawn_review_thread(
let unified_exec_shell_mode = parent_turn_context
.environments
.local()
.and_then(|environment| environment.shell.as_ref())
.and_then(|environment| environment.shell().ok())
.map_or(UnifiedExecShellMode::Direct, |shell| {
UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(review_features.get()),
+26 -9
View File
@@ -5692,11 +5692,15 @@ async fn request_permissions_tool_resolves_relative_paths_against_selected_envir
}))
.expect("test setup should allow updating approval policy");
let current_environment = turn_context_mut.environments.turn_environments[0].clone();
let current_shell = current_environment
.shell()
.cloned()
.map_err(ToString::to_string);
turn_context_mut.environments.turn_environments[0] = TurnEnvironment::new(
"remote".to_string(),
current_environment.environment,
environment_cwd.clone(),
current_environment.shell,
current_shell,
);
let call_id = "call-1".to_string();
@@ -6321,7 +6325,7 @@ async fn primary_environment_uses_first_turn_environment() {
"second".to_string(),
Arc::clone(&first_environment.environment),
second_cwd.clone(),
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
));
assert_eq!(
@@ -7300,7 +7304,12 @@ async fn build_settings_update_items_emits_environment_item_for_network_changes(
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;
*environment = TurnEnvironment::new(
environment.environment_id.clone(),
Arc::clone(&environment.environment),
environment.cwd().clone(),
Err("not configured for test".to_string()),
);
}
let environment_context =
@@ -7313,12 +7322,19 @@ async fn environment_context_omits_shell_when_environment_shell_is_absent() {
let primary_environment = turn_context
.environments
.turn_environments
.first_mut()
.first()
.cloned()
.expect("primary environment");
primary_environment.shell = Some(crate::shell::Shell {
shell_type: crate::shell::ShellType::Cmd,
shell_path: PathBuf::from("cmd"),
});
let primary_cwd = primary_environment.cwd().clone();
turn_context.environments.turn_environments[0] = TurnEnvironment::new(
primary_environment.environment_id,
primary_environment.environment,
primary_cwd,
Ok(crate::shell::Shell {
shell_type: crate::shell::ShellType::Cmd,
shell_path: PathBuf::from("cmd"),
}),
);
let environment_context =
crate::context::EnvironmentContext::from_turn_context(&turn_context).render();
@@ -9876,7 +9892,8 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() {
let shell = turn_context
.environments
.single_local_environment()
.and_then(|environment| environment.shell.as_ref())
.expect("single local environment")
.shell()
.expect("local environment shell");
let command = shell.derive_exec_args(
command_script,
+18 -3
View File
@@ -45,6 +45,13 @@ impl TurnSkillsContext {
pub(crate) type ShellSnapshotTask = Shared<BoxFuture<'static, Option<Arc<ShellSnapshotFile>>>>;
#[derive(Clone, Debug, thiserror::Error)]
#[error("shell is unavailable in environment `{environment_id}`: {reason}")]
pub(crate) struct ShellUnavailableError {
environment_id: String,
reason: String,
}
#[derive(Clone)]
pub(crate) struct TurnEnvironment {
pub(crate) environment_id: String,
@@ -56,7 +63,7 @@ pub(crate) struct TurnEnvironment {
// process-launch boundaries and remove this paired migration state.
cwd: AbsolutePathBuf,
cwd_uri: PathUri,
pub(crate) shell: Option<shell::Shell>,
shell: Result<shell::Shell, ShellUnavailableError>,
pub(crate) shell_snapshot: ShellSnapshotTask,
}
@@ -65,9 +72,13 @@ impl TurnEnvironment {
environment_id: String,
environment: Arc<Environment>,
cwd: AbsolutePathBuf,
shell: Option<shell::Shell>,
shell: Result<shell::Shell, String>,
) -> Self {
let cwd_uri = PathUri::from_abs_path(&cwd);
let shell = shell.map_err(|reason| ShellUnavailableError {
environment_id: environment_id.clone(),
reason,
});
Self {
environment_id,
environment,
@@ -96,6 +107,10 @@ impl TurnEnvironment {
&self.cwd_uri
}
pub(crate) fn shell(&self) -> Result<&shell::Shell, &ShellUnavailableError> {
self.shell.as_ref()
}
pub(crate) fn selection(&self) -> TurnEnvironmentSelection {
TurnEnvironmentSelection {
environment_id: self.environment_id.clone(),
@@ -553,7 +568,7 @@ impl Session {
let available_models = models_manager.try_list_models().unwrap_or_default();
let unified_exec_shell_mode = environments
.local()
.and_then(|environment| environment.shell.as_ref())
.and_then(|environment| environment.shell().ok())
.map_or(UnifiedExecShellMode::Direct, |shell| {
UnifiedExecShellMode::for_session(
codex_tools::unified_exec_feature_mode_for_features(
+1 -1
View File
@@ -75,7 +75,7 @@ impl ShellSnapshot {
return None;
}
let shell = environment.shell.clone()?;
let shell = environment.shell().ok()?.clone();
let cwd = environment.cwd().clone();
Self::build_for_cwd(Arc::clone(config), cwd, shell).await
}
+8 -5
View File
@@ -125,11 +125,7 @@ pub(crate) async fn execute_user_shell_command(
session.send_event(turn_context.as_ref(), event).await;
}
let Some((turn_environment, environment_shell)) = turn_context
.environments
.single_local_environment()
.and_then(|environment| environment.shell.as_ref().map(|shell| (environment, shell)))
else {
let Some(turn_environment) = turn_context.environments.single_local_environment() else {
send_user_shell_error(
&session,
turn_context.as_ref(),
@@ -138,6 +134,13 @@ pub(crate) async fn execute_user_shell_command(
.await;
return;
};
let environment_shell = match turn_environment.shell() {
Ok(shell) => shell,
Err(err) => {
send_user_shell_error(&session, turn_context.as_ref(), &err.to_string()).await;
return;
}
};
// Execute the user's script under the environment's shell; this
// allows commands that use shell features (pipes, &&, redirects, etc.).
@@ -91,11 +91,9 @@ impl ShellCommandHandler {
cwd: codex_utils_absolute_path::AbsolutePathBuf,
allow_login_shell: bool,
) -> Result<ExecParams, FunctionCallError> {
let Some(shell) = turn_environment.shell.as_ref() else {
return Err(FunctionCallError::RespondToModel(
"shell is unavailable in this session".to_string(),
));
};
let shell = turn_environment
.shell()
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?;
let use_login_shell = Self::resolve_use_login_shell(params.login, allow_login_shell)?;
let command = Self::base_command(shell, &params.command, use_login_shell);
@@ -82,8 +82,7 @@ async fn shell_command_handler_to_exec_params_uses_environment_shell_and_turn_co
let justification = Some("because tests".to_string());
let expected_command = turn_environment
.shell
.as_ref()
.shell()
.expect("environment shell")
.derive_exec_args(&command, /*use_login_shell*/ true);
let expected_cwd = turn_environment
@@ -185,8 +184,7 @@ async fn shell_command_handler_defaults_to_non_login_when_disallowed() {
assert_eq!(
exec_params.command,
turn_environment
.shell
.as_ref()
.shell()
.expect("environment shell")
.derive_exec_args("echo hello", /*use_login_shell*/ false)
);
@@ -1,4 +1,5 @@
use crate::sandboxing::SandboxPermissions;
use crate::session::turn_context::ShellUnavailableError;
use crate::shell::Shell;
use crate::shell::ShellType;
use crate::shell::get_shell_by_model_provided_path;
@@ -95,7 +96,7 @@ fn post_unified_exec_tool_use_payload(
pub(crate) fn get_command(
args: &ExecCommandArgs,
environment_shell: Option<&Shell>,
environment_shell: Result<&Shell, &ShellUnavailableError>,
shell_mode: &UnifiedExecShellMode,
allow_login_shell: bool,
) -> Result<ResolvedCommand, String> {
@@ -115,10 +116,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()
.or(environment_shell)
.ok_or_else(|| "shell is unavailable in this environment".to_string())?;
let shell = match model_shell.as_ref() {
Some(shell) => shell,
None => environment_shell.map_err(ToString::to_string)?,
};
Ok(ResolvedCommand {
command: shell.derive_exec_args(&args.cmd, use_login_shell),
shell_type: shell.shell_type,
@@ -153,7 +153,7 @@ impl ExecCommandHandler {
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
let resolved_command = get_command(
&args,
turn_environment.shell.as_ref(),
turn_environment.shell(),
&shell_mode,
turn.config.permissions.allow_login_shell,
)
@@ -49,7 +49,7 @@ fn test_get_command_uses_environment_shell_when_unspecified() -> anyhow::Result<
let resolved = get_command(
&args,
Some(&default_user_shell()),
Ok(&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,
Some(&default_user_shell()),
Ok(&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,
Some(&default_user_shell()),
Ok(&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,
Some(&default_user_shell()),
Ok(&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,
Some(&default_user_shell()),
Ok(&default_user_shell()),
&UnifiedExecShellMode::Direct,
/*allow_login_shell*/ false,
)
@@ -183,8 +183,13 @@ fn test_get_command_rejects_explicit_shell_in_zsh_fork_mode() -> anyhow::Result<
})?,
});
let err = get_command(&args, None, &shell_mode, /*allow_login_shell*/ true)
.expect_err("explicit shell should be rejected");
let err = get_command(
&args,
Ok(&default_user_shell()),
&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"),
@@ -285,12 +285,9 @@ mod tests {
.first()
.cloned()
.expect("default local turn environment");
turn.environments.turn_environments[0] = TurnEnvironment::new(
current.environment_id,
current.environment,
cwd,
current.shell,
);
let shell = current.shell().cloned().map_err(ToString::to_string);
turn.environments.turn_environments[0] =
TurnEnvironment::new(current.environment_id, current.environment, cwd, shell);
}
#[test]
@@ -20,7 +20,7 @@ fn test_turn_environment(environment_id: &str) -> crate::session::turn_context::
environment_id.to_string(),
std::sync::Arc::new(codex_exec_server::Environment::default_for_tests()),
std::env::temp_dir().abs(),
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
)
}
+4 -5
View File
@@ -240,11 +240,10 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
attempt: &SandboxAttempt<'_>,
ctx: &ToolCtx,
) -> Result<ExecToolCallOutput, ToolError> {
let Some(shell) = req.turn_environment.shell.as_ref() else {
return Err(ToolError::Rejected(
"shell is unavailable in this session".to_string(),
));
};
let shell = req
.turn_environment
.shell()
.map_err(|err| ToolError::Rejected(err.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(
@@ -117,11 +117,8 @@ pub(super) async fn try_run_zsh_fork(
return Ok(None);
}
if !matches!(
req.turn_environment
.shell
.as_ref()
.map(|shell| shell.shell_type),
Some(ShellType::Zsh)
req.turn_environment.shell().map(|shell| shell.shell_type),
Ok(ShellType::Zsh)
) {
tracing::warn!("ZshFork backend specified, but environment shell is not Zsh.");
return Ok(None);
@@ -531,7 +531,7 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul
let mut hook_shell_argv = turn_context
.environments
.single_local_environment()
.and_then(|environment| environment.shell.as_ref())
.and_then(|environment| environment.shell().ok())
.expect("local environment shell")
.derive_exec_args("", /*use_login_shell*/ false);
let hook_shell_program = hook_shell_argv.remove(0);
@@ -300,7 +300,11 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
let runtime_path_prepends = RuntimePathPrepends::default();
let command = if environment_is_remote {
base_command.to_vec()
} else if let Some(shell) = req.turn_environment.shell.as_ref() {
} else {
let shell = req
.turn_environment
.shell()
.map_err(|err| ToolError::Rejected(err.to_string()))?;
maybe_wrap_shell_lc_with_snapshot(
base_command,
shell,
@@ -309,10 +313,6 @@ 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,
@@ -434,7 +434,7 @@ mod tests {
LOCAL_ENVIRONMENT_ID.to_string(),
Arc::new(Environment::default_for_tests()),
cwd,
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
)
}
+1 -1
View File
@@ -598,7 +598,7 @@ async fn zsh_fork_unified_exec_keeps_shell_parameter_when_remote_environment_ava
.expect("remote test environment"),
),
remote_cwd,
/*shell*/ None,
/*shell*/ Err("not configured for test".to_string()),
),
);
})