Separate thread settings from environment configuration (#39597)

## Why

Environment-owned permission profiles and workspace roots must remain effective
without being persisted or restored as thread-owned settings.

## What changed

- Keep thread settings snapshots and restore data separate from the effective
  configuration supplied by the primary environment.
- Use resolved environment permissions, active profiles, workspace roots, and
  network policy when building turn context and session events.
- Preserve environment selections when agents are evicted, resumed, or spawned,
  and validate owner configuration when it becomes ready.
- Start memory initialization only after the primary environment is configured.

## Testing

- Extend remote-environment and multi-agent tests to cover settings persistence,
  owner permission profiles, workspace roots, spawning, eviction, and resume.

GitOrigin-RevId: d82f126981cd0190233020bbdd61d96c70558868
This commit is contained in:
sayan-oai authored and copyberry committed 2026-08-20 05:29:12 +00:00
1 parent 8f4a48a6ad
commit d75c85f651
35 files changed
+564 -308

No files matched your search

@@ -2,7 +2,6 @@ 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;
@@ -36,7 +35,6 @@ async fn handle_resume_agent(
let ToolInvocation {
session,
turn,
step_context,
payload,
call_id,
..
@@ -90,7 +88,6 @@ async fn handle_resume_agent(
match Box::pin(try_resume_closed_agent(
&session,
&turn,
step_context.environments.primary(),
receiver_thread_id,
child_depth,
))
@@ -191,11 +188,10 @@ 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(), environment)?;
let config = build_agent_resume_config(turn.as_ref())?;
Box::pin(session.services.agent_control.resume_agent_from_rollout(
config,
receiver_thread_id,
@@ -34,7 +34,6 @@ impl Handler {
let ToolInvocation {
session,
turn,
step_context,
payload,
call_id,
..
@@ -49,8 +48,7 @@ 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(), step_context.environments.primary())?;
let resume_config = build_agent_resume_config(turn.as_ref())?;
session
.services
.agent_control
@@ -86,11 +86,8 @@ async fn handle_spawn_agent(
}),
)
.await;
let mut config = build_agent_spawn_config(
&session.get_base_instructions().await,
turn.as_ref(),
step_context.environments.primary(),
)?;
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
if let Some(service_tier) = args.service_tier.as_ref() {
config.service_tier = Some(service_tier.clone());
}
@@ -115,11 +112,7 @@ async fn handle_spawn_agent(
args.service_tier.as_deref(),
)
.await?;
apply_spawn_agent_runtime_overrides(
&mut config,
turn.as_ref(),
step_context.environments.primary(),
)?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
let result = Box::pin(session.services.agent_control.spawn_agent_with_metadata(
config,
@@ -5,7 +5,6 @@ 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,36 +169,29 @@ 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 by the turn and selected environment, including model selection,
/// reasoning settings, approval policy, sandbox, and cwd. Role-specific overrides are layered
/// runtime-owned fields carried by the 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.
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, environment)?;
let mut config = build_agent_shared_config(turn)?;
config.base_instructions = Some(base_instructions.text.clone());
config.base_instructions_provenance = base_instructions.provenance.clone();
Ok(config)
}
pub(crate) fn build_agent_resume_config(
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<Config, FunctionCallError> {
let mut config = build_agent_shared_config(turn, environment)?;
pub(crate) fn build_agent_resume_config(turn: &TurnContext) -> Result<Config, FunctionCallError> {
let mut config = build_agent_shared_config(turn)?;
// For resume, keep base instructions sourced from rollout/session metadata.
config.base_instructions = None;
config.base_instructions_provenance = None;
Ok(config)
}
fn build_agent_shared_config(
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<Config, FunctionCallError> {
fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, FunctionCallError> {
let base_config = turn.config.clone();
let mut config = (*base_config).clone();
config.model = Some(turn.model_info.slug.clone());
@@ -219,7 +211,7 @@ fn build_agent_shared_config(
{
config.developer_instructions = Some(developer_instructions);
}
apply_spawn_agent_runtime_overrides(&mut config, turn, environment)?;
apply_spawn_agent_runtime_overrides(&mut config, turn)?;
Ok(config)
}
@@ -237,13 +229,11 @@ 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 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.
/// 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.
pub(crate) fn apply_spawn_agent_runtime_overrides(
config: &mut Config,
turn: &TurnContext,
environment: Option<&TurnEnvironment>,
) -> Result<(), FunctionCallError> {
config
.permissions
@@ -256,12 +246,14 @@ 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(permission_profile)
.set_permission_profile_from_session_snapshot(
turn.config
.permissions
.permission_profile_state()
.snapshot(),
)
.map_err(|err| {
FunctionCallError::RespondToModel(format!("permission_profile is invalid: {err}"))
})?;
@@ -4,6 +4,7 @@ use crate::ThreadManager;
use crate::config::AgentRoleConfig;
use crate::config::DEFAULT_AGENT_MAX_DEPTH;
use crate::config::PermissionProfileSnapshot;
use crate::environment_selection::EnvironmentConfigOrigin;
use crate::environment_selection::TurnEnvironmentState;
use crate::function_tool::FunctionCallError;
use crate::init_state_db;
@@ -2301,6 +2302,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
};
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(expected_permission_profile.clone());
environment.config_origin = EnvironmentConfigOrigin::Owner;
assert_ne!(
role_config.permissions.effective_permission_profile(),
expected_permission_profile,
@@ -2308,7 +2310,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
);
assert_ne!(
expected_permission_profile,
turn.permission_profile(),
turn.config.permissions.effective_permission_profile(),
"test requires an environment profile that differs from the thread profile"
);
@@ -2360,6 +2362,10 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
expected_network_sandbox_policy
);
assert_eq!(child_turn.permission_profile(), expected_permission_profile);
assert_ne!(
child_turn.config.permissions.permission_profile(),
&expected_permission_profile
);
}
#[tokio::test]
@@ -4240,6 +4246,10 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
let (_session, turn) = make_session_and_context().await;
let mut config = turn.config.as_ref().clone();
config.agent_max_depth = 3;
config
.permissions
.set_permission_profile(PermissionProfile::workspace_write())
.expect("test config should allow workspace writes");
config
.features
.enable(Feature::Sqlite)
@@ -4269,6 +4279,22 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
.expect("parent thread should start");
let parent_thread_id = parent.thread_id;
let parent_session = parent.thread.session.clone();
let parent_turn = parent_session.new_default_turn().await;
let mut owner_config = parent_turn
.environments
.primary()
.expect("parent should have an environment")
.config()
.clone();
let owner_permission_profile = PermissionProfile::read_only();
owner_config.permission_profile =
PermissionProfileSnapshot::legacy(owner_permission_profile.clone());
let parent_environment = parent.thread.environment_selections().await.remove(0);
parent
.thread
.environment_ready(&parent_environment, owner_config)
.await
.expect("owner environment should be installed");
let child_turn = parent_session.new_default_turn().await;
let child_spawn_output = SpawnAgentHandler::default()
@@ -4360,6 +4386,16 @@ async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtr
manager.agent_control().get_status(child_thread_id).await,
AgentStatus::NotFound
);
assert_eq!(
manager
.get_thread(child_thread_id)
.await
.expect("resumed child thread should exist")
.config_snapshot()
.await
.permission_profile,
owner_permission_profile
);
assert_ne!(
manager
.agent_control()
@@ -4519,8 +4555,7 @@ 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, turn.environments.primary())
.expect("spawn config");
let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config");
let mut expected = (*turn.config).clone();
expected.base_instructions_provenance = base_instructions.provenance.clone();
expected.base_instructions = Some(base_instructions.text);
@@ -4538,10 +4573,6 @@ async fn build_agent_spawn_config_uses_turn_context_values() {
.approval_policy
.set(AskForApproval::OnRequest)
.expect("approval policy set");
expected
.permissions
.set_permission_profile(turn.permission_profile())
.expect("permission profile set");
assert_eq!(config, expected);
}
@@ -4574,10 +4605,9 @@ async fn build_agent_resume_config_clears_base_instructions() {
panic!("parent environment should be ready");
};
environment.config_mut().permission_profile =
PermissionProfileSnapshot::legacy(environment_permission_profile.clone());
PermissionProfileSnapshot::legacy(environment_permission_profile);
let config =
build_agent_resume_config(&turn, turn.environments.primary()).expect("resume config");
let config = build_agent_resume_config(&turn).expect("resume config");
let mut expected = (*turn.config).clone();
expected.base_instructions = None;
@@ -4596,9 +4626,5 @@ async fn build_agent_resume_config_clears_base_instructions() {
.approval_policy
.set(AskForApproval::OnRequest)
.expect("approval policy set");
expected
.permissions
.set_permission_profile(environment_permission_profile)
.expect("permission profile set");
assert_eq!(config, expected);
}
@@ -59,7 +59,6 @@ pub(crate) async fn handle_message_string_tool(
let ToolInvocation {
session,
turn,
step_context,
call_id,
source,
..
@@ -83,8 +82,7 @@ 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(), step_context.environments.primary())?;
let resume_config = build_agent_resume_config(turn.as_ref())?;
session
.services
.agent_control
@@ -62,11 +62,8 @@ 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(),
step_context.environments.primary(),
)?;
let mut config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
if let Some(service_tier) = args.service_tier.as_ref() {
config.service_tier = Some(service_tier.clone());
}
@@ -94,11 +91,7 @@ async fn handle_spawn_agent(
args.service_tier.as_deref(),
)
.await?;
apply_spawn_agent_runtime_overrides(
&mut config,
turn.as_ref(),
step_context.environments.primary(),
)?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
let spawn_source = thread_spawn_source(
session.thread_id,