Keep environment tools stable across readiness changes (#54098)

## Why

Environment tool availability and selectors should remain stable as selected environments become ready.

## What changed

- Keep configured environment tools advertised even when no execution environment is ready, and derive `environment_id` selectors from all selected environments.
- Return guidance to wait when an environment is unavailable, while preserving errors for unknown environment IDs. Require a usable primary environment for `write_stdin`.
- Always include `shell` and `login` in the `exec_command` schema and mark `stable_environment_tools` as removed.

## Testing

Update integration tests to expect environment tools with empty or starting environments, and remove explicit feature opt-ins from affected scenarios.

GitOrigin-RevId: 1590c1b5be16a39e4a370663c552b881602545b5
This commit is contained in:
Ahmed Ibrahim
2026-10-14 21:06:42 +00:00
committed by copyberry
parent f10ec115b7
commit 0c5720ea0f
15 changed files with 52 additions and 157 deletions
@@ -332,9 +332,8 @@ impl ApplyPatchHandler {
// Verify the parsed patch against the selected environment filesystem.
let turn_environment = resolve_tool_environment(
&step_context,
&step_context.environments,
selected_environment_id.as_deref(),
"apply_patch is unavailable in this session",
)?;
let fs = turn_environment.environment.get_filesystem();
let sandbox = turn_environment.sandbox_context(/*additional_permissions*/ None);
+10 -20
View File
@@ -36,7 +36,6 @@ mod view_image;
pub(crate) mod view_image_spec;
mod wait_for_environment;
use codex_features::Feature;
use codex_file_system::FileSystemSandboxContext;
use codex_sandboxing::policy_transforms::materialize_additional_permissions_with_context;
use codex_sandboxing::policy_transforms::merge_permission_profiles;
@@ -48,6 +47,7 @@ use serde::Deserialize;
use serde_json::Map;
use serde_json::Value;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::function_tool::FunctionCallError;
use crate::sandboxing::SandboxPermissions;
use crate::session::step_context::StepContext;
@@ -158,17 +158,9 @@ where
}
fn resolve_tool_environment<'a>(
step_context: &'a StepContext,
environments: &'a TurnEnvironmentSnapshot,
environment_id: Option<&str>,
legacy_unavailable_message: &'static str,
) -> Result<&'a TurnEnvironment, FunctionCallError> {
let environments = &step_context.environments;
let stable_environment_tools = step_context
.turn
.config
.features
.get()
.enabled(Feature::StableEnvironmentTools);
environment_id.map_or_else(
|| environments.primary(),
|environment_id| {
@@ -178,21 +170,19 @@ fn resolve_tool_environment<'a>(
},
).ok_or_else(|| {
if let Some(environment_id) = environment_id
&& (!stable_environment_tools
|| !environments
.all_selections()
.iter()
.any(|selection| selection.environment_id == environment_id))
&& !environments
.all_selections()
.iter()
.any(|selection| selection.environment_id == environment_id)
{
return FunctionCallError::RespondToModel(format!(
"unknown turn environment id `{environment_id}`"
));
}
FunctionCallError::RespondToModel(if stable_environment_tools {
"No usable execution environment is available. Wait for an environment to become available before using this tool.".to_string()
} else {
legacy_unavailable_message.to_string()
})
FunctionCallError::RespondToModel(
"No usable execution environment is available. Wait for an environment to become available before using this tool."
.to_string(),
)
})
}
@@ -69,9 +69,8 @@ impl RequestPermissionsHandler {
let environment_args: RequestPermissionsEnvironmentArgs = parse_arguments(&arguments)?;
let turn_environment = resolve_tool_environment(
&step_context,
&step_context.environments,
environment_args.environment_id.as_deref(),
"request_permissions requires a primary environment",
)?;
let sandbox_context =
turn_environment.sandbox_context(/*additional_permissions*/ None);
+13 -20
View File
@@ -7,7 +7,6 @@ use std::collections::BTreeMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandToolOptions {
pub include_login_parameter: bool,
pub exec_permission_approvals_enabled: bool,
}
@@ -16,7 +15,6 @@ pub fn create_exec_command_tool(options: CommandToolOptions) -> ToolSpec {
create_exec_command_tool_with_environment_id(
options,
/*include_environment_id*/ false,
/*include_shell_parameter*/ true,
/*include_windows_shell_guidance*/ cfg!(windows),
)
}
@@ -24,7 +22,6 @@ pub fn create_exec_command_tool(options: CommandToolOptions) -> ToolSpec {
pub(crate) fn create_exec_command_tool_with_environment_id(
options: CommandToolOptions,
include_environment_id: bool,
include_shell_parameter: bool,
include_windows_shell_guidance: bool,
) -> ToolSpec {
let yield_time_ms_description = if cfg!(windows) {
@@ -62,23 +59,19 @@ pub(crate) fn create_exec_command_tool_with_environment_id(
)),
),
]);
if include_shell_parameter {
properties.insert(
"shell".to_string(),
JsonSchema::string(Some(
"Shell binary to launch. Defaults to the user's default shell.".to_string(),
)),
);
}
if options.include_login_parameter {
properties.insert(
"login".to_string(),
JsonSchema::boolean(Some(
"True runs the shell with -l/-i semantics; false disables them. Defaults to true."
.to_string(),
)),
);
}
properties.insert(
"shell".to_string(),
JsonSchema::string(Some(
"Shell binary to launch. Defaults to the user's default shell.".to_string(),
)),
);
properties.insert(
"login".to_string(),
JsonSchema::boolean(Some(
"True runs the shell with -l/-i semantics; false disables them. Defaults to true."
.to_string(),
)),
);
if include_environment_id {
properties.insert(
"environment_id".to_string(),
@@ -9,7 +9,6 @@ fn windows_shell_guidance_description() -> String {
#[test]
fn exec_command_tool_matches_expected_spec() {
let tool = create_exec_command_tool(CommandToolOptions {
include_login_parameter: true,
exec_permission_approvals_enabled: false,
});
@@ -57,8 +57,6 @@ const EXEC_COMMAND_REJECTION_MAX_BYTES: usize = 900;
#[derive(Clone, Copy)]
pub(crate) struct ExecCommandHandlerOptions {
pub(crate) include_login_parameter: bool,
pub(crate) include_shell_parameter: bool,
pub(crate) allow_tty: bool,
pub(crate) exec_permission_approvals_enabled: bool,
pub(crate) include_environment_id: bool,
@@ -81,8 +79,6 @@ impl Default for ExecCommandHandler {
Self {
lifetime: ExecCommandLifetime::Interactive,
options: ExecCommandHandlerOptions {
include_login_parameter: false,
include_shell_parameter: true,
allow_tty: true,
exec_permission_approvals_enabled: false,
include_environment_id: false,
@@ -116,11 +112,9 @@ impl ToolExecutor<ToolInvocation> for ExecCommandHandler {
fn spec(&self) -> ToolSpec {
let spec = create_exec_command_tool_with_environment_id(
CommandToolOptions {
include_login_parameter: self.options.include_login_parameter,
exec_permission_approvals_enabled: self.options.exec_permission_approvals_enabled,
},
self.options.include_environment_id,
self.options.include_shell_parameter,
self.options.include_windows_shell_guidance,
);
let mut spec = match self.lifetime {
@@ -184,9 +178,8 @@ impl ExecCommandHandler {
);
let environment_args: ExecCommandEnvironmentArgs = parse_arguments(&arguments)?;
let turn_environment = resolve_tool_environment(
&step_context,
&step_context.environments,
environment_args.environment_id.as_deref(),
"unified exec is unavailable in this session",
)?;
let native_environment_cwd = turn_environment.cwd().clone();
let cwd = environment_args
@@ -1,6 +1,4 @@
use crate::function_tool::FunctionCallError;
use codex_features::Feature;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
use crate::tools::context::boxed_tool_output;
@@ -82,18 +80,7 @@ impl WriteStdinHandler {
};
let args: WriteStdinArgs = parse_arguments(&arguments)?;
if turn
.config
.features
.get()
.enabled(Feature::StableEnvironmentTools)
{
resolve_tool_environment(
&step_context,
/*environment_id*/ None,
"unified exec is unavailable in this session",
)?;
}
resolve_tool_environment(&step_context.environments, /*environment_id*/ None)?;
let context =
UnifiedExecContext::new(session.clone(), step_context, cancellation_token, call_id);
let response = session
@@ -142,11 +142,8 @@ impl ViewImageHandler {
}
};
let turn_environment = resolve_tool_environment(
&step_context,
environment_id.as_deref(),
"view_image is unavailable in this session",
)?;
let turn_environment =
resolve_tool_environment(&step_context.environments, environment_id.as_deref())?;
let path_uri = turn_environment.cwd().join(&path).map_err(|err| {
FunctionCallError::RespondToModel(format!(
"unable to resolve image path `{path}` against environment cwd `{}`: {err}",
+9 -33
View File
@@ -1206,20 +1206,9 @@ fn standalone_web_search_enabled(turn_context: &TurnContext, model_info: &ModelI
.enabled(Feature::StandaloneWebSearch))
}
fn tool_environment_mode(context: &CoreToolPlanContext<'_>) -> ToolEnvironmentMode {
let count = if context
.turn_context
.config
.features
.get()
.enabled(Feature::StableEnvironmentTools)
{
// Keep selectors stable as selected attachments change readiness.
context.environments.environments.len()
} else {
context.environments.turn_environments().count()
};
ToolEnvironmentMode::from_count(count)
fn tool_environment_mode(environments: &TurnEnvironmentSnapshot) -> ToolEnvironmentMode {
// Keep environment selectors stable as selected attachments change readiness.
ToolEnvironmentMode::from_count(environments.environments.len())
}
fn should_include_windows_shell_guidance(environments: &TurnEnvironmentSnapshot) -> bool {
@@ -1245,12 +1234,8 @@ fn should_include_windows_shell_guidance(environments: &TurnEnvironmentSnapshot)
fn add_shell_tools(context: &CoreToolPlanContext<'_>, registry: &mut ToolRegistry) {
let turn_context = context.turn_context;
let features = turn_context.config.features.get();
let environment_mode = tool_environment_mode(context);
let stable_environment_tools = features.enabled(Feature::StableEnvironmentTools);
let advertise_environment_tools =
stable_environment_tools || environment_mode.has_environment();
if !advertise_environment_tools
|| !features.enabled(Feature::ShellTool)
let environment_mode = tool_environment_mode(context.environments);
if !features.enabled(Feature::ShellTool)
|| matches!(context.model_info.shell_type, ConfigShellToolType::Disabled)
{
return;
@@ -1263,12 +1248,6 @@ fn add_shell_tools(context: &CoreToolPlanContext<'_>, registry: &mut ToolRegistr
&& context.tool_policy.expose_additional_permissions;
let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple);
let options = ExecCommandHandlerOptions {
include_login_parameter: stable_environment_tools
|| context
.environments
.turn_environments()
.any(|environment| environment.config().allow_login_shell),
include_shell_parameter: true,
allow_tty: features.enabled(Feature::UnifiedExecTty),
exec_permission_approvals_enabled,
include_environment_id,
@@ -1307,10 +1286,7 @@ fn add_mcp_resource_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut ToolRegistry) {
let turn_context = context.turn_context;
let features = turn_context.config.features.get();
let environment_mode = tool_environment_mode(context);
let stable_environment_tools = features.enabled(Feature::StableEnvironmentTools);
let advertise_environment_tools =
stable_environment_tools || environment_mode.has_environment();
let environment_mode = tool_environment_mode(context.environments);
if turn_context.config.update_plan_enabled {
registry.add(PlanHandler);
@@ -1376,7 +1352,7 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
registry.add_with_exposure(SendMessageToUserAsyncHandler, ToolExposure::DirectModelOnly);
}
if advertise_environment_tools && features.enabled(Feature::RequestPermissionsTool) {
if features.enabled(Feature::RequestPermissionsTool) {
registry.add(RequestPermissionsHandler);
}
@@ -1429,7 +1405,7 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
));
}
if advertise_environment_tools && context.model_info.apply_patch_tool_type.is_some() {
if context.model_info.apply_patch_tool_type.is_some() {
let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple);
registry.add(ApplyPatchHandler::new(include_environment_id));
}
@@ -1443,7 +1419,7 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, registry: &mut Tool
registry.add(TestSyncHandler);
}
if advertise_environment_tools && features.enabled(Feature::ViewImage) {
if features.enabled(Feature::ViewImage) {
let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple);
registry.add(ViewImageHandler::new(ViewImageToolOptions {
can_request_original_image_detail: can_request_original_image_detail(
+3 -11
View File
@@ -1911,10 +1911,6 @@ async fn pending_attachment_installs_configuration_before_waiting_turn_resumes()
let mut builder = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| {
config
.features
.enable(Feature::StableEnvironmentTools)
.expect("enable stable environment tools");
assert!(config.features.enable(Feature::DeferredExecutor).is_ok());
assert!(
config
@@ -2860,6 +2856,7 @@ async fn ready_before_selection_resolves_resumed_thread_capability_root_after_wa
// The first request may legally see either Starting or Ready; the wait makes step two ready.
let first_tools = tool_names(&requests[0].body_json());
assert!(first_tools.contains(&"wait_for_environment".to_string()));
assert!(first_tools.contains(&"exec_command".to_string()));
let first_user_context = requests[0].message_input_texts("user");
let first_environment_context = first_user_context
.iter()
@@ -2868,13 +2865,8 @@ async fn ready_before_selection_resolves_resumed_thread_capability_root_after_wa
let first_has_ready_root = first_user_context
.iter()
.any(|text| text.contains("<ready_capability_roots>ready-first-root"));
let first_is_starting = first_environment_context.contains("<status>starting</status>");
assert_eq!(
first_tools.contains(&"exec_command".to_string()),
!first_is_starting,
"without stable_environment_tools, commands require a ready transport"
);
if first_is_starting {
// Tool availability no longer distinguishes Starting from Ready.
if first_environment_context.contains("<status>starting</status>") {
assert!(!first_has_ready_root);
} else {
assert!(first_environment_context.contains("<shell>"));
+3 -8
View File
@@ -1959,14 +1959,9 @@ async fn subagent_waits_for_its_inherited_environment_configuration() -> Result<
use super::remote_env::spawn_tests::PendingSpawnCase;
use super::remote_env::spawn_tests::pending_subagent_scenario;
let requests = pending_subagent_scenario(PendingSpawnCase::TurnSettings, |config| {
configure_scenario_catalog(config);
config
.features
.enable(Feature::StableEnvironmentTools)
.expect("enable stable environment tools");
})
.await?;
let requests =
pending_subagent_scenario(PendingSpawnCase::TurnSettings, configure_scenario_catalog)
.await?;
let labels = [
"parent delegates while the environment is starting",
"parent waits for the worker",
@@ -3062,10 +3062,6 @@ async fn production_turn_keeps_rebalanced_catalogs_stable_after_compaction_and_r
model_info.max_context_window = None;
})
.with_config(|config| {
config
.features
.enable(Feature::StableEnvironmentTools)
.expect("enable stable environment tools");
configure_catalog_test(config);
config.cloud_skill_enabled = true;
config.model_provider.name = "Skills compaction test".to_string();
@@ -16,8 +16,8 @@ Settings:
text: {"verbosity":"low"}
tool_choice: "auto"
-- request 1 (turn) --
00:additional_tools/developer (3; hash=e80da11342c6e6dd):
- namespace/functions; hash=bd9e182b4235cdc1
00:additional_tools/developer (3; hash=5e8370540461db70):
- namespace/functions; hash=7d26e086c1dbba28
- custom/exec
- function/wait
- function/request_user_input
+5 -26
View File
@@ -244,12 +244,8 @@ async fn strict_tool_collisions_do_not_duplicate_unrelated_compaction_errors() -
Ok(())
}
#[test_case::test_case(false; "default_off")]
#[test_case::test_case(true; "opted_in")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn empty_turn_environments_gate_environment_backed_tools(
stable_environment_tools: bool,
) -> Result<()> {
async fn empty_turn_environments_keeps_environment_backed_tools() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -263,17 +259,7 @@ async fn empty_turn_environments_gate_environment_backed_tools(
)
.await;
let mut builder = test_codex().with_config(move |config| {
if stable_environment_tools {
config
.features
.enable(Feature::StableEnvironmentTools)
.expect("enable stable environment tools");
}
config
.features
.enable(Feature::RequestPermissionsTool)
.expect("enable permissions tool");
let mut builder = test_codex().with_config(|config| {
config.update_plan_enabled = true;
config
.features
@@ -290,17 +276,10 @@ async fn empty_turn_environments_gate_environment_backed_tools(
tools.contains(&"update_plan".to_string()),
"non-environment tool should remain available; got {tools:?}"
);
for environment_tool in [
"exec_command",
"write_stdin",
"apply_patch",
"view_image",
"request_permissions",
] {
assert_eq!(
for environment_tool in ["exec_command", "write_stdin", "apply_patch", "view_image"] {
assert!(
tools.contains(&environment_tool.to_string()),
stable_environment_tools,
"unexpected {environment_tool} availability for empty environments; got {tools:?}"
"{environment_tool} should remain available for explicit empty turn environments; got {tools:?}"
);
}
+1 -1
View File
@@ -1155,7 +1155,7 @@ pub const FEATURES: &[FeatureSpec] = &[
FeatureSpec {
id: Feature::StableEnvironmentTools,
key: "stable_environment_tools",
stage: Stage::UnderDevelopment,
stage: Stage::Removed,
default_enabled: false,
},
FeatureSpec {