Use turn environment permissions for tool execution (#37038)

## What changed

- Derive sandboxing, approval, and permission-profile environment variables from the selected turn environment for shell, unified exec, `apply_patch`, image viewing, and network approval flows.
- Materialize project-root permissions against every workspace root in that environment, allowing `apply_patch` to write to secondary workspace roots while preserving protected paths.
- Carry the selected environment's permission profile into spawned or resumed agents and Guardian permission context.

## Testing

- Add an integration test covering `apply_patch` writes in a secondary workspace root.
- Extend tool, Guardian, and multi-agent tests to distinguish environment permissions from thread-level permissions.

GitOrigin-RevId: e22da8974bcd3de1e724978b1a7790307a51e4bc
This commit is contained in:
sayan-oai authored and copyberry committed 2026-08-05 06:38:57 +00:00
1 parent 1fe6be9719
commit bac3ef1d8e
28 files changed
+398 -147

No files matched your search

@@ -259,8 +259,7 @@ fn apply_patch_payload_command(payload: &ToolPayload) -> Option<String> {
async fn effective_patch_permissions(
session: &Session,
turn: &TurnContext,
environment_id: &str,
environment: &TurnEnvironment,
action: &ApplyPatchAction,
cwd: &PathUri,
) -> std::io::Result<(
@@ -268,6 +267,7 @@ async fn effective_patch_permissions(
crate::tools::handlers::EffectiveAdditionalPermissions,
codex_protocol::permissions::FileSystemSandboxPolicy,
)> {
let environment_id = environment.environment_id.as_str();
let file_paths = file_paths_for_action(action);
let native_cwd = cwd.to_abs_path()?;
let granted_permissions = merge_permission_profiles(
@@ -280,7 +280,9 @@ async fn effective_patch_permissions(
.await
.as_ref(),
);
let base_file_system_sandbox_policy = turn.file_system_sandbox_policy();
let base_file_system_sandbox_policy = environment
.permission_profile_with_workspace_roots()
.file_system_sandbox_policy();
let file_system_sandbox_policy = effective_file_system_sandbox_policy(
&base_file_system_sandbox_policy,
granted_permissions.as_ref(),
@@ -527,17 +529,12 @@ async fn execute_verified_patch(
tool_ctx: ToolCtx,
) -> Result<String, FunctionCallError> {
let (file_paths, effective_additional_permissions, file_system_sandbox_policy) =
effective_patch_permissions(
tool_ctx.session.as_ref(),
tool_ctx.turn.as_ref(),
&turn_environment.environment_id,
&action,
cwd,
)
.await
.unwrap_or_else(|_| patch_permissions_without_path_matching(&action));
effective_patch_permissions(tool_ctx.session.as_ref(), &turn_environment, &action, cwd)
.await
.unwrap_or_else(|_| patch_permissions_without_path_matching(&action));
let apply = apply_patch::prepare_apply_patch(
tool_ctx.turn.as_ref(),
turn_environment.permission_profile(),
&file_system_sandbox_policy,
action,
)?;
@@ -2,6 +2,7 @@ use super::*;
use crate::agent::next_thread_spawn_depth;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::tools::handlers::multi_agents_spec::create_resume_agent_tool;
use codex_tools::ToolSpec;
use std::sync::Arc;
@@ -35,6 +36,7 @@ async fn handle_resume_agent(
let ToolInvocation {
session,
turn,
step_context,
payload,
call_id,
..
@@ -88,6 +90,7 @@ async fn handle_resume_agent(
match Box::pin(try_resume_closed_agent(
&session,
&turn,
step_context.environments.primary(),
receiver_thread_id,
child_depth,
))
@@ -188,10 +191,11 @@ impl ToolOutput for ResumeAgentResult {
async fn try_resume_closed_agent(
session: &Arc<Session>,
turn: &Arc<TurnContext>,
environment: Option<&TurnEnvironment>,
receiver_thread_id: ThreadId,
child_depth: i32,
) -> Result<(), FunctionCallError> {
let config = build_agent_resume_config(turn.as_ref())?;
let config = build_agent_resume_config(turn.as_ref(), environment)?;
Box::pin(session.services.agent_control.resume_agent_from_rollout(
config,
receiver_thread_id,
@@ -34,6 +34,7 @@ impl Handler {
let ToolInvocation {
session,
turn,
step_context,
payload,
call_id,
..
@@ -48,7 +49,8 @@ impl Handler {
.agent_control
.get_agent_metadata(receiver_thread_id);
if receiver_agent.is_some() {
let resume_config = build_agent_resume_config(turn.as_ref())?;
let resume_config =
build_agent_resume_config(turn.as_ref(), step_context.environments.primary())?;
session
.services
.agent_control
@@ -86,8 +86,11 @@ async fn handle_spawn_agent(
}),
)
.await;
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
let mut config = build_agent_spawn_config(
&session.get_base_instructions().await,
turn.as_ref(),
step_context.environments.primary(),
)?;
if let Some(service_tier) = args.service_tier.as_ref() {
config.service_tier = Some(service_tier.clone());
}
@@ -112,7 +115,11 @@ async fn handle_spawn_agent(
args.service_tier.as_deref(),
)
.await?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
apply_spawn_agent_runtime_overrides(
&mut config,
turn.as_ref(),
step_context.environments.primary(),
)?;
let result = Box::pin(session.services.agent_control.spawn_agent_with_metadata(
config,
@@ -6,6 +6,7 @@ use crate::config::HARD_MAX_MULTI_AGENT_V2_TIMEOUT_MS;
use crate::function_tool::FunctionCallError;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
@@ -170,27 +171,34 @@ pub(crate) fn parse_collab_input(
/// Builds the base config snapshot for a newly spawned sub-agent.
///
/// The returned config starts from the parent's effective config and then refreshes the
/// runtime-owned fields carried on `turn`, including model selection, reasoning settings,
/// approval policy, sandbox, and cwd. Role-specific overrides are layered after this step;
/// skipping this helper and cloning stale config state directly can send the child agent out with
/// the wrong provider or runtime policy.
/// runtime-owned fields carried by the turn and selected environment, including model selection,
/// reasoning settings, approval policy, sandbox, and cwd. Role-specific overrides are layered
/// after this step; skipping this helper and cloning stale config state directly can send the child
/// agent out with the wrong provider or runtime policy.
pub(crate) fn build_agent_spawn_config(
base_instructions: &BaseInstructions,
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<Config, FunctionCallError> {
let mut config = build_agent_shared_config(turn)?;
let mut config = build_agent_shared_config(turn, environment)?;
config.base_instructions = Some(base_instructions.text.clone());
Ok(config)
}
pub(crate) fn build_agent_resume_config(turn: &TurnContext) -> Result<Config, FunctionCallError> {
let mut config = build_agent_shared_config(turn)?;
pub(crate) fn build_agent_resume_config(
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<Config, FunctionCallError> {
let mut config = build_agent_shared_config(turn, environment)?;
// For resume, keep base instructions sourced from rollout/session metadata.
config.base_instructions = None;
Ok(config)
}
fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, FunctionCallError> {
fn build_agent_shared_config(
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<Config, FunctionCallError> {
let base_config = turn.config.clone();
let mut config = (*base_config).clone();
config.model = Some(turn.model_info.slug.clone());
@@ -210,7 +218,7 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, FunctionCallE
{
config.developer_instructions = Some(developer_instructions);
}
apply_spawn_agent_runtime_overrides(&mut config, turn)?;
apply_spawn_agent_runtime_overrides(&mut config, turn, environment)?;
Ok(config)
}
@@ -228,11 +236,13 @@ pub(crate) fn reject_full_fork_agent_type_override(
/// Copies runtime-only turn state onto a child config before it is handed to `AgentControl`.
///
/// These values are chosen by the live turn rather than persisted config, so leaving them stale
/// can make a child agent disagree with its parent about approval policy, cwd, or sandboxing.
/// These values are chosen by the live turn and selected environment rather than persisted config,
/// so leaving them stale can make a child agent disagree with its parent about approval policy,
/// cwd, or sandboxing.
pub(crate) fn apply_spawn_agent_runtime_overrides(
config: &mut Config,
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<(), FunctionCallError> {
config
.permissions
@@ -245,9 +255,12 @@ pub(crate) fn apply_spawn_agent_runtime_overrides(
#[allow(deprecated)]
let turn_cwd = turn.cwd.clone();
config.cwd = turn_cwd;
let permission_profile = environment
.map(|environment| environment.permission_profile().clone())
.unwrap_or_else(|| turn.permission_profile());
config
.permissions
.set_permission_profile(turn.permission_profile())
.set_permission_profile(permission_profile)
.map_err(|err| {
FunctionCallError::RespondToModel(format!("permission_profile is invalid: {err}"))
})?;
@@ -3,6 +3,8 @@ use crate::StartThreadOptions;
use crate::ThreadManager;
use crate::config::AgentRoleConfig;
use crate::config::DEFAULT_AGENT_MAX_DEPTH;
use crate::config::PermissionProfileSnapshot;
use crate::environment_selection::TurnEnvironmentState;
use crate::function_tool::FunctionCallError;
use crate::init_state_db;
use crate::local_agent_graph_store_from_state_db;
@@ -2264,7 +2266,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
config
.permissions
.set_permission_profile(expected_permission_profile.clone())
.set_permission_profile(PermissionProfile::Disabled)
.expect("test setup should allow updating permission profile");
set_turn_config(&mut turn, config);
let role_name = install_role_with_model_override(&mut turn).await;
@@ -2272,11 +2274,26 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
crate::agent::role::apply_role_to_config(&mut role_config, Some(role_name.as_str()))
.await
.expect("non-empty role config should apply");
let TurnEnvironmentState::Ready(environment) = turn
.environments
.environments
.first_mut()
.expect("parent environment should exist")
else {
panic!("parent environment should be ready");
};
environment.config.permission_profile =
PermissionProfileSnapshot::legacy(expected_permission_profile.clone());
assert_ne!(
role_config.permissions.effective_permission_profile(),
expected_permission_profile,
"role config must discard the runtime permission override before it is reapplied"
);
assert_ne!(
expected_permission_profile,
turn.permission_profile(),
"test requires an environment profile that differs from the thread profile"
);
let invocation = invocation(
Arc::new(session),
@@ -4446,6 +4463,7 @@ async fn build_agent_spawn_config_uses_turn_context_values() {
&file_system_sandbox_policy,
network_sandbox_policy,
);
turn.environments.environments.clear();
Arc::make_mut(&mut turn.config)
.permissions
.set_permission_profile(permission_profile)
@@ -4456,7 +4474,8 @@ async fn build_agent_spawn_config_uses_turn_context_values() {
.set(AskForApproval::OnRequest)
.expect("approval policy set");
let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config");
let config = build_agent_spawn_config(&base_instructions, &turn, turn.environments.primary())
.expect("spawn config");
let mut expected = (*turn.config).clone();
expected.base_instructions = Some(base_instructions.text);
expected.model = Some(turn.model_info.slug.clone());
@@ -4491,8 +4510,25 @@ async fn build_agent_resume_config_clears_base_instructions() {
.approval_policy
.set(AskForApproval::OnRequest)
.expect("approval policy set");
let environment_permission_profile =
if turn.permission_profile() == PermissionProfile::read_only() {
PermissionProfile::workspace_write()
} else {
PermissionProfile::read_only()
};
let TurnEnvironmentState::Ready(environment) = turn
.environments
.environments
.first_mut()
.expect("parent environment should exist")
else {
panic!("parent environment should be ready");
};
environment.config.permission_profile =
PermissionProfileSnapshot::legacy(environment_permission_profile.clone());
let config = build_agent_resume_config(&turn).expect("resume config");
let config =
build_agent_resume_config(&turn, turn.environments.primary()).expect("resume config");
let mut expected = (*turn.config).clone();
expected.base_instructions = None;
@@ -4512,7 +4548,7 @@ async fn build_agent_resume_config_clears_base_instructions() {
.expect("approval policy set");
expected
.permissions
.set_permission_profile(turn.permission_profile())
.set_permission_profile(environment_permission_profile)
.expect("permission profile set");
assert_eq!(config, expected);
}
@@ -59,6 +59,7 @@ pub(crate) async fn handle_message_string_tool(
let ToolInvocation {
session,
turn,
step_context,
call_id,
source,
..
@@ -82,7 +83,8 @@ pub(crate) async fn handle_message_string_tool(
let receiver_agent_path = receiver_agent.agent_path.clone().ok_or_else(|| {
FunctionCallError::RespondToModel("target agent is missing an agent_path".to_string())
})?;
let resume_config = build_agent_resume_config(turn.as_ref())?;
let resume_config =
build_agent_resume_config(turn.as_ref(), step_context.environments.primary())?;
session
.services
.agent_control
@@ -60,8 +60,11 @@ async fn handle_spawn_agent(
let session_source = turn.session_source.clone();
let child_depth = next_thread_spawn_depth(&session_source);
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
let mut config = build_agent_spawn_config(
&session.get_base_instructions().await,
turn.as_ref(),
step_context.environments.primary(),
)?;
if let Some(service_tier) = args.service_tier.as_ref() {
config.service_tier = Some(service_tier.clone());
}
@@ -87,7 +90,11 @@ async fn handle_spawn_agent(
args.service_tier.as_deref(),
)
.await?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
apply_spawn_agent_runtime_overrides(
&mut config,
turn.as_ref(),
step_context.environments.primary(),
)?;
let spawn_source = thread_spawn_source(
session.thread_id,
+1 -1
View File
@@ -178,7 +178,7 @@ async fn run_exec_like(args: RunExecLikeArgs) -> Result<FunctionToolOutput, Func
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &exec_params.command,
approval_policy: turn.approval_policy(),
permission_profile: turn.permission_profile(),
permission_profile: turn_environment.permission_profile().clone(),
windows_sandbox_level: turn.windows_sandbox_level,
sandbox_permissions: if effective_additional_permissions.permissions_preapproved {
codex_protocol::models::SandboxPermissions::UseDefault
@@ -105,7 +105,7 @@ impl ShellCommandHandler {
&turn_context.config.permissions.shell_environment_policy,
Some(session.thread_id),
);
let active_permission_profile = turn_context.config.permissions.active_permission_profile();
let active_permission_profile = turn_environment.active_permission_profile();
inject_permission_profile_env(&mut env, active_permission_profile.as_ref());
let sandbox_permissions = resolve_sandbox_permissions(
params.sandbox_permissions,
@@ -81,8 +81,8 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
Arc::make_mut(&mut turn_context.config)
.permissions
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active(
permission_profile,
ActivePermissionProfile::new("test-profile"),
permission_profile.clone(),
ActivePermissionProfile::new("thread-profile"),
))
.expect("set active permission profile");
@@ -100,6 +100,7 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
let expected_command = selected_shell.derive_exec_args(&command, /*use_login_shell*/ true);
let selected_cwd = turn_context.config.cwd.join("selected-environment");
let expected_cwd = selected_cwd.join("subdir");
let active_permission_profile = ActivePermissionProfile::new("selected-profile");
let selected_environment = TurnEnvironment::new(
"selected-environment".to_string(),
Arc::clone(
@@ -114,19 +115,17 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
Some(selected_shell),
EnvironmentConfig {
allow_login_shell: true,
permission_profile: turn_context
.config
.permissions
.permission_profile_state()
.snapshot(),
permission_profile: PermissionProfileSnapshot::active(
permission_profile,
active_permission_profile.clone(),
),
},
);
let mut expected_env = create_env(
&turn_context.config.permissions.shell_environment_policy,
Some(session.thread_id),
);
let active_permission_profile = turn_context.config.permissions.active_permission_profile();
inject_permission_profile_env(&mut expected_env, active_permission_profile.as_ref());
inject_permission_profile_env(&mut expected_env, Some(&active_permission_profile));
let params = ShellCommandToolCallParams {
command,
@@ -154,9 +153,7 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
assert_eq!(exec_params.env, expected_env);
assert_eq!(
exec_params.env.get(CODEX_PERMISSION_PROFILE_ENV_VAR),
active_permission_profile
.as_ref()
.map(|profile| &profile.id)
Some(&active_permission_profile.id)
);
assert_eq!(exec_params.network, turn_context.network);
assert_eq!(
@@ -156,7 +156,7 @@ impl ExecCommandHandler {
// permissions config below. Consult the configured platform-sandbox requirement before
// deciding whether parsing may continue without that base path.
let sandbox = SandboxManager::new().select_initial(
&turn.permission_profile(),
turn_environment.permission_profile(),
SandboxablePreference::Auto,
turn.windows_sandbox_level,
turn.network.is_some(),
+15 -6
View File
@@ -244,6 +244,7 @@ impl ToolOutput for ViewImageOutput {
#[cfg(test)]
mod tests {
use super::*;
use crate::config::PermissionProfileSnapshot;
use crate::environment_selection::TurnEnvironmentState;
use crate::session::step_context::StepContext;
use crate::session::tests::make_session_and_context;
@@ -318,8 +319,14 @@ mod tests {
std::fs::write(image_path.as_path(), b"not a real image").expect("write test image");
Arc::make_mut(&mut turn.config)
.permissions
.set_permission_profile(PermissionProfile::read_only())
.expect("test setup should allow updating permission profile");
.set_permission_profile(PermissionProfile::Disabled)
.expect("set thread permission profile");
let TurnEnvironmentState::Ready(environment) = &mut turn.environments.environments[0]
else {
panic!("primary environment should be ready");
};
environment.config.permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::read_only());
let turn = Arc::new(turn);
let result = ViewImageHandler::default()
@@ -386,10 +393,12 @@ mod tests {
replace_primary_environment_cwd(&mut turn, image_cwd.clone());
let image_path = image_cwd.join("image.png");
std::fs::write(image_path.as_path(), b"not a real image").expect("write test image");
Arc::make_mut(&mut turn.config)
.permissions
.set_permission_profile(PermissionProfile::Disabled)
.expect("set permission profile");
let TurnEnvironmentState::Ready(environment) = &mut turn.environments.environments[0]
else {
panic!("primary environment should be ready");
};
environment.config.permission_profile =
PermissionProfileSnapshot::legacy(PermissionProfile::Disabled);
let turn = Arc::new(turn);
let result = ViewImageHandler::default()