mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
Simplify environment cwd handling
Keep selected environment cwd scoped to resolved turn environments, remove fallback helpers added during review, and preserve existing MCP default/local fallback behavior inline. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -24,9 +24,6 @@ pub enum ConstraintError {
|
||||
requirement_source: RequirementSource,
|
||||
reason: String,
|
||||
},
|
||||
|
||||
#[error("invalid combination: {reason}")]
|
||||
InvalidCombination { reason: String },
|
||||
}
|
||||
|
||||
impl ConstraintError {
|
||||
@@ -35,12 +32,6 @@ impl ConstraintError {
|
||||
field_name: field_name.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invalid_combination(reason: impl Into<String>) -> Self {
|
||||
Self::InvalidCombination {
|
||||
reason: reason.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type ConstraintResult<T> = Result<T, ConstraintError>;
|
||||
|
||||
@@ -41,15 +41,6 @@ impl ResolvedTurnEnvironments {
|
||||
self.turn_environments.first()
|
||||
}
|
||||
|
||||
pub(crate) fn primary_cwd_or_fallback(
|
||||
&self,
|
||||
fallback_cwd: &AbsolutePathBuf,
|
||||
) -> AbsolutePathBuf {
|
||||
self.primary_turn_environment()
|
||||
.map(|environment| environment.cwd.clone())
|
||||
.unwrap_or_else(|| fallback_cwd.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn primary_environment(&self) -> Option<Arc<codex_exec_server::Environment>> {
|
||||
self.primary_turn_environment()
|
||||
.map(|environment| Arc::clone(&environment.environment))
|
||||
@@ -175,7 +166,6 @@ mod tests {
|
||||
)
|
||||
.expect("environment selections should resolve");
|
||||
|
||||
assert_eq!(resolved.primary_cwd_or_fallback(&cwd), selected_cwd);
|
||||
assert_eq!(
|
||||
resolved
|
||||
.primary_turn_environment()
|
||||
@@ -184,15 +174,4 @@ mod tests {
|
||||
"local"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolved_environment_selections_use_fallback_without_selections() {
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let manager = EnvironmentManager::default_for_tests();
|
||||
|
||||
let resolved =
|
||||
resolve_environment_selections(&manager, &[]).expect("empty selections are valid");
|
||||
|
||||
assert_eq!(resolved.primary_cwd_or_fallback(&cwd), cwd);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
impl Session {
|
||||
pub(crate) fn fallback_mcp_runtime_environment(
|
||||
&self,
|
||||
fallback_cwd: &AbsolutePathBuf,
|
||||
require_default_environment: bool,
|
||||
) -> CodexResult<McpRuntimeEnvironment> {
|
||||
if let Some(default_environment) = self.services.environment_manager.default_environment() {
|
||||
return Ok(McpRuntimeEnvironment::new(
|
||||
default_environment,
|
||||
fallback_cwd.to_path_buf(),
|
||||
));
|
||||
}
|
||||
|
||||
if require_default_environment {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"MCP runtime environment requires a default environment".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(McpRuntimeEnvironment::new(
|
||||
self.services.environment_manager.local_environment(),
|
||||
fallback_cwd.to_path_buf(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_runtime_environment_for_configuration(
|
||||
&self,
|
||||
session_configuration: &SessionConfiguration,
|
||||
) -> CodexResult<McpRuntimeEnvironment> {
|
||||
let turn_environment = crate::environment_selection::resolve_environment_selections(
|
||||
self.services.environment_manager.as_ref(),
|
||||
&session_configuration.environments,
|
||||
)
|
||||
.map_err(|err| {
|
||||
CodexErr::InvalidRequest(err.to_string().replace(
|
||||
"unknown turn environment id",
|
||||
"unknown stored MCP environment id",
|
||||
))
|
||||
})?
|
||||
.primary_turn_environment()
|
||||
.cloned();
|
||||
|
||||
if let Some(turn_environment) = turn_environment {
|
||||
return Ok(McpRuntimeEnvironment::new(
|
||||
Arc::clone(&turn_environment.environment),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
));
|
||||
}
|
||||
|
||||
self.fallback_mcp_runtime_environment(
|
||||
&session_configuration.cwd,
|
||||
/*require_default_environment*/ true,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_runtime_environment_for_turn_context(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
require_default_environment: bool,
|
||||
) -> CodexResult<McpRuntimeEnvironment> {
|
||||
if let Some(turn_environment) = turn_context.primary_environment() {
|
||||
return Ok(McpRuntimeEnvironment::new(
|
||||
Arc::clone(&turn_environment.environment),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
));
|
||||
}
|
||||
|
||||
self.fallback_mcp_runtime_environment(&turn_context.cwd, require_default_environment)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "active turn checks and turn state updates must remain atomic"
|
||||
@@ -290,15 +221,18 @@ impl Session {
|
||||
let mcp_servers = with_codex_apps_mcp(mcp_servers, auth.as_ref(), &mcp_config);
|
||||
let auth_statuses =
|
||||
compute_auth_statuses(mcp_servers.iter(), store_mode, auth.as_ref()).await;
|
||||
let enabled_mcp_server_count = mcp_servers.values().filter(|server| server.enabled).count();
|
||||
let mcp_runtime_environment = match self
|
||||
.mcp_runtime_environment_for_turn_context(turn_context, enabled_mcp_server_count > 0)
|
||||
{
|
||||
Ok(runtime_environment) => runtime_environment,
|
||||
Err(err) => {
|
||||
warn!("failed to resolve MCP runtime environment for refresh: {err}");
|
||||
return;
|
||||
}
|
||||
let mcp_runtime_environment = match turn_context.primary_environment() {
|
||||
Some(turn_environment) => McpRuntimeEnvironment::new(
|
||||
Arc::clone(&turn_environment.environment),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
),
|
||||
None => McpRuntimeEnvironment::new(
|
||||
self.services
|
||||
.environment_manager
|
||||
.default_environment()
|
||||
.unwrap_or_else(|| self.services.environment_manager.local_environment()),
|
||||
turn_context.cwd.to_path_buf(),
|
||||
),
|
||||
};
|
||||
{
|
||||
let mut guard = self.services.mcp_startup_cancellation_token.lock().await;
|
||||
|
||||
@@ -442,7 +442,7 @@ impl Codex {
|
||||
|
||||
async fn spawn_internal(args: CodexSpawnArgs) -> CodexResult<CodexSpawnOk> {
|
||||
let CodexSpawnArgs {
|
||||
mut config,
|
||||
config,
|
||||
auth_manager,
|
||||
models_manager,
|
||||
environment_manager,
|
||||
@@ -467,13 +467,11 @@ impl Codex {
|
||||
} = args;
|
||||
let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY);
|
||||
let (tx_event, rx_event) = async_channel::unbounded();
|
||||
config.cwd = environment_selections.primary_cwd_or_fallback(&config.cwd);
|
||||
let load_config = config.clone();
|
||||
let fs = environment_selections.primary_filesystem();
|
||||
let plugins_input = load_config.plugins_config_input();
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let plugin_outcome = plugins_manager.plugins_for_config(&plugins_input).await;
|
||||
let effective_skill_roots = plugin_outcome.effective_skill_roots();
|
||||
let skills_input = skills_load_input_from_config(&load_config, effective_skill_roots);
|
||||
let skills_input = skills_load_input_from_config(&config, effective_skill_roots);
|
||||
let loaded_skills = skills_manager.skills_for_config(&skills_input, fs).await;
|
||||
|
||||
for err in &loaded_skills.errors {
|
||||
@@ -493,7 +491,7 @@ impl Codex {
|
||||
}
|
||||
|
||||
let primary_environment = environment_selections.primary_environment();
|
||||
let user_instructions = AgentsMdManager::new(&load_config)
|
||||
let user_instructions = AgentsMdManager::new(&config)
|
||||
.user_instructions(primary_environment.as_deref())
|
||||
.await;
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::*;
|
||||
use crate::goals::GoalRuntimeState;
|
||||
use codex_config::ConstraintError;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
@@ -146,14 +145,6 @@ impl SessionConfiguration {
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&self, updates: &SessionSettingsUpdate) -> ConstraintResult<Self> {
|
||||
if updates.cwd.as_ref().is_some_and(|cwd| cwd.is_relative())
|
||||
&& updates.environments.is_some()
|
||||
{
|
||||
return Err(ConstraintError::invalid_combination(
|
||||
"relative `cwd` cannot be updated together with turn-local `environments`",
|
||||
));
|
||||
}
|
||||
|
||||
let mut next_configuration = self.clone();
|
||||
let current_sandbox_policy = self.sandbox_policy();
|
||||
let current_file_system_sandbox_policy = self.file_system_sandbox_policy();
|
||||
@@ -201,19 +192,17 @@ impl SessionConfiguration {
|
||||
next_configuration.windows_sandbox_level = windows_sandbox_level;
|
||||
}
|
||||
|
||||
let effective_environments = updates
|
||||
.environments
|
||||
.as_deref()
|
||||
.unwrap_or(&self.environments);
|
||||
let absolute_cwd = updates
|
||||
.cwd
|
||||
.as_ref()
|
||||
.map(|cwd| {
|
||||
let base_cwd = effective_environments
|
||||
.first()
|
||||
.map(|environment| &environment.cwd)
|
||||
.unwrap_or(&self.cwd);
|
||||
base_cwd.join(normalize_for_native_workdir(cwd.as_path()))
|
||||
AbsolutePathBuf::relative_to_current_dir(normalize_for_native_workdir(
|
||||
cwd.as_path(),
|
||||
))
|
||||
.unwrap_or_else(|e| {
|
||||
warn!("failed to normalize update cwd: {cwd:?}: {e}");
|
||||
self.cwd.clone()
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| self.cwd.clone());
|
||||
|
||||
@@ -926,7 +915,6 @@ impl Session {
|
||||
.map(|(name, _)| name.clone())
|
||||
.collect();
|
||||
required_mcp_servers.sort();
|
||||
let enabled_mcp_server_count = mcp_servers.values().filter(|server| server.enabled).count();
|
||||
let required_mcp_server_count = required_mcp_servers.len();
|
||||
let tool_plugin_provenance = mcp_manager.tool_plugin_provenance(config.as_ref()).await;
|
||||
{
|
||||
@@ -934,15 +922,30 @@ impl Session {
|
||||
cancel_guard.cancel();
|
||||
*cancel_guard = CancellationToken::new();
|
||||
}
|
||||
let mcp_runtime_environment = match sess
|
||||
.mcp_runtime_environment_for_configuration(&session_configuration)
|
||||
{
|
||||
Ok(runtime_environment) => runtime_environment,
|
||||
Err(_) if enabled_mcp_server_count == 0 => sess.fallback_mcp_runtime_environment(
|
||||
&session_configuration.cwd,
|
||||
/*require_default_environment*/ false,
|
||||
)?,
|
||||
Err(err) => return Err(err.into()),
|
||||
let turn_environment = crate::environment_selection::resolve_environment_selections(
|
||||
sess.services.environment_manager.as_ref(),
|
||||
&session_configuration.environments,
|
||||
)
|
||||
.map_err(|err| {
|
||||
CodexErr::InvalidRequest(err.to_string().replace(
|
||||
"unknown turn environment id",
|
||||
"unknown stored MCP environment id",
|
||||
))
|
||||
})?
|
||||
.primary_turn_environment()
|
||||
.cloned();
|
||||
let mcp_runtime_environment = match turn_environment {
|
||||
Some(turn_environment) => McpRuntimeEnvironment::new(
|
||||
Arc::clone(&turn_environment.environment),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
),
|
||||
None => McpRuntimeEnvironment::new(
|
||||
sess.services
|
||||
.environment_manager
|
||||
.default_environment()
|
||||
.unwrap_or_else(|| sess.services.environment_manager.local_environment()),
|
||||
session_configuration.cwd.to_path_buf(),
|
||||
),
|
||||
};
|
||||
let (mcp_connection_manager, cancel_token) = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
|
||||
@@ -3330,84 +3330,6 @@ async fn relative_cwd_update_without_environments_resolves_under_session_cwd() {
|
||||
assert!(state.session_configuration.environments.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn relative_cwd_update_with_turn_environment_is_rejected() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
let (stored_cwd, turn_environment_cwd) = {
|
||||
let mut state = session.state.lock().await;
|
||||
let stored_cwd = state.session_configuration.cwd.clone();
|
||||
let stored_environment_cwd = stored_cwd.join("stored-environment");
|
||||
let turn_environment_cwd = stored_cwd.join("turn-environment");
|
||||
state.session_configuration.environments = vec![TurnEnvironmentSelection {
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: stored_environment_cwd,
|
||||
}];
|
||||
(stored_cwd, turn_environment_cwd)
|
||||
};
|
||||
std::fs::create_dir_all(turn_environment_cwd.join("project").as_path())
|
||||
.expect("create project dir");
|
||||
|
||||
let err = session
|
||||
.new_turn_with_sub_id(
|
||||
"sub-1".to_string(),
|
||||
SessionSettingsUpdate {
|
||||
cwd: Some(PathBuf::from("project")),
|
||||
environments: Some(vec![TurnEnvironmentSelection {
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: turn_environment_cwd.clone(),
|
||||
}]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("cwd and explicit environments should be rejected");
|
||||
|
||||
let state = session.state.lock().await;
|
||||
assert!(matches!(err, CodexErr::InvalidRequest(_)));
|
||||
assert!(err.to_string().contains("cannot be updated together"));
|
||||
assert_eq!(state.session_configuration.cwd, stored_cwd);
|
||||
assert_eq!(
|
||||
state.session_configuration.environments[0].cwd,
|
||||
stored_cwd.join("stored-environment")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn relative_cwd_update_with_empty_turn_environments_is_rejected() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
let stored_cwd = {
|
||||
let mut state = session.state.lock().await;
|
||||
let stored_cwd = state.session_configuration.cwd.clone();
|
||||
state.session_configuration.environments = vec![TurnEnvironmentSelection {
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: stored_cwd.join("stored-environment"),
|
||||
}];
|
||||
stored_cwd
|
||||
};
|
||||
std::fs::create_dir_all(stored_cwd.join("project").as_path()).expect("create project dir");
|
||||
|
||||
let err = session
|
||||
.new_turn_with_sub_id(
|
||||
"sub-1".to_string(),
|
||||
SessionSettingsUpdate {
|
||||
cwd: Some(PathBuf::from("project")),
|
||||
environments: Some(Vec::new()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("cwd and explicit empty environments should be rejected");
|
||||
|
||||
let state = session.state.lock().await;
|
||||
assert!(matches!(err, CodexErr::InvalidRequest(_)));
|
||||
assert!(err.to_string().contains("cannot be updated together"));
|
||||
assert_eq!(state.session_configuration.cwd, stored_cwd);
|
||||
assert_eq!(
|
||||
state.session_configuration.environments[0].cwd,
|
||||
stored_cwd.join("stored-environment")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn absolute_cwd_update_with_turn_environment_is_allowed() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
@@ -4643,34 +4565,6 @@ async fn duplicate_turn_environment_returns_error_without_mutating_session() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_runtime_environment_for_configuration_errors_on_unknown_environment() {
|
||||
let (session, _turn_context) = make_session_and_context().await;
|
||||
{
|
||||
let mut state = session.state.lock().await;
|
||||
let cwd = state.session_configuration.cwd.clone();
|
||||
state.session_configuration.environments = vec![TurnEnvironmentSelection {
|
||||
environment_id: "missing-environment".to_string(),
|
||||
cwd,
|
||||
}];
|
||||
}
|
||||
|
||||
let session_configuration = {
|
||||
let state = session.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
let err = match session.mcp_runtime_environment_for_configuration(&session_configuration) {
|
||||
Ok(_) => panic!("unknown stored environment should fail"),
|
||||
Err(err) => err,
|
||||
};
|
||||
|
||||
assert!(matches!(err, CodexErr::InvalidRequest(_)));
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("unknown stored MCP environment id `missing-environment`")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_task_turn_span_inherits_dispatch_trace_context() {
|
||||
struct TraceCaptureTask {
|
||||
|
||||
@@ -1074,14 +1074,11 @@ impl ThreadManagerState {
|
||||
let is_resumed_thread = matches!(&initial_history, InitialHistory::Resumed(_));
|
||||
let environment_selections =
|
||||
resolve_environment_selections(self.environment_manager.as_ref(), &environments)?;
|
||||
let effective_cwd = environment_selections.primary_cwd_or_fallback(&config.cwd);
|
||||
let mut load_config = config.clone();
|
||||
load_config.cwd = effective_cwd;
|
||||
let watch_registration = match environment_selections.primary_turn_environment() {
|
||||
Some(turn_environment) if !turn_environment.environment.is_remote() => {
|
||||
self.skills_watcher
|
||||
.register_config(
|
||||
&load_config,
|
||||
&config,
|
||||
self.skills_manager.as_ref(),
|
||||
self.plugins_manager.as_ref(),
|
||||
Some(turn_environment.environment.get_filesystem()),
|
||||
|
||||
Reference in New Issue
Block a user