mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Merge branch 'main' into codex/refresh-turn-diff-environments
This commit is contained in:
@@ -810,12 +810,15 @@
|
||||
"clock_source": {
|
||||
"$ref": "#/definitions/CurrentTimeSource"
|
||||
},
|
||||
"delivery_mode": {
|
||||
"$ref": "#/definitions/CurrentTimeReminderDeliveryMode"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"reminder_interval_seconds": {
|
||||
"format": "uint64",
|
||||
"minimum": 1.0,
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
},
|
||||
"sleep_tool": {
|
||||
@@ -825,6 +828,25 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"CurrentTimeReminderDeliveryMode": {
|
||||
"description": "Which inference boundaries may receive current-time reminders.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Allow a reminder before any inference request once the interval is due.",
|
||||
"enum": [
|
||||
"any_inference"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Allow reminders after user input or tool output; new context windows still force one.",
|
||||
"enum": [
|
||||
"after_user_or_tool_output"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"CurrentTimeSource": {
|
||||
"enum": [
|
||||
"system",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::residency::is_v2_resident_session_source;
|
||||
use super::*;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
|
||||
const AGENT_NAMES: &str = include_str!("../agent_names.txt");
|
||||
|
||||
@@ -433,6 +434,16 @@ impl AgentControl {
|
||||
))
|
||||
})?;
|
||||
|
||||
let selected_capability_roots = parent_history
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| {
|
||||
let RolloutItem::SessionMeta(meta_line) = item else {
|
||||
return None;
|
||||
};
|
||||
Some(meta_line.meta.selected_capability_roots.clone())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut forked_rollout_items = parent_history.items;
|
||||
if let SpawnAgentForkMode::LastNTurns(last_n_turns) = fork_mode {
|
||||
forked_rollout_items =
|
||||
@@ -504,6 +515,8 @@ impl AgentControl {
|
||||
{
|
||||
forked_rollout_items.push(RolloutItem::ResponseItem(subagent_usage_hint_message));
|
||||
}
|
||||
let mut thread_extension_init = ExtensionDataInit::new();
|
||||
thread_extension_init.insert(selected_capability_roots);
|
||||
|
||||
state
|
||||
.fork_thread_with_source(
|
||||
@@ -517,6 +530,7 @@ impl AgentControl {
|
||||
inherited_environments,
|
||||
inherited_exec_policy,
|
||||
options.environments.clone(),
|
||||
thread_extension_init,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ use codex_features::Feature;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::MessagePhase;
|
||||
@@ -38,6 +40,7 @@ use codex_thread_store::InMemoryThreadStore;
|
||||
use codex_thread_store::LocalThreadStore;
|
||||
use codex_thread_store::LocalThreadStoreConfig;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use tokio::time::Duration;
|
||||
@@ -1446,7 +1449,34 @@ async fn spawn_agent_fork_last_n_turns_keeps_only_recent_turns() {
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_fork_last_n_turns_drops_parent_startup_prefix_when_under_limit() {
|
||||
let harness = AgentControlHarness::new().await;
|
||||
let (parent_thread_id, parent_thread) = harness.start_thread().await;
|
||||
let selected_capability_roots = vec![SelectedCapabilityRoot {
|
||||
id: "demo@1".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "build".to_string(),
|
||||
path: PathUri::parse("file:///plugins/demo").expect("plugin root URI"),
|
||||
},
|
||||
}];
|
||||
let mut thread_extension_init = ExtensionDataInit::new();
|
||||
thread_extension_init.insert(selected_capability_roots.clone());
|
||||
let parent = harness
|
||||
.manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: harness.config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
metrics_service_name: None,
|
||||
parent_trace: None,
|
||||
environments: Vec::new(),
|
||||
thread_extension_init,
|
||||
supports_openai_form_elicitation: false,
|
||||
})
|
||||
.await
|
||||
.expect("start parent thread");
|
||||
let parent_thread_id = parent.thread_id;
|
||||
let parent_thread = parent.thread;
|
||||
let startup_turn_context = parent_thread.codex.session.new_default_turn().await;
|
||||
parent_thread
|
||||
.codex
|
||||
@@ -1525,6 +1555,14 @@ async fn spawn_agent_fork_last_n_turns_drops_parent_startup_prefix_when_under_li
|
||||
!history_contains_text(history.raw_items(), "parent startup developer context"),
|
||||
"bounded fork should drop parent startup context even when fewer turns exist than requested"
|
||||
);
|
||||
assert_eq!(
|
||||
&child_thread
|
||||
.codex
|
||||
.session
|
||||
.services
|
||||
.selected_capability_roots,
|
||||
&selected_capability_roots
|
||||
);
|
||||
assert!(
|
||||
child_thread
|
||||
.codex
|
||||
@@ -2213,6 +2251,7 @@ async fn spawn_thread_subagents_persist_parent_originator_across_new_and_truncat
|
||||
.manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: harness.config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
|
||||
@@ -40,6 +40,7 @@ use crate::guardian::spawn_approval_request_review;
|
||||
use crate::mcp_tool_call::MCP_TOOL_APPROVAL_ACCEPT;
|
||||
use crate::mcp_tool_call::MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION;
|
||||
use crate::mcp_tool_call::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC;
|
||||
use crate::mcp_tool_call::McpToolApprovalMetadata;
|
||||
use crate::mcp_tool_call::build_guardian_mcp_tool_review_request;
|
||||
use crate::mcp_tool_call::is_mcp_tool_approval_question_id;
|
||||
use crate::mcp_tool_call::lookup_mcp_tool_metadata;
|
||||
@@ -60,6 +61,12 @@ use codex_protocol::protocol::MultiAgentVersion;
|
||||
#[cfg(test)]
|
||||
use crate::session::completed_session_loop_termination;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingMcpInvocation {
|
||||
invocation: McpInvocation,
|
||||
metadata: Option<McpToolApprovalMetadata>,
|
||||
}
|
||||
|
||||
/// Start an interactive sub-Codex thread and return IO channels.
|
||||
///
|
||||
/// The returned `events_rx` yields non-approval events emitted by the sub-agent.
|
||||
@@ -86,6 +93,7 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
};
|
||||
let CodexSpawnOk { codex, .. } = Box::pin(Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
allow_provider_model_fallback: false,
|
||||
user_instructions,
|
||||
installation_id: parent_session.installation_id.clone(),
|
||||
auth_manager,
|
||||
@@ -148,10 +156,10 @@ pub(crate) async fn run_codex_thread_interactive(
|
||||
let parent_session_clone = Arc::clone(&parent_session);
|
||||
let parent_ctx_clone = Arc::clone(&parent_ctx);
|
||||
let codex_for_events = Arc::clone(&codex);
|
||||
// Cache delegated MCP invocations so guardian can recover the full tool call
|
||||
// context when the later legacy RequestUserInput approval event only carries
|
||||
// a call_id plus approval question metadata.
|
||||
let pending_mcp_invocations = Arc::new(Mutex::new(HashMap::<String, McpInvocation>::new()));
|
||||
// Cache the child call's MCP metadata at begin time. The later legacy
|
||||
// RequestUserInput approval event only carries a call_id and question metadata.
|
||||
let pending_mcp_invocations =
|
||||
Arc::new(Mutex::new(HashMap::<String, PendingMcpInvocation>::new()));
|
||||
tokio::spawn(async move {
|
||||
forward_events(
|
||||
codex_for_events,
|
||||
@@ -269,7 +277,7 @@ async fn forward_events(
|
||||
tx_sub: Sender<Event>,
|
||||
parent_session: Arc<Session>,
|
||||
parent_ctx: Arc<TurnContext>,
|
||||
pending_mcp_invocations: Arc<Mutex<HashMap<String, McpInvocation>>>,
|
||||
pending_mcp_invocations: Arc<Mutex<HashMap<String, PendingMcpInvocation>>>,
|
||||
cancel_token: CancellationToken,
|
||||
) {
|
||||
let cancelled = cancel_token.cancelled();
|
||||
@@ -356,10 +364,34 @@ async fn forward_events(
|
||||
id,
|
||||
msg: EventMsg::McpToolCallBegin(event),
|
||||
} => {
|
||||
// Runtime refreshes are published before a request step is captured, so
|
||||
// the child runtime at call begin is the one executing this invocation.
|
||||
// Cache its metadata now; the later approval event has only a call ID.
|
||||
let metadata = if let Some(turn_context) =
|
||||
codex.session.turn_context_for_sub_id(&id).await
|
||||
{
|
||||
let mcp = codex.session.services.latest_mcp_runtime();
|
||||
lookup_mcp_tool_metadata(
|
||||
codex.session.as_ref(),
|
||||
turn_context.as_ref(),
|
||||
mcp.manager(),
|
||||
&event.invocation.server,
|
||||
&event.invocation.tool,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
pending_mcp_invocations
|
||||
.lock()
|
||||
.await
|
||||
.insert(event.call_id.clone(), event.invocation.clone());
|
||||
.insert(
|
||||
event.call_id.clone(),
|
||||
PendingMcpInvocation {
|
||||
invocation: event.invocation.clone(),
|
||||
metadata,
|
||||
},
|
||||
);
|
||||
if !forward_event_or_shutdown(
|
||||
&codex,
|
||||
&tx_sub,
|
||||
@@ -647,7 +679,7 @@ async fn handle_request_user_input(
|
||||
id: String,
|
||||
parent_session: &Arc<Session>,
|
||||
parent_ctx: &Arc<TurnContext>,
|
||||
pending_mcp_invocations: &Arc<Mutex<HashMap<String, McpInvocation>>>,
|
||||
pending_mcp_invocations: &Arc<Mutex<HashMap<String, PendingMcpInvocation>>>,
|
||||
event: RequestUserInputEvent,
|
||||
cancel_token: &CancellationToken,
|
||||
) {
|
||||
@@ -685,12 +717,12 @@ async fn handle_request_user_input(
|
||||
/// programmatically after running the guardian review.
|
||||
///
|
||||
/// The RequestUserInput event only carries `call_id` plus approval question
|
||||
/// metadata, so this helper joins it back to the cached `McpToolCallBegin`
|
||||
/// invocation in order to rebuild the full guardian review request.
|
||||
/// metadata, so this helper joins it back to the child runtime metadata cached at
|
||||
/// `McpToolCallBegin` in order to rebuild the full guardian review request.
|
||||
async fn maybe_auto_review_mcp_request_user_input(
|
||||
parent_session: &Arc<Session>,
|
||||
parent_ctx: &Arc<TurnContext>,
|
||||
pending_mcp_invocations: &Arc<Mutex<HashMap<String, McpInvocation>>>,
|
||||
pending_mcp_invocations: &Arc<Mutex<HashMap<String, PendingMcpInvocation>>>,
|
||||
event: &RequestUserInputEvent,
|
||||
cancel_token: &CancellationToken,
|
||||
) -> Option<RequestUserInputResponse> {
|
||||
@@ -701,18 +733,13 @@ async fn maybe_auto_review_mcp_request_user_input(
|
||||
.questions
|
||||
.iter()
|
||||
.find(|question| is_mcp_tool_approval_question_id(&question.id))?;
|
||||
let invocation = pending_mcp_invocations
|
||||
let pending = pending_mcp_invocations
|
||||
.lock()
|
||||
.await
|
||||
.get(&event.call_id)
|
||||
.cloned()?;
|
||||
let metadata = lookup_mcp_tool_metadata(
|
||||
parent_session.as_ref(),
|
||||
parent_ctx.as_ref(),
|
||||
&invocation.server,
|
||||
&invocation.tool,
|
||||
)
|
||||
.await;
|
||||
let invocation = pending.invocation;
|
||||
let metadata = pending.metadata;
|
||||
let approvals_reviewer =
|
||||
mcp_approvals_reviewer(parent_ctx, &invocation.server, metadata.as_ref());
|
||||
if !routes_approval_to_guardian_with_reviewer(parent_ctx, approvals_reviewer) {
|
||||
|
||||
@@ -411,10 +411,13 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() {
|
||||
|
||||
let pending_mcp_invocations = Arc::new(Mutex::new(HashMap::from([(
|
||||
"call-1".to_string(),
|
||||
McpInvocation {
|
||||
server: "custom_server".to_string(),
|
||||
tool: "dangerous_tool".to_string(),
|
||||
arguments: None,
|
||||
PendingMcpInvocation {
|
||||
invocation: McpInvocation {
|
||||
server: "custom_server".to_string(),
|
||||
tool: "dangerous_tool".to_string(),
|
||||
arguments: None,
|
||||
},
|
||||
metadata: None,
|
||||
},
|
||||
)])));
|
||||
let cancel_token = CancellationToken::new();
|
||||
@@ -460,10 +463,13 @@ async fn delegated_mcp_user_reviewer_returns_none_without_metadata() {
|
||||
crate::session::tests::make_session_and_context_with_rx().await;
|
||||
let pending_mcp_invocations = Arc::new(Mutex::new(HashMap::from([(
|
||||
"call-1".to_string(),
|
||||
McpInvocation {
|
||||
server: CODEX_APPS_MCP_SERVER_NAME.to_string(),
|
||||
tool: "dangerous_tool".to_string(),
|
||||
arguments: None,
|
||||
PendingMcpInvocation {
|
||||
invocation: McpInvocation {
|
||||
server: CODEX_APPS_MCP_SERVER_NAME.to_string(),
|
||||
tool: "dangerous_tool".to_string(),
|
||||
arguments: None,
|
||||
},
|
||||
metadata: None,
|
||||
},
|
||||
)])));
|
||||
let cancel_token = CancellationToken::new();
|
||||
|
||||
@@ -594,6 +594,17 @@ impl CodexThread {
|
||||
self.codex.session.runtime_mcp_config(config).await
|
||||
}
|
||||
|
||||
/// Returns the exact MCP config, environment bindings, and manager most recently published.
|
||||
pub async fn current_mcp_runtime(&self) -> Arc<crate::session::McpRuntimeSnapshot> {
|
||||
let turn_context = self.codex.session.new_default_turn().await;
|
||||
self.codex
|
||||
.session
|
||||
.capture_step_context(turn_context)
|
||||
.await
|
||||
.mcp
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub fn multi_agent_version(&self) -> Option<MultiAgentVersion> {
|
||||
self.codex.session.multi_agent_version()
|
||||
}
|
||||
@@ -615,8 +626,9 @@ impl CodexThread {
|
||||
uri: &str,
|
||||
) -> anyhow::Result<serde_json::Value> {
|
||||
let result = self
|
||||
.codex
|
||||
.session
|
||||
.current_mcp_runtime()
|
||||
.await
|
||||
.manager_arc()
|
||||
.read_resource(server, ReadResourceRequestParams::new(uri))
|
||||
.await?;
|
||||
|
||||
@@ -630,8 +642,9 @@ impl CodexThread {
|
||||
arguments: Option<serde_json::Value>,
|
||||
meta: Option<serde_json::Value>,
|
||||
) -> anyhow::Result<CallToolResult> {
|
||||
self.codex
|
||||
.session
|
||||
self.current_mcp_runtime()
|
||||
.await
|
||||
.manager_arc()
|
||||
.call_tool(server, tool, arguments, meta)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::McpServerCommandMatcher;
|
||||
use codex_config::McpServerIdentity;
|
||||
use codex_config::McpServerRequirement;
|
||||
use codex_config::McpServerValueMatcher;
|
||||
use codex_config::ProfileV2Name;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::Sourced;
|
||||
@@ -113,11 +117,15 @@ use std::time::Duration;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn stdio_mcp(command: &str) -> McpServerConfig {
|
||||
stdio_mcp_with_args(command, &[])
|
||||
}
|
||||
|
||||
fn stdio_mcp_with_args(command: &str, args: &[&str]) -> McpServerConfig {
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: command.to_string(),
|
||||
args: Vec::new(),
|
||||
args: args.iter().map(ToString::to_string).collect(),
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
@@ -625,13 +633,15 @@ current_time_reminder = true
|
||||
r#"
|
||||
[features.current_time_reminder]
|
||||
enabled = true
|
||||
reminder_interval_seconds = 4
|
||||
reminder_interval_seconds = 0
|
||||
clock_source = "external"
|
||||
delivery_mode = "after_user_or_tool_output"
|
||||
sleep_tool = true
|
||||
"#,
|
||||
CurrentTimeReminderConfig {
|
||||
reminder_interval_seconds: 4,
|
||||
reminder_interval_seconds: 0,
|
||||
clock_source: CurrentTimeSource::External,
|
||||
delivery_mode: CurrentTimeReminderDeliveryMode::AfterUserOrToolOutput,
|
||||
sleep_tool: true,
|
||||
},
|
||||
),
|
||||
@@ -643,26 +653,6 @@ sleep_tool = true
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_config_rejects_zero_current_time_reminder_interval() -> std::io::Result<()> {
|
||||
let error = load_current_time_reminder_config(
|
||||
r#"
|
||||
[features.current_time_reminder]
|
||||
enabled = true
|
||||
reminder_interval_seconds = 0
|
||||
"#,
|
||||
)
|
||||
.await
|
||||
.expect_err("zero reminder interval should be rejected");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"features.current_time_reminder.reminder_interval_seconds must be positive"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_current_time_reminder_config(config_toml: &str) -> std::io::Result<Config> {
|
||||
let codex_home = tempdir()?;
|
||||
let config_toml = toml::from_str(config_toml).expect("TOML should deserialize");
|
||||
@@ -4146,7 +4136,7 @@ fn filter_mcp_servers_by_allowlist_enforces_identity_rules() {
|
||||
BTreeMap::from([
|
||||
(
|
||||
MISMATCHED_URL_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Url {
|
||||
url: "https://example.com/other".to_string(),
|
||||
},
|
||||
@@ -4154,7 +4144,7 @@ fn filter_mcp_servers_by_allowlist_enforces_identity_rules() {
|
||||
),
|
||||
(
|
||||
MISMATCHED_COMMAND_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "other-cmd".to_string(),
|
||||
},
|
||||
@@ -4162,7 +4152,7 @@ fn filter_mcp_servers_by_allowlist_enforces_identity_rules() {
|
||||
),
|
||||
(
|
||||
MATCHED_URL_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Url {
|
||||
url: GOOD_URL.to_string(),
|
||||
},
|
||||
@@ -4170,7 +4160,7 @@ fn filter_mcp_servers_by_allowlist_enforces_identity_rules() {
|
||||
),
|
||||
(
|
||||
MATCHED_COMMAND_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: GOOD_CMD.to_string(),
|
||||
},
|
||||
@@ -4227,6 +4217,117 @@ fn filter_mcp_servers_by_allowlist_allows_all_when_unset() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_mcp_servers_by_matchers_enforces_command_and_positional_args() {
|
||||
let mut servers = HashMap::from([
|
||||
(
|
||||
"internal_mcp_proxy".to_string(),
|
||||
stdio_mcp_with_args(
|
||||
"company-cli",
|
||||
&[
|
||||
"mcp",
|
||||
"proxy",
|
||||
"--server",
|
||||
"https://pricing.mcp.internal.example.com",
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"unlisted".to_string(),
|
||||
stdio_mcp_with_args(
|
||||
"company-cli",
|
||||
&[
|
||||
"mcp",
|
||||
"proxy",
|
||||
"--server",
|
||||
"https://pricing.mcp.internal.example.com",
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"wrong-order".to_string(),
|
||||
stdio_mcp_with_args(
|
||||
"company-cli",
|
||||
&[
|
||||
"proxy",
|
||||
"mcp",
|
||||
"--server",
|
||||
"https://pricing.mcp.internal.example.com",
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"trailing-arg".to_string(),
|
||||
stdio_mcp_with_args(
|
||||
"company-cli",
|
||||
&[
|
||||
"mcp",
|
||||
"proxy",
|
||||
"--server",
|
||||
"https://pricing.mcp.internal.example.com",
|
||||
"--verbose",
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"wrong-host".to_string(),
|
||||
stdio_mcp_with_args(
|
||||
"company-cli",
|
||||
&["mcp", "proxy", "--server", "https://mcp.example.com"],
|
||||
),
|
||||
),
|
||||
]);
|
||||
let source = RequirementSource::LegacyManagedConfigTomlFromMdm;
|
||||
let requirement = McpServerRequirement::Command(McpServerCommandMatcher {
|
||||
executable: "company-cli".to_string(),
|
||||
args: vec![
|
||||
McpServerValueMatcher::Exact {
|
||||
value: "mcp".to_string(),
|
||||
},
|
||||
McpServerValueMatcher::Exact {
|
||||
value: "proxy".to_string(),
|
||||
},
|
||||
McpServerValueMatcher::Exact {
|
||||
value: "--server".to_string(),
|
||||
},
|
||||
McpServerValueMatcher::Regex {
|
||||
expression:
|
||||
r"^https://[A-Za-z0-9-]+\.mcp\.internal\.example\.com(?::443)?(?:/.*)?$"
|
||||
.to_string(),
|
||||
},
|
||||
],
|
||||
});
|
||||
let requirements = Sourced::new(
|
||||
BTreeMap::from([
|
||||
("internal_mcp_proxy".to_string(), requirement.clone()),
|
||||
("wrong-order".to_string(), requirement.clone()),
|
||||
("trailing-arg".to_string(), requirement.clone()),
|
||||
("wrong-host".to_string(), requirement),
|
||||
]),
|
||||
source.clone(),
|
||||
);
|
||||
|
||||
filter_mcp_servers_by_requirements(&mut servers, Some(&requirements));
|
||||
|
||||
let reason = Some(McpServerDisabledReason::Requirements { source });
|
||||
assert_eq!(
|
||||
servers
|
||||
.iter()
|
||||
.map(|(name, server)| (
|
||||
name.clone(),
|
||||
(server.enabled, server.disabled_reason.clone())
|
||||
))
|
||||
.collect::<HashMap<String, (bool, Option<McpServerDisabledReason>)>>(),
|
||||
HashMap::from([
|
||||
("internal_mcp_proxy".to_string(), (true, None)),
|
||||
("unlisted".to_string(), (false, reason.clone())),
|
||||
("wrong-order".to_string(), (false, reason.clone())),
|
||||
("trailing-arg".to_string(), (false, reason.clone())),
|
||||
("wrong-host".to_string(), (false, reason)),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_mcp_servers_by_allowlist_blocks_all_when_empty() {
|
||||
let mut servers = HashMap::from([
|
||||
@@ -4277,7 +4378,7 @@ fn filter_plugin_mcp_servers_by_allowlist_enforces_plugin_and_identity_rules() {
|
||||
mcp_servers: Some(BTreeMap::from([
|
||||
(
|
||||
MATCHED_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: GOOD_CMD.to_string(),
|
||||
},
|
||||
@@ -4285,7 +4386,7 @@ fn filter_plugin_mcp_servers_by_allowlist_enforces_plugin_and_identity_rules() {
|
||||
),
|
||||
(
|
||||
MISMATCHED_SERVER.to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: GOOD_CMD.to_string(),
|
||||
},
|
||||
@@ -4326,7 +4427,7 @@ fn filter_plugin_mcp_servers_by_allowlist_blocks_unlisted_plugin() {
|
||||
codex_config::PluginRequirementsToml {
|
||||
mcp_servers: Some(BTreeMap::from([(
|
||||
"server-a".to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "cmd-a".to_string(),
|
||||
},
|
||||
@@ -4357,6 +4458,65 @@ fn filter_plugin_mcp_servers_by_allowlist_blocks_unlisted_plugin() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_plugin_mcp_servers_by_matchers_enforces_name_and_invocation() {
|
||||
const MATCHED_SERVER: &str = "matched";
|
||||
const MISMATCHED_SERVER: &str = "mismatched";
|
||||
const UNLISTED_SERVER: &str = "unlisted";
|
||||
|
||||
let mut servers = HashMap::from([
|
||||
(
|
||||
MATCHED_SERVER.to_string(),
|
||||
stdio_mcp_with_args("company-cli", &["approved"]),
|
||||
),
|
||||
(
|
||||
MISMATCHED_SERVER.to_string(),
|
||||
stdio_mcp_with_args("company-cli", &["rejected"]),
|
||||
),
|
||||
(
|
||||
UNLISTED_SERVER.to_string(),
|
||||
stdio_mcp_with_args("company-cli", &["approved"]),
|
||||
),
|
||||
]);
|
||||
let source = RequirementSource::LegacyManagedConfigTomlFromMdm;
|
||||
let requirement = McpServerRequirement::Command(McpServerCommandMatcher {
|
||||
executable: "company-cli".to_string(),
|
||||
args: vec![McpServerValueMatcher::Exact {
|
||||
value: "approved".to_string(),
|
||||
}],
|
||||
});
|
||||
let requirements = Sourced::new(
|
||||
BTreeMap::from([(
|
||||
"sample@test".to_string(),
|
||||
codex_config::PluginRequirementsToml {
|
||||
mcp_servers: Some(BTreeMap::from([
|
||||
(MATCHED_SERVER.to_string(), requirement.clone()),
|
||||
(MISMATCHED_SERVER.to_string(), requirement),
|
||||
])),
|
||||
},
|
||||
)]),
|
||||
source.clone(),
|
||||
);
|
||||
|
||||
filter_plugin_mcp_servers_by_requirements("sample@test", &mut servers, Some(&requirements));
|
||||
|
||||
let reason = Some(McpServerDisabledReason::Requirements { source });
|
||||
assert_eq!(
|
||||
servers
|
||||
.iter()
|
||||
.map(|(name, server)| (
|
||||
name.clone(),
|
||||
(server.enabled, server.disabled_reason.clone())
|
||||
))
|
||||
.collect::<HashMap<String, (bool, Option<McpServerDisabledReason>)>>(),
|
||||
HashMap::from([
|
||||
(MATCHED_SERVER.to_string(), (true, None)),
|
||||
(MISMATCHED_SERVER.to_string(), (false, reason.clone())),
|
||||
(UNLISTED_SERVER.to_string(), (false, reason)),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rebuild_preserving_session_layers_refreshes_requirements() -> std::io::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
@@ -4366,7 +4526,7 @@ async fn rebuild_preserving_session_layers_refreshes_requirements() -> std::io::
|
||||
let mcp_requirements = BTreeMap::from([
|
||||
(
|
||||
"session_overrides_user".to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "session-command".to_string(),
|
||||
},
|
||||
@@ -4374,7 +4534,7 @@ async fn rebuild_preserving_session_layers_refreshes_requirements() -> std::io::
|
||||
),
|
||||
(
|
||||
"managed_overrides_session".to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "managed-command".to_string(),
|
||||
},
|
||||
@@ -4382,7 +4542,7 @@ async fn rebuild_preserving_session_layers_refreshes_requirements() -> std::io::
|
||||
),
|
||||
(
|
||||
"fresh_global".to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "fresh-global-command".to_string(),
|
||||
},
|
||||
@@ -4390,7 +4550,7 @@ async fn rebuild_preserving_session_layers_refreshes_requirements() -> std::io::
|
||||
),
|
||||
(
|
||||
"fresh_project".to_string(),
|
||||
McpServerRequirement {
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "fresh-project-command".to_string(),
|
||||
},
|
||||
|
||||
@@ -14,7 +14,6 @@ use codex_config::ConfigRequirements;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use codex_config::ConstrainedWithSource;
|
||||
use codex_config::FeatureRequirementsToml;
|
||||
use codex_config::McpServerIdentity;
|
||||
use codex_config::McpServerRequirement;
|
||||
use codex_config::PluginRequirementsToml;
|
||||
use codex_config::ProfileV2Name;
|
||||
@@ -40,7 +39,6 @@ use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::History;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::McpServerDisabledReason;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_config::types::MemoriesConfig;
|
||||
use codex_config::types::ModelAvailabilityNuxConfig;
|
||||
use codex_config::types::Notice;
|
||||
@@ -59,6 +57,7 @@ use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::CodeModeConfigToml;
|
||||
use codex_features::CurrentTimeReminderConfigToml;
|
||||
use codex_features::CurrentTimeReminderDeliveryMode;
|
||||
use codex_features::CurrentTimeSource;
|
||||
use codex_features::Feature;
|
||||
use codex_features::FeatureConfigSource;
|
||||
@@ -1120,6 +1119,7 @@ pub struct RolloutBudgetConfig {
|
||||
pub struct CurrentTimeReminderConfig {
|
||||
pub reminder_interval_seconds: u64,
|
||||
pub clock_source: CurrentTimeSource,
|
||||
pub delivery_mode: CurrentTimeReminderDeliveryMode,
|
||||
/// Whether to expose the input-interruptible `clock.sleep` tool.
|
||||
pub sleep_tool: bool,
|
||||
}
|
||||
@@ -1129,6 +1129,7 @@ impl Default for CurrentTimeReminderConfig {
|
||||
Self {
|
||||
reminder_interval_seconds: 1,
|
||||
clock_source: CurrentTimeSource::System,
|
||||
delivery_mode: CurrentTimeReminderDeliveryMode::AnyInference,
|
||||
sleep_tool: false,
|
||||
}
|
||||
}
|
||||
@@ -1887,7 +1888,7 @@ fn filter_mcp_servers_by_requirements(
|
||||
let allowed = allowlist
|
||||
.value
|
||||
.get(name)
|
||||
.is_some_and(|requirement| mcp_server_matches_requirement(requirement, server));
|
||||
.is_some_and(|requirement| requirement.matches(server));
|
||||
if allowed {
|
||||
server.disabled_reason = None;
|
||||
} else {
|
||||
@@ -1916,7 +1917,7 @@ fn filter_plugin_mcp_servers_by_requirements(
|
||||
for (name, server) in mcp_servers.iter_mut() {
|
||||
let allowed = plugin_mcp_requirements
|
||||
.and_then(|mcp_requirements| mcp_requirements.get(name))
|
||||
.is_some_and(|requirement| mcp_server_matches_requirement(requirement, server));
|
||||
.is_some_and(|requirement| requirement.matches(server));
|
||||
if allowed {
|
||||
server.disabled_reason = None;
|
||||
} else {
|
||||
@@ -1979,26 +1980,6 @@ where
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn mcp_server_matches_requirement(
|
||||
requirement: &McpServerRequirement,
|
||||
server: &McpServerConfig,
|
||||
) -> bool {
|
||||
match &requirement.identity {
|
||||
McpServerIdentity::Command {
|
||||
command: want_command,
|
||||
} => matches!(
|
||||
&server.transport,
|
||||
McpServerTransportConfig::Stdio { command: got_command, .. }
|
||||
if got_command == want_command
|
||||
),
|
||||
McpServerIdentity::Url { url: want_url } => matches!(
|
||||
&server.transport,
|
||||
McpServerTransportConfig::StreamableHttp { url: got_url, .. }
|
||||
if got_url == want_url
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_global_mcp_servers(
|
||||
codex_home: &Path,
|
||||
) -> std::io::Result<BTreeMap<String, McpServerConfig>> {
|
||||
@@ -2685,18 +2666,15 @@ fn resolve_current_time_reminder_config(
|
||||
let reminder_interval_seconds = base
|
||||
.and_then(|config| config.reminder_interval_seconds)
|
||||
.unwrap_or(default.reminder_interval_seconds);
|
||||
if reminder_interval_seconds == 0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"features.current_time_reminder.reminder_interval_seconds must be positive",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Some(CurrentTimeReminderConfig {
|
||||
reminder_interval_seconds,
|
||||
clock_source: base
|
||||
.and_then(|config| config.clock_source)
|
||||
.unwrap_or(default.clock_source),
|
||||
delivery_mode: base
|
||||
.and_then(|config| config.delivery_mode)
|
||||
.unwrap_or(default.delivery_mode),
|
||||
sleep_tool: base
|
||||
.and_then(|config| config.sleep_tool)
|
||||
.unwrap_or(default.sleep_tool),
|
||||
|
||||
@@ -246,11 +246,14 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
});
|
||||
}
|
||||
|
||||
let runtime_context =
|
||||
McpRuntimeContext::new(Arc::clone(&environment_manager), config.cwd.to_path_buf());
|
||||
let auth_status_entries = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
auth.as_ref(),
|
||||
&runtime_context,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -270,8 +273,9 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
PermissionProfile::default(),
|
||||
// Connector discovery is threadless. Use an actually configured env if
|
||||
// one exists, but do not reintroduce the old hidden-local fallback.
|
||||
McpRuntimeContext::new(environment_manager, config.cwd.to_path_buf()),
|
||||
runtime_context,
|
||||
config.codex_home.to_path_buf(),
|
||||
mcp_manager.codex_apps_tools_cache(),
|
||||
codex_apps_tools_cache_key(auth.as_ref()),
|
||||
mcp_config.prefix_mcp_tool_names,
|
||||
mcp_config.client_elicitation_capability,
|
||||
|
||||
@@ -2,6 +2,9 @@ mod agents_md;
|
||||
mod environment;
|
||||
|
||||
use crate::context::ContextualUserFragment;
|
||||
use codex_extension_api::PreviousWorldStateSection;
|
||||
use codex_extension_api::RenderedWorldStateFragment;
|
||||
use codex_extension_api::WorldStateSectionContribution;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use indexmap::IndexMap;
|
||||
@@ -83,6 +86,54 @@ impl<S: WorldStateSection> ErasedWorldStateSection for S {
|
||||
}
|
||||
}
|
||||
|
||||
struct ExtensionWorldStateSection(WorldStateSectionContribution);
|
||||
|
||||
impl ErasedWorldStateSection for ExtensionWorldStateSection {
|
||||
fn snapshot(&self) -> Option<Value> {
|
||||
let mut snapshot = self.0.snapshot().clone();
|
||||
remove_null_object_fields(&mut snapshot);
|
||||
(!snapshot.is_null()).then_some(snapshot)
|
||||
}
|
||||
|
||||
fn matches_legacy_fragment(&self, role: &str, text: &str) -> bool {
|
||||
self.0.matches_legacy_fragment(role, text)
|
||||
}
|
||||
|
||||
fn render_diff(
|
||||
&self,
|
||||
previous: PreviousSectionState<'_, Value>,
|
||||
) -> Option<Box<dyn ContextualUserFragment>> {
|
||||
let previous = match previous {
|
||||
PreviousSectionState::Absent => PreviousWorldStateSection::Absent,
|
||||
PreviousSectionState::Unknown => PreviousWorldStateSection::Unknown,
|
||||
PreviousSectionState::Known(previous) => PreviousWorldStateSection::Known(previous),
|
||||
};
|
||||
self.0
|
||||
.render_diff(previous)
|
||||
.map(|fragment| Box::new(WorldStateContextFragment(fragment)) as _)
|
||||
}
|
||||
}
|
||||
|
||||
struct WorldStateContextFragment(RenderedWorldStateFragment);
|
||||
|
||||
impl ContextualUserFragment for WorldStateContextFragment {
|
||||
fn role(&self) -> &'static str {
|
||||
self.0.role()
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
self.0.markers()
|
||||
}
|
||||
|
||||
fn body(&self) -> String {
|
||||
self.0.body().to_string()
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("", "")
|
||||
}
|
||||
}
|
||||
|
||||
/// What is known about a section's previously model-visible state.
|
||||
pub(crate) enum PreviousSectionState<'a, T> {
|
||||
/// No persisted snapshot or matching fragment exists in retained history.
|
||||
@@ -169,6 +220,16 @@ impl WorldState {
|
||||
self.sections.insert(id, Box::new(section));
|
||||
}
|
||||
|
||||
pub(crate) fn add_extension_section(&mut self, section: WorldStateSectionContribution) {
|
||||
let id = section.id();
|
||||
assert!(
|
||||
!self.sections.contains_key(id),
|
||||
"duplicate world-state section ID: {id}"
|
||||
);
|
||||
self.sections
|
||||
.insert(id, Box::new(ExtensionWorldStateSection(section)));
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot(&self) -> WorldStateSnapshot {
|
||||
WorldStateSnapshot {
|
||||
sections: self
|
||||
|
||||
@@ -110,6 +110,45 @@ fn render_diff_restores_the_typed_section_snapshot() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_owned_section_uses_its_snapshot_and_renderer() {
|
||||
let mut world_state = WorldState::default();
|
||||
world_state.add_extension_section(WorldStateSectionContribution::new(
|
||||
"extension_test",
|
||||
json!({"value": "after", "optional": null}),
|
||||
|previous| match previous {
|
||||
PreviousWorldStateSection::Known(previous)
|
||||
if previous == &json!({"value": "before"}) =>
|
||||
{
|
||||
Some(RenderedWorldStateFragment::new(
|
||||
"developer",
|
||||
("<extension_test>", "</extension_test>"),
|
||||
"after",
|
||||
))
|
||||
}
|
||||
PreviousWorldStateSection::Absent
|
||||
| PreviousWorldStateSection::Unknown
|
||||
| PreviousWorldStateSection::Known(_) => None,
|
||||
},
|
||||
));
|
||||
let previous = WorldStateSnapshot {
|
||||
sections: BTreeMap::from([("extension_test".to_string(), json!({"value": "before"}))]),
|
||||
};
|
||||
|
||||
let rendered = world_state.render_diff(&previous);
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(world_state.snapshot()).expect("serialize world-state snapshot"),
|
||||
json!({"extension_test": {"value": "after"}})
|
||||
);
|
||||
assert_eq!(rendered.len(), 1);
|
||||
assert_eq!(rendered[0].role(), "developer");
|
||||
assert_eq!(
|
||||
rendered[0].render(),
|
||||
"<extension_test>after</extension_test>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_section_snapshot_is_treated_as_unknown() {
|
||||
let mut current = WorldState::default();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
@@ -227,6 +228,24 @@ pub(crate) struct TurnEnvironmentSnapshot {
|
||||
}
|
||||
|
||||
impl TurnEnvironmentSnapshot {
|
||||
/// Maps each captured environment to its exact ready handle, or `None` when it was starting.
|
||||
pub(crate) fn captured_environments(&self) -> HashMap<String, Option<Arc<Environment>>> {
|
||||
self.turn_environments
|
||||
.iter()
|
||||
.map(|environment| {
|
||||
(
|
||||
environment.environment_id.clone(),
|
||||
Some(Arc::clone(&environment.environment)),
|
||||
)
|
||||
})
|
||||
.chain(
|
||||
self.starting
|
||||
.iter()
|
||||
.map(|environment| (environment.selection.environment_id.clone(), None)),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn primary(&self) -> Option<&TurnEnvironment> {
|
||||
self.turn_environments.first()
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@ use codex_protocol::ThreadId;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::config_types::EnvironmentVariablePattern;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicy;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::shell_environment;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub use codex_protocol::shell_environment::CODEX_THREAD_ID_ENV_VAR;
|
||||
|
||||
/// Informational name of the active permission profile. Child processes can
|
||||
/// overwrite this value, so it must not be treated as proof of enforcement.
|
||||
pub const CODEX_PERMISSION_PROFILE_ENV_VAR: &str = "CODEX_PERMISSION_PROFILE";
|
||||
|
||||
/// Construct an environment map based on the rules in the specified policy. The
|
||||
/// resulting map can be passed directly to `Command::envs()` after calling
|
||||
/// `env_clear()` to ensure no unintended variables are leaked to the spawned
|
||||
@@ -25,6 +30,27 @@ pub fn create_env(
|
||||
shell_environment::create_env(policy, thread_id.as_deref())
|
||||
}
|
||||
|
||||
/// Injects the selected named permission profile into a shell tool's environment.
|
||||
///
|
||||
/// This is applied after the shell environment policy so the runtime-selected
|
||||
/// profile wins over inherited or configured values.
|
||||
pub(crate) fn inject_permission_profile_env(
|
||||
env: &mut HashMap<String, String>,
|
||||
active_permission_profile: Option<&ActivePermissionProfile>,
|
||||
) {
|
||||
if cfg!(windows) {
|
||||
env.retain(|key, _| !key.eq_ignore_ascii_case(CODEX_PERMISSION_PROFILE_ENV_VAR));
|
||||
} else {
|
||||
env.remove(CODEX_PERMISSION_PROFILE_ENV_VAR);
|
||||
}
|
||||
if let Some(active_permission_profile) = active_permission_profile {
|
||||
env.insert(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
active_permission_profile.id.clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "windows"))]
|
||||
fn create_env_from_vars<I>(
|
||||
vars: I,
|
||||
|
||||
@@ -10,6 +10,59 @@ fn make_vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_permission_profile_env_overrides_policy_value() {
|
||||
let mut env = HashMap::from([(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"stale-profile".to_string(),
|
||||
)]);
|
||||
|
||||
inject_permission_profile_env(
|
||||
&mut env,
|
||||
Some(&ActivePermissionProfile::new("current-profile")),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
env.get(CODEX_PERMISSION_PROFILE_ENV_VAR)
|
||||
.map(String::as_str),
|
||||
Some("current-profile")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_permission_profile_env_removes_stale_value_without_active_profile() {
|
||||
let mut env = HashMap::from([(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"stale-profile".to_string(),
|
||||
)]);
|
||||
|
||||
inject_permission_profile_env(&mut env, /*active_permission_profile*/ None);
|
||||
|
||||
assert_eq!(env.get(CODEX_PERMISSION_PROFILE_ENV_VAR), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn inject_permission_profile_env_replaces_differently_cased_windows_key() {
|
||||
let mut env = HashMap::from([(
|
||||
"codex_permission_profile".to_string(),
|
||||
"stale-profile".to_string(),
|
||||
)]);
|
||||
|
||||
inject_permission_profile_env(
|
||||
&mut env,
|
||||
Some(&ActivePermissionProfile::new("current-profile")),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
env,
|
||||
HashMap::from([(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"current-profile".to_string(),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_core_inherit_defaults_keep_sensitive_vars() {
|
||||
let vars = make_vars(&[
|
||||
|
||||
+45
-13
@@ -3,13 +3,17 @@ use std::sync::Arc;
|
||||
|
||||
use crate::config::Config;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_connectors::ConnectorSnapshot;
|
||||
use codex_connectors::PluginConnectorSource;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::CodexAppsToolsCache;
|
||||
use codex_mcp::EffectiveMcpServer;
|
||||
use codex_mcp::McpConfig;
|
||||
use codex_mcp::McpPluginAttribution;
|
||||
@@ -17,6 +21,7 @@ use codex_mcp::McpServerRegistration;
|
||||
use codex_mcp::codex_apps_mcp_server_config;
|
||||
use codex_mcp::configured_mcp_servers;
|
||||
use codex_mcp::effective_mcp_servers;
|
||||
use codex_plugin::AppConnectorId;
|
||||
|
||||
const LEGACY_CODEX_APPS_REGISTRATION_ID: &str = "legacy_codex_apps";
|
||||
|
||||
@@ -38,14 +43,15 @@ enum OrderedMcpOverlay {
|
||||
pub struct McpManager {
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
extensions: Arc<ExtensionRegistry<Config>>,
|
||||
codex_apps_tools_cache: CodexAppsToolsCache,
|
||||
}
|
||||
|
||||
impl McpManager {
|
||||
pub fn new(plugins_manager: Arc<PluginsManager>) -> Self {
|
||||
Self {
|
||||
Self::new_with_extensions(
|
||||
plugins_manager,
|
||||
extensions: codex_extension_api::empty_extension_registry(),
|
||||
}
|
||||
codex_extension_api::empty_extension_registry(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a manager that resolves host-installed MCP contributions.
|
||||
@@ -56,34 +62,43 @@ impl McpManager {
|
||||
Self {
|
||||
plugins_manager,
|
||||
extensions,
|
||||
codex_apps_tools_cache: CodexAppsToolsCache::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codex_apps_tools_cache(&self) -> CodexAppsToolsCache {
|
||||
self.codex_apps_tools_cache.clone()
|
||||
}
|
||||
|
||||
/// Returns the MCP config after applying compatibility built-ins and
|
||||
/// runtime-only extension overlays.
|
||||
pub async fn runtime_config(&self, config: &Config) -> McpConfig {
|
||||
self.runtime_config_with_context(config, /*thread_init*/ None)
|
||||
self.runtime_config_with_context(McpServerContributionContext::global(config))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn runtime_config_for_thread(
|
||||
pub(crate) async fn runtime_config_for_step(
|
||||
&self,
|
||||
config: &Config,
|
||||
thread_init: &ExtensionDataInit,
|
||||
thread_store: &ExtensionData,
|
||||
available_environment_ids: &[String],
|
||||
) -> McpConfig {
|
||||
self.runtime_config_with_context(config, Some(thread_init))
|
||||
.await
|
||||
self.runtime_config_with_context(McpServerContributionContext::for_step(
|
||||
config,
|
||||
thread_init,
|
||||
thread_store,
|
||||
available_environment_ids,
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn runtime_config_with_context(
|
||||
&self,
|
||||
config: &Config,
|
||||
thread_init: Option<&ExtensionDataInit>,
|
||||
context: McpServerContributionContext<'_, Config>,
|
||||
) -> McpConfig {
|
||||
let context = match thread_init {
|
||||
Some(thread_init) => McpServerContributionContext::for_thread(config, thread_init),
|
||||
None => McpServerContributionContext::global(config),
|
||||
};
|
||||
let config = context.config();
|
||||
let mut selected_plugin_connector_sources = Vec::new();
|
||||
let mut selected_plugin_registrations = Vec::new();
|
||||
let mut overlays = Vec::new();
|
||||
// A contributor can emit multiple ordered actions, so order each action globally rather
|
||||
@@ -114,6 +129,17 @@ impl McpManager {
|
||||
*config,
|
||||
),
|
||||
),
|
||||
McpServerContribution::SelectedPluginConnectors {
|
||||
plugin_id,
|
||||
plugin_display_name,
|
||||
connector_ids,
|
||||
} => selected_plugin_connector_sources.push(
|
||||
PluginConnectorSource::from_connector_ids(
|
||||
plugin_id,
|
||||
plugin_display_name,
|
||||
connector_ids.into_iter().map(AppConnectorId),
|
||||
),
|
||||
),
|
||||
McpServerContribution::Remove { name } => {
|
||||
overlays.push(OrderedMcpOverlay::Remove {
|
||||
contributor_id: contributor.id(),
|
||||
@@ -179,6 +205,12 @@ impl McpManager {
|
||||
);
|
||||
}
|
||||
mcp_config.mcp_server_catalog = catalog;
|
||||
mcp_config.connector_snapshot =
|
||||
mcp_config
|
||||
.connector_snapshot
|
||||
.merged_with(&ConnectorSnapshot::from_plugin_sources(
|
||||
selected_plugin_connector_sources,
|
||||
));
|
||||
mcp_config
|
||||
}
|
||||
|
||||
|
||||
@@ -199,15 +199,8 @@ pub(crate) async fn maybe_install_mcp_dependencies(
|
||||
warn!("failed to refresh MCP dependencies for mentioned skills: {err}");
|
||||
return;
|
||||
}
|
||||
let refresh_servers = sess.runtime_mcp_servers(&refresh_config).await;
|
||||
sess.refresh_mcp_servers_now(
|
||||
turn_context,
|
||||
refresh_servers,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
sess.refresh_mcp_servers_now(turn_context, &refresh_config, elicitation_reviewer)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn should_install_mcp_dependencies(
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::mcp_openai_file::rewrite_mcp_tool_arguments_for_openai_files;
|
||||
use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam;
|
||||
use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::step_context::StepContext;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::tools::sandboxing::PermissionRequestPayload;
|
||||
@@ -35,6 +36,7 @@ use codex_features::Feature;
|
||||
use codex_hooks::PermissionRequestDecision;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_mcp::McpConnectionManager;
|
||||
use codex_mcp::McpPermissionPromptAutoApproveContext;
|
||||
use codex_mcp::SandboxState;
|
||||
use codex_mcp::auth_elicitation_completed_result;
|
||||
@@ -111,13 +113,15 @@ const MCP_TOOL_CALL_EVENT_RESULT_MAX_BYTES: usize = DEFAULT_OUTPUT_BYTES_CAP;
|
||||
/// item lifecycle events to the `Session`.
|
||||
pub(crate) async fn handle_mcp_tool_call(
|
||||
sess: Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
step_context: &Arc<StepContext>,
|
||||
call_id: String,
|
||||
server: String,
|
||||
tool_name: String,
|
||||
hook_tool_name: HookToolName,
|
||||
arguments: String,
|
||||
) -> HandledMcpToolCall {
|
||||
let turn_context = &step_context.turn;
|
||||
let manager = step_context.mcp.manager();
|
||||
// Parse the `arguments` as JSON. An empty string is OK, but invalid JSON
|
||||
// is not.
|
||||
let arguments_value = if arguments.trim().is_empty() {
|
||||
@@ -141,8 +145,14 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
arguments: arguments_value.clone(),
|
||||
};
|
||||
|
||||
let metadata =
|
||||
lookup_mcp_tool_metadata(sess.as_ref(), turn_context.as_ref(), &server, &tool_name).await;
|
||||
let metadata = lookup_mcp_tool_metadata(
|
||||
sess.as_ref(),
|
||||
turn_context.as_ref(),
|
||||
manager,
|
||||
&server,
|
||||
&tool_name,
|
||||
)
|
||||
.await;
|
||||
let item_metadata = McpToolCallItemMetadata::from_tool_metadata(&server, metadata.as_ref());
|
||||
let app_tool_policy = if server == CODEX_APPS_MCP_SERVER_NAME {
|
||||
let annotations = metadata
|
||||
@@ -169,7 +179,6 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
} else if let Some(approval_mode) = {
|
||||
// Selected-plugin registrations are absent from config.toml and the legacy plugin manager,
|
||||
// so their resolved catalog entry is the authoritative source for tool approval policy.
|
||||
let manager = sess.services.mcp_connection_manager.load();
|
||||
manager
|
||||
.is_selected_plugin_mcp_server(&server)
|
||||
.then(|| manager.tool_approval_mode(&server, &tool_name))
|
||||
@@ -226,7 +235,7 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
|
||||
if let Some(decision) = maybe_request_mcp_tool_approval(
|
||||
&sess,
|
||||
turn_context,
|
||||
step_context,
|
||||
&call_id,
|
||||
&invocation,
|
||||
&hook_tool_name,
|
||||
@@ -241,7 +250,7 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
| McpToolApprovalDecision::AcceptAndRemember => {
|
||||
return handle_approved_mcp_tool_call(
|
||||
sess.as_ref(),
|
||||
turn_context.as_ref(),
|
||||
step_context.as_ref(),
|
||||
&call_id,
|
||||
invocation,
|
||||
metadata.as_ref(),
|
||||
@@ -298,7 +307,7 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
|
||||
handle_approved_mcp_tool_call(
|
||||
sess.as_ref(),
|
||||
turn_context.as_ref(),
|
||||
step_context.as_ref(),
|
||||
&call_id,
|
||||
invocation,
|
||||
metadata.as_ref(),
|
||||
@@ -340,24 +349,21 @@ impl McpToolCallItemMetadata {
|
||||
|
||||
async fn handle_approved_mcp_tool_call(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
step_context: &StepContext,
|
||||
call_id: &str,
|
||||
invocation: McpInvocation,
|
||||
metadata: Option<&McpToolApprovalMetadata>,
|
||||
item_metadata: McpToolCallItemMetadata,
|
||||
) -> HandledMcpToolCall {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let manager = step_context.mcp.manager();
|
||||
let server = invocation.server.clone();
|
||||
maybe_mark_thread_memory_mode_polluted(sess, turn_context, &server).await;
|
||||
maybe_mark_thread_memory_mode_polluted(sess, turn_context, manager, &server).await;
|
||||
let tool_name = invocation.tool.clone();
|
||||
let arguments_value = invocation.arguments.clone();
|
||||
let connector_id = metadata.and_then(|metadata| metadata.connector_id.as_deref());
|
||||
let connector_name = metadata.and_then(|metadata| metadata.connector_name.as_deref());
|
||||
let server_origin = {
|
||||
let mcp_connection_manager = sess.services.mcp_connection_manager.load_full();
|
||||
mcp_connection_manager
|
||||
.server_origin(&server)
|
||||
.map(str::to_string)
|
||||
};
|
||||
let server_origin = manager.server_origin(&server).map(str::to_string);
|
||||
|
||||
let start = Instant::now();
|
||||
let rewrite = rewrite_mcp_tool_arguments_for_openai_files(
|
||||
@@ -380,7 +386,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
build_mcp_tool_call_request_meta(turn_context, &server, call_id, metadata);
|
||||
execute_mcp_tool_call(
|
||||
sess,
|
||||
turn_context,
|
||||
step_context,
|
||||
call_id,
|
||||
&invocation,
|
||||
rewritten_arguments,
|
||||
@@ -420,7 +426,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
truncate_mcp_tool_result_for_event(&result),
|
||||
)
|
||||
.await;
|
||||
maybe_track_codex_app_used(sess, turn_context, &server, &tool_name).await;
|
||||
maybe_track_codex_app_used(sess, turn_context, manager, &server, &tool_name).await;
|
||||
|
||||
let outcome = mcp_call_metric_outcome(&result);
|
||||
emit_mcp_call_metrics(
|
||||
@@ -547,17 +553,19 @@ fn truncate_str_to_char_boundary(value: &str, max_chars: usize) -> &str {
|
||||
|
||||
async fn execute_mcp_tool_call(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
step_context: &StepContext,
|
||||
call_id: &str,
|
||||
invocation: &McpInvocation,
|
||||
rewritten_arguments: Option<JsonValue>,
|
||||
metadata: Option<&McpToolApprovalMetadata>,
|
||||
request_meta: Option<JsonValue>,
|
||||
) -> Result<CallToolResult, String> {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let manager = step_context.mcp.manager();
|
||||
let request_meta = with_mcp_tool_call_thread_id_meta(request_meta, &sess.thread_id.to_string());
|
||||
let request_meta = augment_mcp_tool_request_meta_with_sandbox_state(
|
||||
sess,
|
||||
turn_context,
|
||||
step_context,
|
||||
manager,
|
||||
&invocation.server,
|
||||
request_meta,
|
||||
)
|
||||
@@ -568,7 +576,7 @@ async fn execute_mcp_tool_call(
|
||||
.rollout_thread_trace
|
||||
.start_mcp_call_trace(call_id);
|
||||
let request_meta = mcp_call_trace.add_request_meta(request_meta);
|
||||
let result = sess
|
||||
let result = manager
|
||||
.call_tool(
|
||||
&invocation.server,
|
||||
&invocation.tool,
|
||||
@@ -587,6 +595,7 @@ async fn execute_mcp_tool_call(
|
||||
Ok(maybe_request_codex_apps_auth_elicitation(
|
||||
sess,
|
||||
turn_context,
|
||||
manager,
|
||||
call_id,
|
||||
&invocation.server,
|
||||
metadata,
|
||||
@@ -598,17 +607,13 @@ async fn execute_mcp_tool_call(
|
||||
async fn maybe_request_codex_apps_auth_elicitation(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
manager: &McpConnectionManager,
|
||||
call_id: &str,
|
||||
server: &str,
|
||||
metadata: Option<&McpToolApprovalMetadata>,
|
||||
result: CallToolResult,
|
||||
) -> CallToolResult {
|
||||
if !sess
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.is_host_owned_codex_apps_server(server)
|
||||
{
|
||||
if !manager.is_host_owned_codex_apps_server(server) {
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -666,15 +671,16 @@ async fn maybe_request_codex_apps_auth_elicitation(
|
||||
return result;
|
||||
}
|
||||
|
||||
refresh_codex_apps_after_connector_auth(sess, turn_context).await;
|
||||
refresh_codex_apps_after_connector_auth(sess, turn_context, manager).await;
|
||||
auth_elicitation_completed_result(&plan.auth_failure, result.meta)
|
||||
}
|
||||
|
||||
async fn refresh_codex_apps_after_connector_auth(sess: &Session, turn_context: &TurnContext) {
|
||||
let mcp_tools_result = {
|
||||
let manager = sess.services.mcp_connection_manager.load_full();
|
||||
manager.hard_refresh_codex_apps_tools_cache().await
|
||||
};
|
||||
async fn refresh_codex_apps_after_connector_auth(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
manager: &McpConnectionManager,
|
||||
) {
|
||||
let mcp_tools_result = manager.hard_refresh_codex_apps_tools_cache().await;
|
||||
|
||||
match mcp_tools_result {
|
||||
Ok(mcp_tools) => {
|
||||
@@ -692,13 +698,13 @@ async fn refresh_codex_apps_after_connector_auth(sess: &Session, turn_context: &
|
||||
}
|
||||
|
||||
async fn augment_mcp_tool_request_meta_with_sandbox_state(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
step_context: &StepContext,
|
||||
manager: &McpConnectionManager,
|
||||
server: &str,
|
||||
mut meta: Option<serde_json::Value>,
|
||||
) -> anyhow::Result<Option<serde_json::Value>> {
|
||||
let mcp_connection_manager = sess.services.mcp_connection_manager.load_full();
|
||||
let supports_sandbox_state_meta = mcp_connection_manager
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let supports_sandbox_state_meta = manager
|
||||
.server_supports_sandbox_state_meta_capability(server)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
@@ -706,18 +712,18 @@ async fn augment_mcp_tool_request_meta_with_sandbox_state(
|
||||
return Ok(meta);
|
||||
}
|
||||
|
||||
let server_environment_id = mcp_connection_manager
|
||||
let server_environment_id = manager
|
||||
.server_environment_id(server)
|
||||
.unwrap_or(codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID);
|
||||
let Some(sandbox_cwd) = sandbox_cwd_for_mcp_server(turn_context, server_environment_id) else {
|
||||
let Some(sandbox_cwd) = sandbox_cwd_for_mcp_server(step_context, server_environment_id) else {
|
||||
return Ok(meta);
|
||||
};
|
||||
let permission_profile = turn_context.permission_profile();
|
||||
let sandbox_state = serde_json::to_value(SandboxState {
|
||||
permission_profile,
|
||||
codex_linux_sandbox_exe: turn_context.config.codex_linux_sandbox_exe.clone(),
|
||||
codex_linux_sandbox_exe: step_context.mcp.config().codex_linux_sandbox_exe.clone(),
|
||||
sandbox_cwd,
|
||||
use_legacy_landlock: turn_context.config.features.use_legacy_landlock(),
|
||||
use_legacy_landlock: step_context.mcp.config().use_legacy_landlock,
|
||||
})?;
|
||||
|
||||
match meta.as_mut() {
|
||||
@@ -741,8 +747,8 @@ async fn augment_mcp_tool_request_meta_with_sandbox_state(
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
fn sandbox_cwd_for_mcp_server(turn_context: &TurnContext, environment_id: &str) -> Option<PathUri> {
|
||||
if let Some(environment) = turn_context
|
||||
fn sandbox_cwd_for_mcp_server(step_context: &StepContext, environment_id: &str) -> Option<PathUri> {
|
||||
if let Some(environment) = step_context
|
||||
.environments
|
||||
.turn_environments
|
||||
.iter()
|
||||
@@ -753,7 +759,7 @@ fn sandbox_cwd_for_mcp_server(turn_context: &TurnContext, environment_id: &str)
|
||||
|
||||
if environment_id == codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID {
|
||||
#[allow(deprecated)]
|
||||
return Some(PathUri::from_abs_path(&turn_context.cwd));
|
||||
return Some(PathUri::from_abs_path(&step_context.turn.cwd));
|
||||
}
|
||||
|
||||
None
|
||||
@@ -762,16 +768,13 @@ fn sandbox_cwd_for_mcp_server(turn_context: &TurnContext, environment_id: &str)
|
||||
async fn maybe_mark_thread_memory_mode_polluted(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
manager: &McpConnectionManager,
|
||||
server: &str,
|
||||
) {
|
||||
if !turn_context.config.memories.disable_on_external_context {
|
||||
return;
|
||||
}
|
||||
let pollutes_memory = sess
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.server_pollutes_memory(server);
|
||||
let pollutes_memory = manager.server_pollutes_memory(server);
|
||||
if !pollutes_memory {
|
||||
return;
|
||||
}
|
||||
@@ -937,13 +940,14 @@ struct McpAppUsageMetadata {
|
||||
async fn maybe_track_codex_app_used(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
manager: &McpConnectionManager,
|
||||
server: &str,
|
||||
tool_name: &str,
|
||||
) {
|
||||
if server != CODEX_APPS_MCP_SERVER_NAME {
|
||||
return;
|
||||
}
|
||||
let metadata = lookup_mcp_app_usage_metadata(sess, server, tool_name).await;
|
||||
let metadata = lookup_mcp_app_usage_metadata(manager, server, tool_name).await;
|
||||
let (connector_id, app_name) = metadata
|
||||
.map(|metadata| (metadata.connector_id, metadata.app_name))
|
||||
.unwrap_or((None, None));
|
||||
@@ -983,6 +987,7 @@ enum McpToolApprovalDecision {
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct McpToolApprovalMetadata {
|
||||
annotations: Option<ToolAnnotations>,
|
||||
connector_id: Option<String>,
|
||||
@@ -1176,13 +1181,15 @@ fn mcp_tool_approval_prompt_options(
|
||||
|
||||
async fn maybe_request_mcp_tool_approval(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
step_context: &Arc<StepContext>,
|
||||
call_id: &str,
|
||||
invocation: &McpInvocation,
|
||||
hook_tool_name: &HookToolName,
|
||||
metadata: Option<&McpToolApprovalMetadata>,
|
||||
approval_mode: AppToolApproval,
|
||||
) -> Option<McpToolApprovalDecision> {
|
||||
let turn_context = &step_context.turn;
|
||||
let manager = step_context.mcp.manager();
|
||||
let approvals_reviewer = mcp_approvals_reviewer(turn_context, &invocation.server, metadata);
|
||||
if mcp_permission_prompt_is_auto_approved(
|
||||
turn_context.approval_policy.value(),
|
||||
@@ -1201,12 +1208,7 @@ async fn maybe_request_mcp_tool_approval(
|
||||
}
|
||||
|
||||
let session_approval_key = session_mcp_tool_approval_key(invocation, metadata, approval_mode);
|
||||
let persistent_approval_key = if sess
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load()
|
||||
.is_selected_plugin_mcp_server(&invocation.server)
|
||||
{
|
||||
let persistent_approval_key = if manager.is_selected_plugin_mcp_server(&invocation.server) {
|
||||
None
|
||||
} else {
|
||||
persistent_mcp_tool_approval_key(invocation, metadata, approval_mode)
|
||||
@@ -1452,10 +1454,10 @@ async fn mcp_tool_approval_decision_from_guardian(
|
||||
pub(crate) async fn lookup_mcp_tool_metadata(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
manager: &McpConnectionManager,
|
||||
server: &str,
|
||||
tool_name: &str,
|
||||
) -> Option<McpToolApprovalMetadata> {
|
||||
let manager = sess.services.mcp_connection_manager.load_full();
|
||||
let plugin_id = manager
|
||||
.plugin_id_for_mcp_server_name(server)
|
||||
.map(str::to_string);
|
||||
@@ -1471,9 +1473,15 @@ pub(crate) async fn lookup_mcp_tool_metadata(
|
||||
{
|
||||
Some(connectors) => Some(connectors),
|
||||
None => {
|
||||
connectors::list_accessible_connectors_from_mcp_tools(turn_context.config.as_ref())
|
||||
.await
|
||||
.ok()
|
||||
connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
turn_context.config.as_ref(),
|
||||
/*force_refetch*/ false,
|
||||
sess.services.turn_environments.environment_manager(),
|
||||
Arc::clone(&sess.services.mcp_manager),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.map(|status| status.connectors)
|
||||
}
|
||||
};
|
||||
connectors.and_then(|connectors| {
|
||||
@@ -1562,16 +1570,11 @@ fn get_mcp_app_resource_uri(
|
||||
}
|
||||
|
||||
async fn lookup_mcp_app_usage_metadata(
|
||||
sess: &Session,
|
||||
manager: &McpConnectionManager,
|
||||
server: &str,
|
||||
tool_name: &str,
|
||||
) -> Option<McpAppUsageMetadata> {
|
||||
let tools = sess
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.list_all_tools()
|
||||
.await;
|
||||
let tools = manager.list_all_tools().await;
|
||||
|
||||
tools.into_iter().find_map(|tool_info| {
|
||||
if tool_info.server_name == server && tool_info.tool.name == tool_name {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::*;
|
||||
use crate::config::ConfigBuilder;
|
||||
use crate::config::ManagedFeatures;
|
||||
use crate::session::step_context::StepContext;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
use crate::session::tests::make_session_and_context_with_rx;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
@@ -157,10 +158,12 @@ async fn execute_mcp_tool_call_records_replayable_correlation() -> anyhow::Resul
|
||||
})
|
||||
});
|
||||
assert!(dispatch_trace.is_enabled());
|
||||
let turn_context = Arc::new(turn_context);
|
||||
let step_context = StepContext::for_test(Arc::clone(&turn_context));
|
||||
|
||||
let result = execute_mcp_tool_call(
|
||||
&session,
|
||||
&turn_context,
|
||||
step_context.as_ref(),
|
||||
"mcp-call",
|
||||
&McpInvocation {
|
||||
server: "docs".to_string(),
|
||||
@@ -1147,7 +1150,8 @@ async fn mcp_sandbox_cwd_uses_matching_server_environment_uri() -> anyhow::Resul
|
||||
/*shell*/ None,
|
||||
));
|
||||
|
||||
let sandbox_cwd = sandbox_cwd_for_mcp_server(&turn_context, "remote");
|
||||
let step_context = StepContext::for_test(Arc::new(turn_context));
|
||||
let sandbox_cwd = sandbox_cwd_for_mcp_server(&step_context, "remote");
|
||||
|
||||
assert_eq!(sandbox_cwd, Some(secondary_cwd));
|
||||
Ok(())
|
||||
@@ -1157,7 +1161,8 @@ async fn mcp_sandbox_cwd_uses_matching_server_environment_uri() -> anyhow::Resul
|
||||
async fn mcp_sandbox_cwd_is_none_for_unselected_server_environment() -> anyhow::Result<()> {
|
||||
let (_, turn_context) = make_session_and_context().await;
|
||||
|
||||
let sandbox_cwd = sandbox_cwd_for_mcp_server(&turn_context, "remote");
|
||||
let step_context = StepContext::for_test(Arc::new(turn_context));
|
||||
let sandbox_cwd = sandbox_cwd_for_mcp_server(&step_context, "remote");
|
||||
|
||||
assert_eq!(sandbox_cwd, None);
|
||||
Ok(())
|
||||
@@ -1370,7 +1375,10 @@ fn codex_apps_auth_failure_metadata() -> McpToolApprovalMetadata {
|
||||
)
|
||||
}
|
||||
|
||||
async fn install_host_owned_codex_apps_manager(session: &Session, turn_context: &TurnContext) {
|
||||
async fn host_owned_codex_apps_manager(
|
||||
session: &Session,
|
||||
turn_context: &TurnContext,
|
||||
) -> Arc<codex_mcp::McpConnectionManager> {
|
||||
let auth = session.services.auth_manager.auth().await;
|
||||
let startup_cancellation_token = CancellationToken::new();
|
||||
startup_cancellation_token.cancel();
|
||||
@@ -1400,6 +1408,7 @@ async fn install_host_owned_codex_apps_manager(session: &Session, turn_context:
|
||||
},
|
||||
),
|
||||
turn_context.config.codex_home.to_path_buf(),
|
||||
session.services.mcp_manager.codex_apps_tools_cache(),
|
||||
codex_mcp::codex_apps_tools_cache_key(auth.as_ref()),
|
||||
turn_context.config.prefix_mcp_tool_names(),
|
||||
rmcp::model::ElicitationCapability::default(),
|
||||
@@ -1409,22 +1418,20 @@ async fn install_host_owned_codex_apps_manager(session: &Session, turn_context:
|
||||
/*elicitation_reviewer*/ None,
|
||||
)
|
||||
.await;
|
||||
session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.store(Arc::new(manager));
|
||||
Arc::new(manager)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_feature_disabled_returns_original_result() {
|
||||
let (session, turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
install_host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let manager = host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let result = codex_apps_auth_failure_result();
|
||||
let metadata = codex_apps_auth_failure_metadata();
|
||||
|
||||
let returned = maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
&turn_context,
|
||||
manager.as_ref(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
@@ -1445,10 +1452,12 @@ async fn codex_apps_auth_elicitation_non_host_owned_server_returns_original_resu
|
||||
Arc::make_mut(&mut turn_context.config).features = ManagedFeatures::from(features);
|
||||
let result = codex_apps_auth_failure_result();
|
||||
let metadata = codex_apps_auth_failure_metadata();
|
||||
let manager = session.services.latest_mcp_runtime().manager_arc();
|
||||
|
||||
let returned = maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
turn_context,
|
||||
manager.as_ref(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
@@ -1463,7 +1472,7 @@ async fn codex_apps_auth_elicitation_non_host_owned_server_returns_original_resu
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_disallowed_by_policy_returns_original_result() {
|
||||
let (session, mut turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
install_host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let manager = host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let mut features = Features::with_defaults();
|
||||
features.enable(Feature::AuthElicitation);
|
||||
let turn_context = Arc::get_mut(&mut turn_context).expect("single turn context ref");
|
||||
@@ -1478,6 +1487,7 @@ async fn codex_apps_auth_elicitation_disallowed_by_policy_returns_original_resul
|
||||
let returned = maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
turn_context,
|
||||
manager.as_ref(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
@@ -1492,7 +1502,7 @@ async fn codex_apps_auth_elicitation_disallowed_by_policy_returns_original_resul
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_granular_mcp_disabled_returns_original_result() {
|
||||
let (session, mut turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
install_host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let manager = host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let mut features = Features::with_defaults();
|
||||
features.enable(Feature::AuthElicitation);
|
||||
let turn_context = Arc::get_mut(&mut turn_context).expect("single turn context ref");
|
||||
@@ -1513,6 +1523,7 @@ async fn codex_apps_auth_elicitation_granular_mcp_disabled_returns_original_resu
|
||||
let returned = maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
turn_context,
|
||||
manager.as_ref(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
@@ -1527,7 +1538,7 @@ async fn codex_apps_auth_elicitation_granular_mcp_disabled_returns_original_resu
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_feature_enabled_requests_elicitation() {
|
||||
let (session, mut turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
install_host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
let manager = host_owned_codex_apps_manager(&session, &turn_context).await;
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
let mut features = Features::with_defaults();
|
||||
features.enable(Feature::AuthElicitation);
|
||||
@@ -1541,10 +1552,12 @@ async fn codex_apps_auth_elicitation_feature_enabled_requests_elicitation() {
|
||||
let request_task = tokio::spawn({
|
||||
let session = Arc::clone(&session);
|
||||
let turn_context = Arc::clone(&turn_context);
|
||||
let manager = Arc::clone(&manager);
|
||||
async move {
|
||||
maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
&turn_context,
|
||||
manager.as_ref(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
@@ -2465,7 +2478,7 @@ async fn approve_mode_skips_when_annotations_do_not_require_approval() {
|
||||
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-1",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
@@ -2541,7 +2554,7 @@ async fn guardian_mode_skips_auto_when_annotations_do_not_require_approval() {
|
||||
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-guardian",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
@@ -2600,7 +2613,7 @@ async fn permission_request_hook_allows_mcp_tool_call() {
|
||||
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-mcp-hook",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__memory__create_entities"),
|
||||
@@ -2662,7 +2675,7 @@ async fn permission_request_hook_uses_hook_tool_name_without_metadata() {
|
||||
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-mcp-hook-no-metadata",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__memory__create_entities"),
|
||||
@@ -2744,7 +2757,7 @@ async fn permission_request_hook_runs_after_remembered_mcp_approval() {
|
||||
let turn_context = Arc::new(turn_context);
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-mcp-remembered",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__memory__create_entities"),
|
||||
@@ -2827,7 +2840,7 @@ async fn guardian_mode_mcp_denial_returns_rationale_message() {
|
||||
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-guardian-deny",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
@@ -2887,7 +2900,7 @@ async fn prompt_mode_waits_for_approval_when_annotations_do_not_require_approval
|
||||
tokio::spawn(async move {
|
||||
maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-prompt",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
@@ -2945,7 +2958,7 @@ async fn full_access_mode_skips_mcp_tool_approval_for_all_approval_modes() {
|
||||
] {
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-2",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
@@ -3034,7 +3047,7 @@ async fn approve_mode_skips_guardian_in_every_permission_mode() {
|
||||
let turn_context = Arc::new(turn_context);
|
||||
let decision = maybe_request_mcp_tool_approval(
|
||||
&session,
|
||||
&turn_context,
|
||||
&StepContext::for_test(Arc::clone(&turn_context)),
|
||||
"call-3",
|
||||
&invocation,
|
||||
&HookToolName::new("mcp__test__tool"),
|
||||
|
||||
@@ -59,6 +59,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R
|
||||
model_provider: None,
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
|
||||
@@ -64,7 +64,7 @@ pub async fn build_prompt_input(
|
||||
);
|
||||
let thread = thread_manager.start_thread(config).await?;
|
||||
|
||||
let output = build_prompt_input_from_session(thread.thread.codex.session.as_ref(), input).await;
|
||||
let output = build_prompt_input_from_session(&thread.thread.codex.session, input).await;
|
||||
let shutdown = thread.thread.shutdown_and_wait().await;
|
||||
let _removed = thread_manager.remove_thread(&thread.thread_id).await;
|
||||
|
||||
@@ -73,7 +73,7 @@ pub async fn build_prompt_input(
|
||||
}
|
||||
|
||||
pub(crate) async fn build_prompt_input_from_session(
|
||||
sess: &Session,
|
||||
sess: &Arc<Session>,
|
||||
input: Vec<UserInput>,
|
||||
) -> CodexResult<Vec<ResponseItem>> {
|
||||
let turn_context = sess.new_default_turn().await;
|
||||
|
||||
@@ -361,6 +361,7 @@ mod tests {
|
||||
enabled: Some(true),
|
||||
reminder_interval_seconds: Some(1),
|
||||
clock_source: Some(codex_features::CurrentTimeSource::System),
|
||||
delivery_mode: Some(codex_features::CurrentTimeReminderDeliveryMode::AnyInference),
|
||||
sleep_tool: Some(false),
|
||||
}))
|
||||
);
|
||||
|
||||
@@ -598,8 +598,8 @@ async fn shutdown_session_runtime(sess: &Arc<Session>) {
|
||||
warn!("failed to shutdown code mode session: {err}");
|
||||
}
|
||||
sess.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager_arc()
|
||||
.shutdown()
|
||||
.await;
|
||||
sess.guardian_review_session.shutdown().await;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::*;
|
||||
use codex_exec_server::ResolvedSelectedCapabilityRoot;
|
||||
use codex_mcp::ElicitationReviewRequest;
|
||||
use codex_mcp::ElicitationReviewer;
|
||||
use codex_mcp::ElicitationReviewerHandle;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::mcp_approval_meta::APPROVAL_KIND_KEY as MCP_ELICITATION_APPROVAL_KIND_KEY;
|
||||
use codex_protocol::mcp_approval_meta::APPROVAL_KIND_MCP_TOOL_CALL as MCP_ELICITATION_APPROVAL_KIND_MCP_TOOL_CALL;
|
||||
@@ -75,9 +77,20 @@ impl ElicitationReviewer for GuardianMcpElicitationReviewer {
|
||||
|
||||
impl Session {
|
||||
pub(crate) async fn runtime_mcp_config(&self, config: &Config) -> McpConfig {
|
||||
let environments = self.services.turn_environments.snapshot().await;
|
||||
let selected_capability_roots = self
|
||||
.resolve_selected_capability_roots_for_step(&environments)
|
||||
.await;
|
||||
let available_environment_ids =
|
||||
Self::available_selected_environment_ids(&selected_capability_roots);
|
||||
self.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_thread(config, &self.services.mcp_thread_init)
|
||||
.runtime_config_for_step(
|
||||
config,
|
||||
&self.services.mcp_thread_init,
|
||||
&self.services.thread_extension_data,
|
||||
&available_environment_ids,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -88,6 +101,62 @@ impl Session {
|
||||
codex_mcp::configured_mcp_servers(&self.runtime_mcp_config(config).await)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "MCP runtime comparison and publication must remain serialized"
|
||||
)]
|
||||
pub(crate) async fn mcp_runtime_for_step(
|
||||
self: &Arc<Self>,
|
||||
turn_context: &TurnContext,
|
||||
environments: &TurnEnvironmentSnapshot,
|
||||
selected_capability_roots: &[ResolvedSelectedCapabilityRoot],
|
||||
) -> Arc<McpRuntimeSnapshot> {
|
||||
let available_environment_ids =
|
||||
Self::available_selected_environment_ids(selected_capability_roots);
|
||||
let current = self.services.latest_mcp_runtime();
|
||||
if current.available_environment_ids() == available_environment_ids {
|
||||
return current;
|
||||
}
|
||||
|
||||
let _guard = self.services.mcp_projection_lock.lock().await;
|
||||
let current = self.services.latest_mcp_runtime();
|
||||
if current.available_environment_ids() == available_environment_ids {
|
||||
return current;
|
||||
}
|
||||
let mcp_config = self
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_step(
|
||||
&turn_context.config,
|
||||
&self.services.mcp_thread_init,
|
||||
&self.services.thread_extension_data,
|
||||
&available_environment_ids,
|
||||
)
|
||||
.await;
|
||||
self.refresh_mcp_servers_inner(
|
||||
turn_context,
|
||||
mcp_config,
|
||||
environments,
|
||||
&available_environment_ids,
|
||||
Some(self.mcp_elicitation_reviewer()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_selected_capability_roots_for_step(
|
||||
&self,
|
||||
environments: &TurnEnvironmentSnapshot,
|
||||
) -> Vec<ResolvedSelectedCapabilityRoot> {
|
||||
self.services
|
||||
.turn_environments
|
||||
.environment_manager()
|
||||
.resolve_selected_capability_roots(
|
||||
&self.services.selected_capability_roots,
|
||||
&environments.captured_environments(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_elicitation_reviewer(self: &Arc<Self>) -> ElicitationReviewerHandle {
|
||||
Arc::new(GuardianMcpElicitationReviewer::new(self))
|
||||
}
|
||||
@@ -105,8 +174,8 @@ impl Session {
|
||||
) -> McpServerElicitationOutcome {
|
||||
if self
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager()
|
||||
.elicitations_auto_deny()
|
||||
{
|
||||
return McpServerElicitationOutcome {
|
||||
@@ -201,88 +270,28 @@ impl Session {
|
||||
}
|
||||
|
||||
self.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager_arc()
|
||||
.resolve_elicitation(server_name, id, response)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_resources(
|
||||
&self,
|
||||
server: &str,
|
||||
params: Option<PaginatedRequestParams>,
|
||||
) -> anyhow::Result<ListResourcesResult> {
|
||||
self.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.list_resources(server, params)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_resource_templates(
|
||||
&self,
|
||||
server: &str,
|
||||
params: Option<PaginatedRequestParams>,
|
||||
) -> anyhow::Result<ListResourceTemplatesResult> {
|
||||
self.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.list_resource_templates(server, params)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn read_resource(
|
||||
&self,
|
||||
server: &str,
|
||||
params: ReadResourceRequestParams,
|
||||
) -> anyhow::Result<ReadResourceResult> {
|
||||
self.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.read_resource(server, params)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn call_tool(
|
||||
&self,
|
||||
server: &str,
|
||||
tool: &str,
|
||||
arguments: Option<serde_json::Value>,
|
||||
meta: Option<serde_json::Value>,
|
||||
) -> anyhow::Result<CallToolResult> {
|
||||
self.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.call_tool(server, tool, arguments, meta)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn refresh_mcp_servers_inner(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
mcp_servers: HashMap<String, McpServerConfig>,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
mcp_config: McpConfig,
|
||||
environments: &TurnEnvironmentSnapshot,
|
||||
available_environment_ids: &[String],
|
||||
elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
) {
|
||||
) -> Arc<McpRuntimeSnapshot> {
|
||||
let auth = self.services.auth_manager.auth().await;
|
||||
let config = self.get_config().await;
|
||||
let mcp_config = self.runtime_mcp_config(config.as_ref()).await;
|
||||
let mcp_config = Arc::new(mcp_config);
|
||||
let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config);
|
||||
let mcp_servers =
|
||||
effective_mcp_servers_from_configured(mcp_servers, &mcp_config, auth.as_ref());
|
||||
let auth_statuses = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
auth.as_ref(),
|
||||
)
|
||||
.await;
|
||||
let mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
let environment_manager = self.services.turn_environments.environment_manager();
|
||||
// TODO(anp): Migrate MCP runtime cwd plumbing to PathUri so foreign environment cwd
|
||||
// values can be used without falling back to the legacy host cwd.
|
||||
let cwd = turn_context
|
||||
.environments
|
||||
let cwd = environments
|
||||
.primary()
|
||||
.and_then(|turn_environment| turn_environment.cwd().to_abs_path().ok())
|
||||
.map(|cwd| cwd.to_path_buf())
|
||||
@@ -291,28 +300,38 @@ impl Session {
|
||||
turn_context.cwd.to_path_buf()
|
||||
});
|
||||
let mcp_runtime_context = McpRuntimeContext::new(environment_manager, cwd);
|
||||
let auth_statuses = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
mcp_config.mcp_oauth_credentials_store_mode,
|
||||
mcp_config.auth_keyring_backend_kind,
|
||||
auth.as_ref(),
|
||||
&mcp_runtime_context,
|
||||
)
|
||||
.await;
|
||||
let mcp_startup_cancellation_token = {
|
||||
let mut guard = self.services.mcp_startup_cancellation_token.lock().await;
|
||||
guard.cancel();
|
||||
// The previous runtime owns the old token and may still be serving an in-flight step.
|
||||
// Its manager cancels that token when the last runtime handle is dropped.
|
||||
let cancellation_token = CancellationToken::new();
|
||||
*guard = cancellation_token.clone();
|
||||
cancellation_token
|
||||
};
|
||||
let refreshed_manager = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
mcp_config.mcp_oauth_credentials_store_mode,
|
||||
mcp_config.auth_keyring_backend_kind,
|
||||
auth_statuses,
|
||||
&turn_context.approval_policy,
|
||||
turn_context.sub_id.clone(),
|
||||
self.get_tx_event(),
|
||||
mcp_startup_cancellation_token,
|
||||
turn_context.permission_profile(),
|
||||
mcp_runtime_context,
|
||||
config.codex_home.to_path_buf(),
|
||||
mcp_runtime_context.clone(),
|
||||
mcp_config.codex_home.clone(),
|
||||
self.services.mcp_manager.codex_apps_tools_cache(),
|
||||
codex_apps_tools_cache_key(auth.as_ref()),
|
||||
mcp_config.prefix_mcp_tool_names,
|
||||
mcp_config.client_elicitation_capability,
|
||||
mcp_config.client_elicitation_capability.clone(),
|
||||
self.services
|
||||
.supports_openai_form_elicitation
|
||||
.load(std::sync::atomic::Ordering::Relaxed),
|
||||
@@ -322,16 +341,22 @@ impl Session {
|
||||
)
|
||||
.await;
|
||||
{
|
||||
let current_manager = self.services.mcp_connection_manager.load_full();
|
||||
refreshed_manager.set_elicitations_auto_deny(current_manager.elicitations_auto_deny());
|
||||
let current_manager = self.services.latest_mcp_runtime();
|
||||
refreshed_manager
|
||||
.set_elicitations_auto_deny(current_manager.manager().elicitations_auto_deny());
|
||||
}
|
||||
let superseded_manager = self
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.swap(Arc::new(refreshed_manager));
|
||||
superseded_manager.shutdown().await;
|
||||
self.services.publish_mcp_runtime(
|
||||
mcp_config,
|
||||
mcp_runtime_context,
|
||||
available_environment_ids.to_vec(),
|
||||
refreshed_manager,
|
||||
)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "MCP runtime refresh and publication must remain serialized"
|
||||
)]
|
||||
pub(crate) async fn refresh_mcp_servers_if_requested(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
@@ -374,11 +399,44 @@ impl Session {
|
||||
}
|
||||
};
|
||||
|
||||
let mut refresh_config = self.get_config().await.as_ref().clone();
|
||||
refresh_config.mcp_oauth_credentials_store_mode = store_mode;
|
||||
let secret_auth_storage_enabled = match keyring_backend_kind {
|
||||
AuthKeyringBackendKind::Direct => false,
|
||||
AuthKeyringBackendKind::Secrets => true,
|
||||
};
|
||||
if let Err(err) = refresh_config
|
||||
.features
|
||||
.set_enabled(Feature::SecretAuthStorage, secret_auth_storage_enabled)
|
||||
{
|
||||
warn!("failed to apply MCP auth keyring backend refresh config: {err}");
|
||||
return;
|
||||
}
|
||||
|
||||
let _guard = self.services.mcp_projection_lock.lock().await;
|
||||
let available_environment_ids = self
|
||||
.services
|
||||
.latest_mcp_runtime()
|
||||
.available_environment_ids()
|
||||
.to_vec();
|
||||
let mut mcp_config = self
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_step(
|
||||
&refresh_config,
|
||||
&self.services.mcp_thread_init,
|
||||
&self.services.thread_extension_data,
|
||||
&available_environment_ids,
|
||||
)
|
||||
.await;
|
||||
mcp_config.mcp_server_catalog = mcp_config
|
||||
.mcp_server_catalog
|
||||
.with_materialized_servers(mcp_servers);
|
||||
self.refresh_mcp_servers_inner(
|
||||
turn_context,
|
||||
mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
mcp_config,
|
||||
&turn_context.environments,
|
||||
&available_environment_ids,
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
@@ -412,24 +470,56 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "MCP runtime refresh and publication must remain serialized"
|
||||
)]
|
||||
pub(crate) async fn refresh_mcp_servers_now(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
mcp_servers: HashMap<String, McpServerConfig>,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
refresh_config: &Config,
|
||||
elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
) {
|
||||
let _guard = self.services.mcp_projection_lock.lock().await;
|
||||
let available_environment_ids = self
|
||||
.services
|
||||
.latest_mcp_runtime()
|
||||
.available_environment_ids()
|
||||
.to_vec();
|
||||
let mcp_config = self
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_step(
|
||||
refresh_config,
|
||||
&self.services.mcp_thread_init,
|
||||
&self.services.thread_extension_data,
|
||||
&available_environment_ids,
|
||||
)
|
||||
.await;
|
||||
self.refresh_mcp_servers_inner(
|
||||
turn_context,
|
||||
mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
mcp_config,
|
||||
&turn_context.environments,
|
||||
&available_environment_ids,
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn available_selected_environment_ids(
|
||||
selected_capability_roots: &[ResolvedSelectedCapabilityRoot],
|
||||
) -> Vec<String> {
|
||||
let mut available = Vec::new();
|
||||
for root in selected_capability_roots {
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&root.selected_root().location;
|
||||
if !available.contains(environment_id) {
|
||||
available.push(environment_id.clone());
|
||||
}
|
||||
}
|
||||
available
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn mcp_startup_cancellation_token(&self) -> CancellationToken {
|
||||
self.services
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_mcp::McpConfig;
|
||||
use codex_mcp::McpConnectionManager;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
|
||||
/// MCP config, exact environment bindings, and manager used by one model request.
|
||||
pub struct McpRuntimeSnapshot {
|
||||
config: Arc<McpConfig>,
|
||||
manager: Arc<McpConnectionManager>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
available_environment_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl McpRuntimeSnapshot {
|
||||
pub(crate) fn new(
|
||||
config: Arc<McpConfig>,
|
||||
manager: Arc<McpConnectionManager>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
available_environment_ids: Vec<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
manager,
|
||||
runtime_context,
|
||||
available_environment_ids,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(&self) -> &McpConfig {
|
||||
self.config.as_ref()
|
||||
}
|
||||
|
||||
pub fn manager(&self) -> &McpConnectionManager {
|
||||
self.manager.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn manager_arc(&self) -> Arc<McpConnectionManager> {
|
||||
Arc::clone(&self.manager)
|
||||
}
|
||||
|
||||
pub fn runtime_context(&self) -> &McpRuntimeContext {
|
||||
&self.runtime_context
|
||||
}
|
||||
|
||||
pub(crate) fn available_environment_ids(&self) -> &[String] {
|
||||
&self.available_environment_ids
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_uninitialized_for_test(config: &crate::config::Config) -> Arc<Self> {
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_features::Feature;
|
||||
use codex_mcp::ResolvedMcpCatalog;
|
||||
use rmcp::model::ElicitationCapability;
|
||||
|
||||
let mcp_config = McpConfig {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
apps_mcp_product_sku: config.apps_mcp_product_sku.clone(),
|
||||
codex_home: config.codex_home.to_path_buf(),
|
||||
mcp_oauth_credentials_store_mode: config.mcp_oauth_credentials_store_mode,
|
||||
auth_keyring_backend_kind: config.auth_keyring_backend_kind(),
|
||||
mcp_oauth_callback_port: config.mcp_oauth_callback_port,
|
||||
mcp_oauth_callback_url: config.mcp_oauth_callback_url.clone(),
|
||||
skill_mcp_dependency_install_enabled: config
|
||||
.features
|
||||
.enabled(Feature::SkillMcpDependencyInstall),
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
codex_linux_sandbox_exe: config.codex_linux_sandbox_exe.clone(),
|
||||
use_legacy_landlock: config.features.use_legacy_landlock(),
|
||||
apps_enabled: config.features.enabled(Feature::Apps),
|
||||
prefix_mcp_tool_names: config.prefix_mcp_tool_names(),
|
||||
client_elicitation_capability: ElicitationCapability::default(),
|
||||
mcp_server_catalog: ResolvedMcpCatalog::default(),
|
||||
connector_snapshot: codex_connectors::ConnectorSnapshot::default(),
|
||||
};
|
||||
let manager = McpConnectionManager::new_uninitialized_with_permission_profile(
|
||||
&config.permissions.approval_policy,
|
||||
config.permissions.permission_profile(),
|
||||
config.prefix_mcp_tool_names(),
|
||||
);
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
config.cwd.to_path_buf(),
|
||||
);
|
||||
Arc::new(Self::new(
|
||||
Arc::new(mcp_config),
|
||||
Arc::new(manager),
|
||||
runtime_context,
|
||||
Vec::new(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for McpRuntimeSnapshot {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("McpRuntimeSnapshot")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,6 @@ use codex_protocol::dynamic_tools::DynamicToolResponse;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
@@ -158,15 +157,7 @@ use codex_utils_path_uri::PathUri;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::Shared;
|
||||
use futures::prelude::*;
|
||||
use rmcp::model::ElicitationCapability;
|
||||
use rmcp::model::FormElicitationCapability;
|
||||
use rmcp::model::ListResourceTemplatesResult;
|
||||
use rmcp::model::ListResourcesResult;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ReadResourceRequestParams;
|
||||
use rmcp::model::ReadResourceResult;
|
||||
use rmcp::model::RequestId;
|
||||
use rmcp::model::UrlElicitationCapability;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::RwLock;
|
||||
@@ -214,6 +205,7 @@ mod handlers;
|
||||
mod inject;
|
||||
mod input_queue;
|
||||
mod mcp;
|
||||
mod mcp_runtime;
|
||||
pub(crate) mod multi_agents;
|
||||
mod review;
|
||||
mod rollout_budget;
|
||||
@@ -235,6 +227,7 @@ use self::handlers::submission_loop;
|
||||
pub(crate) use self::input_queue::InputQueueActivity;
|
||||
pub(crate) use self::input_queue::TurnInput;
|
||||
pub(crate) use self::input_queue::TurnInputQueue;
|
||||
pub use self::mcp_runtime::McpRuntimeSnapshot;
|
||||
use self::review::spawn_review_thread;
|
||||
use self::session::AppServerClientMetadata;
|
||||
use self::session::Session;
|
||||
@@ -340,7 +333,7 @@ use codex_core_plugins::RecommendedPluginCandidatesInput;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
use codex_mcp::McpConfig;
|
||||
use codex_mcp::compute_auth_statuses;
|
||||
use codex_mcp::effective_mcp_servers_from_configured;
|
||||
use codex_mcp::effective_mcp_servers;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::THREAD_STARTED_METRIC;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
@@ -414,6 +407,7 @@ pub struct CodexSpawnOk {
|
||||
|
||||
pub(crate) struct CodexSpawnArgs {
|
||||
pub(crate) config: Config,
|
||||
pub(crate) allow_provider_model_fallback: bool,
|
||||
pub(crate) user_instructions: LoadedUserInstructions,
|
||||
pub(crate) installation_id: String,
|
||||
pub(crate) auth_manager: Arc<AuthManager>,
|
||||
@@ -503,6 +497,7 @@ impl Codex {
|
||||
async fn spawn_internal(args: CodexSpawnArgs) -> CodexResult<CodexSpawnOk> {
|
||||
let CodexSpawnArgs {
|
||||
mut config,
|
||||
allow_provider_model_fallback,
|
||||
user_instructions,
|
||||
installation_id,
|
||||
auth_manager,
|
||||
@@ -576,8 +571,23 @@ impl Codex {
|
||||
let _ = models_manager.list_models(refresh_strategy).await;
|
||||
}
|
||||
let model = models_manager
|
||||
.get_default_model(&config.model, refresh_strategy)
|
||||
.get_default_model(
|
||||
&config.model,
|
||||
allow_provider_model_fallback,
|
||||
refresh_strategy,
|
||||
)
|
||||
.await;
|
||||
if allow_provider_model_fallback
|
||||
&& let Some(requested_model) = config.model.as_ref()
|
||||
&& model != *requested_model
|
||||
{
|
||||
info!(
|
||||
model_provider = %config.model_provider_id,
|
||||
requested_model,
|
||||
fallback_model = %model,
|
||||
"replaced unavailable requested model with provider default"
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve base instructions for the session. Priority order:
|
||||
// 1. config.base_instructions override
|
||||
@@ -823,8 +833,11 @@ impl Codex {
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let mcp_connection_manager = self.session.services.mcp_connection_manager.load_full();
|
||||
mcp_connection_manager.set_elicitations_auto_deny(mcp_elicitations_auto_deny);
|
||||
self.session
|
||||
.services
|
||||
.latest_mcp_runtime()
|
||||
.manager()
|
||||
.set_elicitations_auto_deny(mcp_elicitations_auto_deny);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2758,6 +2771,7 @@ impl Session {
|
||||
let items = items.as_ref();
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
state.current_time_reminder.note_recorded_items(items);
|
||||
state.record_items(
|
||||
items.iter(),
|
||||
turn_context.model_info.truncation_policy.into(),
|
||||
@@ -2808,7 +2822,7 @@ impl Session {
|
||||
/// `run_turn` and pass the result down; standalone request or history boundaries may capture
|
||||
/// their own step.
|
||||
pub(crate) async fn capture_step_context(
|
||||
&self,
|
||||
self: &Arc<Self>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
) -> Arc<StepContext> {
|
||||
let deferred_executor_enabled = turn_context
|
||||
@@ -2828,9 +2842,21 @@ impl Session {
|
||||
.await;
|
||||
}
|
||||
let loaded_agents_md = self.services.agents_md_manager.get_loaded().await;
|
||||
let selected_capability_roots = self
|
||||
.resolve_selected_capability_roots_for_step(&environments)
|
||||
.await;
|
||||
let mcp = self
|
||||
.mcp_runtime_for_step(
|
||||
turn_context.as_ref(),
|
||||
&environments,
|
||||
&selected_capability_roots,
|
||||
)
|
||||
.await;
|
||||
Arc::new(StepContext::new(
|
||||
turn_context,
|
||||
environments,
|
||||
selected_capability_roots,
|
||||
mcp,
|
||||
loaded_agents_md,
|
||||
))
|
||||
}
|
||||
@@ -2850,6 +2876,7 @@ impl Session {
|
||||
let response_item = items[0].clone();
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
state.current_time_reminder.note_recorded_items(items);
|
||||
state.record_items(
|
||||
items.iter(),
|
||||
turn_context.model_info.truncation_policy.into(),
|
||||
@@ -3096,6 +3123,17 @@ impl Session {
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
world_state: &WorldState,
|
||||
) -> Vec<ResponseItem> {
|
||||
let mcp = self.services.latest_mcp_runtime();
|
||||
self.build_initial_context_with_world_state_and_mcp(turn_context, world_state, &mcp)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn build_initial_context_with_world_state_and_mcp(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
world_state: &WorldState,
|
||||
mcp: &McpRuntimeSnapshot,
|
||||
) -> Vec<ResponseItem> {
|
||||
let mut developer_sections = Vec::<String>::with_capacity(8);
|
||||
let mut contextual_user_sections = Vec::<String>::with_capacity(2);
|
||||
@@ -3189,10 +3227,9 @@ impl Session {
|
||||
}
|
||||
}
|
||||
if turn_context.config.include_apps_instructions && turn_context.apps_enabled() {
|
||||
let mcp_connection_manager = self.services.mcp_connection_manager.load_full();
|
||||
let accessible_and_enabled_connectors =
|
||||
connectors::list_accessible_and_enabled_connectors_from_manager(
|
||||
&mcp_connection_manager,
|
||||
mcp.manager(),
|
||||
&turn_context.config,
|
||||
)
|
||||
.await;
|
||||
@@ -3299,7 +3336,8 @@ impl Session {
|
||||
if turn_context.config.features.enabled(Feature::TokenBudget)
|
||||
&& turn_context.model_context_window().is_some()
|
||||
{
|
||||
let mcp_result = self
|
||||
let mcp_result = mcp
|
||||
.manager()
|
||||
.call_tool(
|
||||
"notes",
|
||||
"thread_hint",
|
||||
@@ -3514,7 +3552,11 @@ impl Session {
|
||||
// Full initial context resets the baseline; later turns persist only its changes.
|
||||
let (mut context_items, world_state_item) = if should_inject_full_context {
|
||||
let context_items = self
|
||||
.build_initial_context_with_world_state(turn_context, world_state.as_ref())
|
||||
.build_initial_context_with_world_state_and_mcp(
|
||||
turn_context,
|
||||
world_state.as_ref(),
|
||||
step_context.mcp.as_ref(),
|
||||
)
|
||||
.await;
|
||||
let snapshot = world_state.snapshot();
|
||||
self.state
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::state::ActiveTurn;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_login::auth::AgentIdentityAuthPolicy;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
|
||||
use codex_protocol::config_types::ServiceTier;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
@@ -489,7 +490,7 @@ impl Session {
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
|
||||
thread_extension_init: ExtensionDataInit,
|
||||
mut thread_extension_init: ExtensionDataInit,
|
||||
supports_openai_form_elicitation: bool,
|
||||
agent_control: AgentControl,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
@@ -555,6 +556,17 @@ impl Session {
|
||||
config.current_time_reminder.as_ref(),
|
||||
external_time_provider,
|
||||
)?;
|
||||
let selected_capability_roots =
|
||||
match thread_extension_init.get::<Vec<SelectedCapabilityRoot>>() {
|
||||
Some(roots) => roots.as_ref().clone(),
|
||||
None => {
|
||||
let roots = initial_history.get_selected_capability_roots();
|
||||
if !roots.is_empty() {
|
||||
thread_extension_init.insert(roots.clone());
|
||||
}
|
||||
roots
|
||||
}
|
||||
};
|
||||
let mcp_thread_init = thread_extension_init.clone();
|
||||
let thread_extension_data = codex_extension_api::ExtensionData::new_with_init(
|
||||
thread_id.to_string(),
|
||||
@@ -584,6 +596,7 @@ impl Session {
|
||||
text: session_configuration.base_instructions.clone(),
|
||||
},
|
||||
dynamic_tools: session_configuration.dynamic_tools.clone(),
|
||||
selected_capability_roots: selected_capability_roots.clone(),
|
||||
multi_agent_version: initial_multi_agent_version,
|
||||
initial_window_id: initial_auto_compact_window_ids
|
||||
.window_id
|
||||
@@ -648,10 +661,25 @@ impl Session {
|
||||
let config_for_mcp = Arc::clone(&config);
|
||||
let mcp_manager_for_mcp = Arc::clone(&mcp_manager);
|
||||
let mcp_thread_init_for_startup = &mcp_thread_init;
|
||||
let thread_extension_data_for_mcp = &thread_extension_data;
|
||||
let mcp_runtime_cwd = session_configuration
|
||||
.environment_selections()
|
||||
.first()
|
||||
.and_then(|environment| environment.cwd.to_abs_path().ok())
|
||||
.map(|cwd| cwd.to_path_buf())
|
||||
.unwrap_or_else(|| session_configuration.cwd().to_path_buf());
|
||||
let mcp_runtime_context =
|
||||
McpRuntimeContext::new(Arc::clone(&environment_manager), mcp_runtime_cwd);
|
||||
let mcp_runtime_context_for_auth = mcp_runtime_context.clone();
|
||||
let auth_and_mcp_fut = async move {
|
||||
let auth = auth_manager_clone.auth().await;
|
||||
let mcp_config = mcp_manager_for_mcp
|
||||
.runtime_config_for_thread(&config_for_mcp, mcp_thread_init_for_startup)
|
||||
.runtime_config_for_step(
|
||||
&config_for_mcp,
|
||||
mcp_thread_init_for_startup,
|
||||
thread_extension_data_for_mcp,
|
||||
/*available_environment_ids*/ &[],
|
||||
)
|
||||
.await;
|
||||
let mcp_servers = codex_mcp::effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config);
|
||||
@@ -660,9 +688,16 @@ impl Session {
|
||||
config_for_mcp.mcp_oauth_credentials_store_mode,
|
||||
config_for_mcp.auth_keyring_backend_kind(),
|
||||
auth.as_ref(),
|
||||
&mcp_runtime_context_for_auth,
|
||||
)
|
||||
.await;
|
||||
(auth, mcp_servers, auth_statuses, tool_plugin_provenance)
|
||||
(
|
||||
auth,
|
||||
mcp_config,
|
||||
mcp_servers,
|
||||
auth_statuses,
|
||||
tool_plugin_provenance,
|
||||
)
|
||||
}
|
||||
.instrument(info_span!(
|
||||
"session_init.auth_mcp",
|
||||
@@ -673,7 +708,7 @@ impl Session {
|
||||
let (
|
||||
thread_persistence_result,
|
||||
state_db_ctx,
|
||||
(auth, mcp_servers, auth_statuses, tool_plugin_provenance),
|
||||
(auth, mcp_config, mcp_servers, auth_statuses, tool_plugin_provenance),
|
||||
) = tokio::join!(thread_persistence_fut, state_db_fut, auth_and_mcp_fut);
|
||||
|
||||
let mut live_thread_init =
|
||||
@@ -1009,6 +1044,8 @@ impl Session {
|
||||
// changing this to use Option or OnceCell, though the current
|
||||
// setup is straightforward enough and performs well.
|
||||
mcp_connection_manager,
|
||||
mcp_runtime: arc_swap::ArcSwapOption::empty(),
|
||||
mcp_projection_lock: Mutex::new(()),
|
||||
mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()),
|
||||
unified_exec_manager: UnifiedExecProcessManager::new(
|
||||
config.background_terminal_max_timeout,
|
||||
@@ -1036,6 +1073,7 @@ impl Session {
|
||||
// TODO(jif): extract session to share between sub-agents
|
||||
session_extension_data,
|
||||
thread_extension_data,
|
||||
selected_capability_roots,
|
||||
mcp_thread_init,
|
||||
supports_openai_form_elicitation: std::sync::atomic::AtomicBool::new(
|
||||
supports_openai_form_elicitation,
|
||||
@@ -1140,14 +1178,6 @@ impl Session {
|
||||
sess.send_event_raw(event).await;
|
||||
}
|
||||
|
||||
let client_elicitation_capability = if config.features.enabled(Feature::AuthElicitation) {
|
||||
ElicitationCapability {
|
||||
form: Some(FormElicitationCapability::default()),
|
||||
url: Some(UrlElicitationCapability::default()),
|
||||
}
|
||||
} else {
|
||||
ElicitationCapability::default()
|
||||
};
|
||||
let mcp_startup_cancellation_token = {
|
||||
let mut cancel_guard = sess.services.mcp_startup_cancellation_token.lock().await;
|
||||
cancel_guard.cancel();
|
||||
@@ -1155,20 +1185,6 @@ impl Session {
|
||||
*cancel_guard = cancel_token.clone();
|
||||
cancel_token
|
||||
};
|
||||
let mcp_runtime_context = {
|
||||
let turn_environments = sess.services.turn_environments.snapshot().await;
|
||||
// TODO(anp): Migrate MCP runtime cwd plumbing to PathUri so foreign environment
|
||||
// cwd values can be used without falling back to the session host cwd.
|
||||
let cwd = turn_environments
|
||||
.primary()
|
||||
.and_then(|turn_environment| turn_environment.cwd().to_abs_path().ok())
|
||||
.map(|cwd| cwd.to_path_buf())
|
||||
.unwrap_or_else(|| session_configuration.cwd().to_path_buf());
|
||||
McpRuntimeContext::new(
|
||||
sess.services.turn_environments.environment_manager(),
|
||||
cwd,
|
||||
)
|
||||
};
|
||||
let mcp_connection_manager = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
@@ -1179,11 +1195,12 @@ impl Session {
|
||||
tx_event.clone(),
|
||||
mcp_startup_cancellation_token,
|
||||
session_configuration.permission_profile(),
|
||||
mcp_runtime_context,
|
||||
mcp_runtime_context.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
sess.services.mcp_manager.codex_apps_tools_cache(),
|
||||
codex_apps_tools_cache_key(auth),
|
||||
config.prefix_mcp_tool_names(),
|
||||
client_elicitation_capability,
|
||||
mcp_config.client_elicitation_capability.clone(),
|
||||
sess.services
|
||||
.supports_openai_form_elicitation
|
||||
.load(std::sync::atomic::Ordering::Relaxed),
|
||||
@@ -1197,7 +1214,12 @@ impl Session {
|
||||
))
|
||||
.await;
|
||||
sess.services
|
||||
.install_mcp_connection_manager(mcp_connection_manager)
|
||||
.install_mcp_connection_manager(
|
||||
Arc::new(mcp_config),
|
||||
mcp_runtime_context,
|
||||
/*available_environment_ids*/ Vec::new(),
|
||||
mcp_connection_manager,
|
||||
)
|
||||
.await?;
|
||||
sess.schedule_startup_prewarm(session_configuration.base_instructions.clone())
|
||||
.await;
|
||||
|
||||
@@ -2,13 +2,19 @@ use std::sync::Arc;
|
||||
|
||||
use crate::agents_md::LoadedAgentsMd;
|
||||
use crate::environment_selection::TurnEnvironmentSnapshot;
|
||||
use crate::session::McpRuntimeSnapshot;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use codex_exec_server::ResolvedSelectedCapabilityRoot;
|
||||
|
||||
/// Request-scoped state that may change between model sampling requests.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct StepContext {
|
||||
pub(crate) turn: Arc<TurnContext>,
|
||||
pub(crate) environments: TurnEnvironmentSnapshot,
|
||||
/// Capability roots bound to ready environments in this exact step.
|
||||
pub(crate) selected_capability_roots: Vec<ResolvedSelectedCapabilityRoot>,
|
||||
/// The exact MCP config and manager used to advertise and execute tools for this step.
|
||||
pub(crate) mcp: Arc<McpRuntimeSnapshot>,
|
||||
/// The canonical AGENTS.md value observed with this environment snapshot.
|
||||
pub(crate) loaded_agents_md: Option<Arc<LoadedAgentsMd>>,
|
||||
}
|
||||
@@ -17,11 +23,15 @@ impl StepContext {
|
||||
pub(crate) fn new(
|
||||
turn: Arc<TurnContext>,
|
||||
environments: TurnEnvironmentSnapshot,
|
||||
selected_capability_roots: Vec<ResolvedSelectedCapabilityRoot>,
|
||||
mcp: Arc<McpRuntimeSnapshot>,
|
||||
loaded_agents_md: Option<Arc<LoadedAgentsMd>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
turn,
|
||||
environments,
|
||||
selected_capability_roots,
|
||||
mcp,
|
||||
loaded_agents_md,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::test_support::models_manager_with_provider;
|
||||
use crate::tools::format_exec_output_str;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigLayerStackOrdering;
|
||||
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NetworkConstraints;
|
||||
use codex_config::NetworkDomainPermissionToml;
|
||||
@@ -25,6 +26,8 @@ use codex_config::NetworkDomainPermissionsToml;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::Sourced;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_config::types::ToolSuggestDisabledTool;
|
||||
use codex_core_skills::HostSkillsSnapshot;
|
||||
use core_test_support::test_codex::local_selections;
|
||||
@@ -188,8 +191,10 @@ impl StepContext {
|
||||
pub(crate) fn for_test(turn: Arc<TurnContext>) -> Arc<Self> {
|
||||
let environments = turn.environments.clone();
|
||||
Arc::new(Self::new(
|
||||
turn,
|
||||
Arc::clone(&turn),
|
||||
environments,
|
||||
Vec::new(),
|
||||
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(&turn.config),
|
||||
/*loaded_agents_md*/ None,
|
||||
))
|
||||
}
|
||||
@@ -378,8 +383,8 @@ async fn request_mcp_server_elicitation_auto_accepts_when_auto_deny_is_enabled()
|
||||
let (session, turn_context, rx) = make_session_and_context_with_rx().await;
|
||||
session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager()
|
||||
.set_elicitations_auto_deny(/*auto_deny*/ true);
|
||||
|
||||
let response = session
|
||||
@@ -4043,6 +4048,7 @@ async fn attach_thread_persistence(session: &mut Session) -> PathBuf {
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
initial_window_id: Uuid::now_v7().to_string(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
@@ -5361,14 +5367,12 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
/*bundled_skills_enabled*/ true,
|
||||
));
|
||||
let network_approval = Arc::new(NetworkApprovalService::default());
|
||||
let mcp_runtime =
|
||||
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(config.as_ref());
|
||||
let services = SessionServices {
|
||||
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from_pointee(
|
||||
McpConnectionManager::new_uninitialized_with_permission_profile(
|
||||
&config.permissions.approval_policy,
|
||||
config.permissions.permission_profile(),
|
||||
config.prefix_mcp_tool_names(),
|
||||
),
|
||||
)),
|
||||
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from(mcp_runtime.manager_arc())),
|
||||
mcp_runtime: arc_swap::ArcSwapOption::from(Some(mcp_runtime)),
|
||||
mcp_projection_lock: Mutex::new(()),
|
||||
mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()),
|
||||
unified_exec_manager: UnifiedExecProcessManager::new(
|
||||
config.background_terminal_max_timeout,
|
||||
@@ -5404,6 +5408,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
agent_control.session_id().to_string(),
|
||||
),
|
||||
thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()),
|
||||
selected_capability_roots: Vec::new(),
|
||||
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
|
||||
supports_openai_form_elicitation: std::sync::atomic::AtomicBool::new(false),
|
||||
agent_control,
|
||||
@@ -6919,6 +6924,7 @@ async fn shutdown_complete_does_not_append_to_thread_store_after_shutdown() {
|
||||
originator: "test_originator".to_string(),
|
||||
base_instructions: BaseInstructions::default(),
|
||||
dynamic_tools: Vec::new(),
|
||||
selected_capability_roots: Vec::new(),
|
||||
multi_agent_version: None,
|
||||
initial_window_id: Uuid::now_v7().to_string(),
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
@@ -7436,14 +7442,12 @@ where
|
||||
/*bundled_skills_enabled*/ true,
|
||||
));
|
||||
let network_approval = Arc::new(NetworkApprovalService::default());
|
||||
let mcp_runtime =
|
||||
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(config.as_ref());
|
||||
let services = SessionServices {
|
||||
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from_pointee(
|
||||
McpConnectionManager::new_uninitialized_with_permission_profile(
|
||||
&config.permissions.approval_policy,
|
||||
config.permissions.permission_profile(),
|
||||
config.prefix_mcp_tool_names(),
|
||||
),
|
||||
)),
|
||||
mcp_connection_manager: Arc::new(arc_swap::ArcSwap::from(mcp_runtime.manager_arc())),
|
||||
mcp_runtime: arc_swap::ArcSwapOption::from(Some(mcp_runtime)),
|
||||
mcp_projection_lock: Mutex::new(()),
|
||||
mcp_startup_cancellation_token: Mutex::new(CancellationToken::new()),
|
||||
unified_exec_manager: UnifiedExecProcessManager::new(
|
||||
config.background_terminal_max_timeout,
|
||||
@@ -7479,6 +7483,7 @@ where
|
||||
agent_control.session_id().to_string(),
|
||||
),
|
||||
thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()),
|
||||
selected_capability_roots: Vec::new(),
|
||||
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
|
||||
supports_openai_form_elicitation: std::sync::atomic::AtomicBool::new(false),
|
||||
agent_control,
|
||||
@@ -7598,8 +7603,15 @@ pub(crate) async fn make_session_and_context_with_rx() -> (
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_mcp_servers_is_deferred_until_next_turn() {
|
||||
async fn refresh_mcp_servers_keeps_the_previous_runtime_alive() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
let session = Arc::new(session);
|
||||
let turn_context = Arc::new(turn_context);
|
||||
let old_runtime = session.services.latest_mcp_runtime();
|
||||
let step_context = session
|
||||
.capture_step_context(Arc::clone(&turn_context))
|
||||
.await;
|
||||
assert!(Arc::ptr_eq(&step_context.mcp, &old_runtime));
|
||||
let old_token = session.mcp_startup_cancellation_token().await;
|
||||
assert!(!old_token.is_cancelled());
|
||||
|
||||
@@ -7607,8 +7619,16 @@ async fn refresh_mcp_servers_is_deferred_until_next_turn() {
|
||||
serde_json::to_value(OAuthCredentialsStoreMode::Auto).expect("serialize store mode");
|
||||
let auth_keyring_backend_kind =
|
||||
serde_json::to_value(AuthKeyringBackendKind::Secrets).expect("serialize keyring backend");
|
||||
let refreshed_mcp_servers = serde_json::from_value::<HashMap<String, McpServerConfig>>(json!({
|
||||
"refreshed": {
|
||||
"url": "https://refreshed.example/mcp",
|
||||
"enabled": false
|
||||
}
|
||||
}))
|
||||
.expect("parse refreshed MCP servers");
|
||||
let refresh_config = McpServerRefreshConfig {
|
||||
mcp_servers: json!({}),
|
||||
mcp_servers: serde_json::to_value(&refreshed_mcp_servers)
|
||||
.expect("serialize refreshed MCP servers"),
|
||||
mcp_oauth_credentials_store_mode,
|
||||
auth_keyring_backend_kind,
|
||||
};
|
||||
@@ -7630,7 +7650,7 @@ async fn refresh_mcp_servers_is_deferred_until_next_turn() {
|
||||
.refresh_mcp_servers_if_requested(&turn_context, /*elicitation_reviewer*/ None)
|
||||
.await;
|
||||
|
||||
assert!(old_token.is_cancelled());
|
||||
assert!(!old_token.is_cancelled());
|
||||
assert!(
|
||||
session
|
||||
.pending_mcp_server_refresh_config
|
||||
@@ -7640,6 +7660,71 @@ async fn refresh_mcp_servers_is_deferred_until_next_turn() {
|
||||
);
|
||||
let new_token = session.mcp_startup_cancellation_token().await;
|
||||
assert!(!new_token.is_cancelled());
|
||||
let new_runtime = session.services.latest_mcp_runtime();
|
||||
assert!(!Arc::ptr_eq(&old_runtime, &new_runtime));
|
||||
assert!(Arc::ptr_eq(&step_context.mcp, &old_runtime));
|
||||
assert_eq!(
|
||||
codex_mcp::configured_mcp_servers(new_runtime.config()),
|
||||
refreshed_mcp_servers
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn built_tools_uses_the_step_mcp_runtime() -> anyhow::Result<()> {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
let session = Arc::new(session);
|
||||
let turn_context = Arc::new(turn_context);
|
||||
let step_context = session.capture_step_context(turn_context).await;
|
||||
|
||||
let mut refresh_config = step_context.turn.config.as_ref().clone();
|
||||
refresh_config.mcp_servers.set(HashMap::from([(
|
||||
"newer".to_string(),
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: "missing-test-mcp-server".to_string(),
|
||||
args: Vec::new(),
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
},
|
||||
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
supports_parallel_tool_calls: false,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: None,
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
},
|
||||
)]))?;
|
||||
session
|
||||
.refresh_mcp_servers_now(
|
||||
step_context.turn.as_ref(),
|
||||
&refresh_config,
|
||||
/*elicitation_reviewer*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
let router = crate::session::turn::built_tools(
|
||||
session.as_ref(),
|
||||
step_context.as_ref(),
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
!router
|
||||
.registered_tool_names_for_test()
|
||||
.iter()
|
||||
.any(|name| name.to_string() == "list_mcp_resources")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -10156,8 +10241,8 @@ async fn fatal_tool_error_stops_turn_and_reports_error() {
|
||||
let tools = {
|
||||
session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager()
|
||||
.list_all_tools()
|
||||
.await
|
||||
};
|
||||
|
||||
@@ -718,6 +718,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
|
||||
|
||||
let CodexSpawnOk { codex, .. } = Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
allow_provider_model_fallback: false,
|
||||
user_instructions: Default::default(),
|
||||
installation_id: "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
auth_manager,
|
||||
|
||||
@@ -1,26 +1,57 @@
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_features::CurrentTimeReminderDeliveryMode;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
|
||||
use super::session::Session;
|
||||
use super::turn_context::TurnContext;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context_manager::is_user_turn_boundary;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct CurrentTimeReminderState {
|
||||
last_delivery_time: Option<DateTime<Utc>>,
|
||||
last_window_id: Option<String>,
|
||||
pending_user_or_tool_output_boundary: bool,
|
||||
}
|
||||
|
||||
impl CurrentTimeReminderState {
|
||||
pub(super) fn note_recorded_items(&mut self, items: &[ResponseItem]) {
|
||||
if items.iter().any(|item| {
|
||||
is_user_turn_boundary(item)
|
||||
|| matches!(
|
||||
item,
|
||||
ResponseItem::FunctionCallOutput { .. }
|
||||
| ResponseItem::CustomToolCallOutput { .. }
|
||||
| ResponseItem::ToolSearchOutput { .. }
|
||||
)
|
||||
}) {
|
||||
self.pending_user_or_tool_output_boundary = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn take_reminder_due(
|
||||
&mut self,
|
||||
window_id: &str,
|
||||
current_time: DateTime<Utc>,
|
||||
interval_seconds: u64,
|
||||
delivery_mode: CurrentTimeReminderDeliveryMode,
|
||||
) -> bool {
|
||||
let reminder_is_due = self.last_window_id.as_deref() != Some(window_id)
|
||||
let is_new_window = self.last_window_id.as_deref() != Some(window_id);
|
||||
// Consume the boundary for this inference even if the interval suppresses delivery.
|
||||
let follows_user_or_tool_output =
|
||||
std::mem::take(&mut self.pending_user_or_tool_output_boundary);
|
||||
if delivery_mode == CurrentTimeReminderDeliveryMode::AfterUserOrToolOutput
|
||||
&& !is_new_window
|
||||
&& !follows_user_or_tool_output
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let reminder_is_due = is_new_window
|
||||
|| interval_seconds == 0
|
||||
|| self.last_delivery_time.is_none_or(|last_delivery_time| {
|
||||
current_time
|
||||
.signed_duration_since(last_delivery_time)
|
||||
@@ -59,6 +90,7 @@ pub(super) async fn maybe_record_current_time_reminder(
|
||||
window_id,
|
||||
current_time,
|
||||
config.reminder_interval_seconds,
|
||||
config.delivery_mode,
|
||||
)
|
||||
};
|
||||
if !reminder_is_due {
|
||||
|
||||
@@ -170,8 +170,13 @@ pub(crate) async fn run_turn(
|
||||
.record_context_updates_and_set_reference_context_item(first_step_context.as_ref())
|
||||
.await;
|
||||
|
||||
let Some((injection_items, explicitly_enabled_connectors)) =
|
||||
build_skills_and_plugins(&sess, turn_context.as_ref(), &input, &cancellation_token).await
|
||||
let Some((injection_items, explicitly_enabled_connectors)) = build_skills_and_plugins(
|
||||
&sess,
|
||||
first_step_context.as_ref(),
|
||||
&input,
|
||||
&cancellation_token,
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -483,10 +488,11 @@ async fn run_hooks_and_record_inputs(
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
async fn build_skills_and_plugins(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &TurnContext,
|
||||
step_context: &StepContext,
|
||||
input: &[TurnInput],
|
||||
cancellation_token: &CancellationToken,
|
||||
) -> Option<(Vec<ResponseItem>, HashSet<String>)> {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
// Guardian input embeds the parent transcript as untrusted evidence. Do not interpret skill or
|
||||
// plugin mentions from that generated prompt as requests to inject additional instructions.
|
||||
if crate::guardian::is_guardian_reviewer_source(&turn_context.session_source) {
|
||||
@@ -517,17 +523,14 @@ async fn build_skills_and_plugins(
|
||||
// enabled plugins, then converted into turn-scoped guidance below.
|
||||
let mentioned_plugins =
|
||||
collect_explicit_plugin_mentions(&user_input, loaded_plugins.capability_summaries());
|
||||
let connector_snapshot = codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let connector_snapshot = step_context.mcp.config().connector_snapshot.clone();
|
||||
let mcp_tools = if turn_context.apps_enabled() || !mentioned_plugins.is_empty() {
|
||||
// Plugin mentions need raw MCP/app inventory even when app tools
|
||||
// are normally hidden so we can describe the plugin's currently
|
||||
// usable capabilities for this turn.
|
||||
match sess
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
match step_context
|
||||
.mcp
|
||||
.manager_arc()
|
||||
.list_all_tools()
|
||||
.or_cancel(cancellation_token)
|
||||
.await
|
||||
@@ -1156,7 +1159,7 @@ pub(crate) async fn built_tools(
|
||||
cancellation_token: &CancellationToken,
|
||||
) -> CodexResult<Arc<ToolRouter>> {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let mcp_connection_manager = sess.services.mcp_connection_manager.load_full();
|
||||
let mcp_connection_manager = step_context.mcp.manager();
|
||||
let has_mcp_servers = mcp_connection_manager.has_servers();
|
||||
let all_mcp_tools = mcp_connection_manager
|
||||
.list_all_tools()
|
||||
@@ -1168,9 +1171,7 @@ pub(crate) async fn built_tools(
|
||||
.plugins_for_config(&turn_context.config.plugins_config_input())
|
||||
.instrument(trace_span!("built_tools.load_plugins"))
|
||||
.await;
|
||||
let connector_snapshot = codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let connector_snapshot = step_context.mcp.config().connector_snapshot.clone();
|
||||
|
||||
let apps_enabled = turn_context.apps_enabled();
|
||||
let accessible_connectors =
|
||||
|
||||
@@ -686,7 +686,8 @@ impl Session {
|
||||
.unwrap_or_else(|| session_configuration.cwd().clone());
|
||||
let per_turn_config = Self::build_per_turn_config(&session_configuration, cwd.clone());
|
||||
{
|
||||
let mcp_connection_manager = self.services.mcp_connection_manager.load_full();
|
||||
let mcp_runtime = self.services.latest_mcp_runtime();
|
||||
let mcp_connection_manager = mcp_runtime.manager();
|
||||
mcp_connection_manager.set_approval_policy(&session_configuration.approval_policy);
|
||||
mcp_connection_manager
|
||||
.set_permission_profile(session_configuration.permission_profile());
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::step_context::StepContext;
|
||||
use crate::context::world_state::AgentsMdState;
|
||||
use crate::context::world_state::EnvironmentsState;
|
||||
use crate::context::world_state::WorldState;
|
||||
use codex_extension_api::WorldStateContributionInput;
|
||||
|
||||
impl Session {
|
||||
pub(crate) async fn build_world_state_for_step(
|
||||
@@ -10,6 +11,10 @@ impl Session {
|
||||
step_context: &StepContext,
|
||||
) -> WorldState {
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
tracing::trace!(
|
||||
selected_capability_root_count = step_context.selected_capability_roots.len(),
|
||||
"building step world state"
|
||||
);
|
||||
let environment_subagents = if turn_context.config.include_environment_context {
|
||||
self.services
|
||||
.agent_control
|
||||
@@ -30,6 +35,28 @@ impl Session {
|
||||
.with_subagents(environment_subagents),
|
||||
);
|
||||
}
|
||||
let environments = step_context.environments.to_selections();
|
||||
let ready_selected_capability_roots = step_context
|
||||
.selected_capability_roots
|
||||
.iter()
|
||||
.map(|root| root.selected_root().clone())
|
||||
.collect::<Vec<_>>();
|
||||
for contributor in self.services.extensions.context_contributors() {
|
||||
for section in contributor
|
||||
.contribute_world_state(WorldStateContributionInput {
|
||||
thread_id: self.thread_id(),
|
||||
turn_id: turn_context.sub_id.as_str(),
|
||||
environments: &environments,
|
||||
ready_selected_capability_roots: &ready_selected_capability_roots,
|
||||
session_store: &self.services.session_extension_data,
|
||||
thread_store: &self.services.thread_extension_data,
|
||||
turn_store: turn_context.extension_data.as_ref(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
world_state.add_extension_section(section);
|
||||
}
|
||||
}
|
||||
world_state
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::exec_policy::ExecPolicyManager;
|
||||
use crate::guardian::GuardianRejection;
|
||||
use crate::guardian::GuardianRejectionCircuitBreaker;
|
||||
use crate::mcp::McpManager;
|
||||
use crate::session::McpRuntimeSnapshot;
|
||||
use crate::tools::code_mode::CodeModeService;
|
||||
use crate::tools::handlers::ToolSearchHandlerCache;
|
||||
use crate::tools::network_approval::NetworkApprovalService;
|
||||
@@ -30,9 +31,12 @@ use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_hooks::Hooks;
|
||||
use codex_login::AuthManager;
|
||||
use codex_mcp::McpConfig;
|
||||
use codex_mcp::McpConnectionManager;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_rollout::state_db::StateDbHandle;
|
||||
use codex_rollout_trace::ThreadTraceContext;
|
||||
use codex_thread_store::LiveThread;
|
||||
@@ -43,8 +47,12 @@ use tokio::sync::Mutex;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct SessionServices {
|
||||
/// The latest manager; callers retain an owned handle while performing MCP I/O.
|
||||
/// Mirror of the latest manager for extension resource clients that predate runtime snapshots.
|
||||
pub(crate) mcp_connection_manager: Arc<ArcSwap<McpConnectionManager>>,
|
||||
/// The latest atomically published MCP config and manager pair.
|
||||
pub(crate) mcp_runtime: ArcSwapOption<McpRuntimeSnapshot>,
|
||||
/// Serializes environment-driven runtime rebuilds.
|
||||
pub(crate) mcp_projection_lock: Mutex<()>,
|
||||
pub(crate) mcp_startup_cancellation_token: Mutex<CancellationToken>,
|
||||
pub(crate) unified_exec_manager: UnifiedExecProcessManager,
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
@@ -72,6 +80,9 @@ pub(crate) struct SessionServices {
|
||||
pub(crate) session_extension_data: ExtensionData,
|
||||
pub(crate) thread_extension_data: ExtensionData,
|
||||
pub(crate) supports_openai_form_elicitation: AtomicBool,
|
||||
/// Raw capability selections for this thread. Each model step resolves them against its
|
||||
/// current executor environments before using them.
|
||||
pub(crate) selected_capability_roots: Vec<SelectedCapabilityRoot>,
|
||||
pub(crate) mcp_thread_init: ExtensionDataInit,
|
||||
pub(crate) agent_control: AgentControl,
|
||||
pub(crate) network_proxy: ArcSwapOption<StartedNetworkProxy>,
|
||||
@@ -95,12 +106,41 @@ impl SessionServices {
|
||||
/// resolve through the session's manager while validation waits.
|
||||
pub(crate) async fn install_mcp_connection_manager(
|
||||
&self,
|
||||
config: Arc<McpConfig>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
available_environment_ids: Vec<String>,
|
||||
manager: McpConnectionManager,
|
||||
) -> Result<()> {
|
||||
self.mcp_connection_manager.store(Arc::new(manager));
|
||||
self.mcp_connection_manager
|
||||
.load_full()
|
||||
.validate_required_servers()
|
||||
.await
|
||||
let runtime =
|
||||
self.publish_mcp_runtime(config, runtime_context, available_environment_ids, manager);
|
||||
runtime.manager().validate_required_servers().await
|
||||
}
|
||||
|
||||
pub(crate) fn publish_mcp_runtime(
|
||||
&self,
|
||||
config: Arc<McpConfig>,
|
||||
runtime_context: McpRuntimeContext,
|
||||
available_environment_ids: Vec<String>,
|
||||
manager: McpConnectionManager,
|
||||
) -> Arc<McpRuntimeSnapshot> {
|
||||
let manager = Arc::new(manager);
|
||||
// Publish the manager for legacy resource clients first. Once the paired snapshot is
|
||||
// visible, every model-scoped consumer observes this exact manager.
|
||||
self.mcp_connection_manager.store(Arc::clone(&manager));
|
||||
let runtime = Arc::new(McpRuntimeSnapshot::new(
|
||||
config,
|
||||
manager,
|
||||
runtime_context,
|
||||
available_environment_ids,
|
||||
));
|
||||
self.mcp_runtime.store(Some(Arc::clone(&runtime)));
|
||||
runtime
|
||||
}
|
||||
|
||||
pub(crate) fn latest_mcp_runtime(&self) -> Arc<McpRuntimeSnapshot> {
|
||||
let Some(runtime) = self.mcp_runtime.load_full() else {
|
||||
unreachable!("MCP runtime must be installed before handling requests");
|
||||
};
|
||||
runtime
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ pub struct ThreadManager {
|
||||
|
||||
pub struct StartThreadOptions {
|
||||
pub config: Config,
|
||||
pub allow_provider_model_fallback: bool,
|
||||
pub initial_history: InitialHistory,
|
||||
pub session_source: Option<SessionSource>,
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
@@ -195,8 +196,10 @@ pub struct StartThreadOptions {
|
||||
|
||||
fn originator_from_service_name(service_name: Option<&str>) -> Option<String> {
|
||||
let service_name = service_name?.trim();
|
||||
if service_name.eq_ignore_ascii_case("codex_work_desktop") {
|
||||
return Some("codex_work_desktop".to_string());
|
||||
for originator in ["codex_work_desktop", "codex_work_web", "codex_work_mobile"] {
|
||||
if service_name.eq_ignore_ascii_case(originator) {
|
||||
return Some(originator.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -632,6 +635,7 @@ impl ThreadManager {
|
||||
);
|
||||
Box::pin(self.start_thread_with_options(StartThreadOptions {
|
||||
config,
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -668,6 +672,7 @@ impl ThreadManager {
|
||||
Box::pin(self.state.spawn_thread_with_source(
|
||||
options.config,
|
||||
options.initial_history,
|
||||
options.allow_provider_model_fallback,
|
||||
Arc::clone(&self.state.auth_manager),
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -763,6 +768,7 @@ impl ThreadManager {
|
||||
Box::pin(self.state.spawn_thread_with_source(
|
||||
config,
|
||||
initial_history,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
auth_manager,
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -832,6 +838,7 @@ impl ThreadManager {
|
||||
Box::pin(self.state.spawn_thread_with_source(
|
||||
config,
|
||||
initial_history,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
auth_manager,
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -1332,6 +1339,7 @@ impl ThreadManagerState {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
InitialHistory::New,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
Arc::clone(&self.auth_manager),
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -1370,6 +1378,7 @@ impl ThreadManagerState {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
initial_history,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
Arc::clone(&self.auth_manager),
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -1402,6 +1411,7 @@ impl ThreadManagerState {
|
||||
inherited_environments: Option<TurnEnvironmentSnapshot>,
|
||||
inherited_exec_policy: Option<Arc<crate::exec_policy::ExecPolicyManager>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
thread_extension_init: ExtensionDataInit,
|
||||
) -> CodexResult<NewThread> {
|
||||
let environments = environments.unwrap_or_else(|| {
|
||||
default_thread_environment_selections(self.environment_manager.as_ref(), &config.cwd)
|
||||
@@ -1409,6 +1419,7 @@ impl ThreadManagerState {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
initial_history,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
Arc::clone(&self.auth_manager),
|
||||
agent_control,
|
||||
session_source,
|
||||
@@ -1421,7 +1432,7 @@ impl ThreadManagerState {
|
||||
inherited_exec_policy,
|
||||
/*parent_trace*/ None,
|
||||
environments,
|
||||
/*thread_extension_init*/ ExtensionDataInit::default(),
|
||||
thread_extension_init,
|
||||
/*supports_openai_form_elicitation*/ false,
|
||||
/*user_shell_override*/ None,
|
||||
))
|
||||
@@ -1450,6 +1461,7 @@ impl ThreadManagerState {
|
||||
Box::pin(self.spawn_thread_with_source(
|
||||
config,
|
||||
initial_history,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
auth_manager,
|
||||
agent_control,
|
||||
self.session_source.clone(),
|
||||
@@ -1474,6 +1486,7 @@ impl ThreadManagerState {
|
||||
&self,
|
||||
config: Config,
|
||||
initial_history: InitialHistory,
|
||||
allow_provider_model_fallback: bool,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
agent_control: AgentControl,
|
||||
session_source: SessionSource,
|
||||
@@ -1540,6 +1553,7 @@ impl ThreadManagerState {
|
||||
codex, thread_id, ..
|
||||
} = Box::pin(Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
allow_provider_model_fallback,
|
||||
user_instructions,
|
||||
installation_id: self.installation_id.clone(),
|
||||
auth_manager,
|
||||
|
||||
@@ -20,6 +20,8 @@ use codex_protocol::protocol::AgentMessageEvent;
|
||||
use codex_protocol::protocol::InitialHistory;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::ResumedHistory;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
@@ -120,6 +122,18 @@ fn effective_originator_prefers_thread_scoped_sources_before_env_originator() {
|
||||
Some("inherited_originator"),
|
||||
"codex_work_desktop",
|
||||
),
|
||||
(
|
||||
Some("codex_work_web"),
|
||||
Some("persisted_originator"),
|
||||
Some("inherited_originator"),
|
||||
"codex_work_web",
|
||||
),
|
||||
(
|
||||
Some("codex_work_mobile"),
|
||||
Some("persisted_originator"),
|
||||
Some("inherited_originator"),
|
||||
"codex_work_mobile",
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some("persisted_originator"),
|
||||
@@ -398,6 +412,7 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
|
||||
let thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config,
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: Some(SessionSource::Internal(
|
||||
InternalSessionSource::MemoryConsolidation,
|
||||
@@ -540,6 +555,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
let first_thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -555,6 +571,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
let second_thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -567,8 +584,28 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
})
|
||||
.await
|
||||
.expect("start second thread");
|
||||
let first_resolved = first_thread.thread.runtime_mcp_config(&config).await;
|
||||
let second_resolved = second_thread.thread.runtime_mcp_config(&config).await;
|
||||
let first_session = &first_thread.thread.codex.session;
|
||||
let first_resolved = first_session
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_step(
|
||||
&config,
|
||||
&first_session.services.mcp_thread_init,
|
||||
&first_session.services.thread_extension_data,
|
||||
/*available_environment_ids*/ &[],
|
||||
)
|
||||
.await;
|
||||
let second_session = &second_thread.thread.codex.session;
|
||||
let second_resolved = second_session
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_step(
|
||||
&config,
|
||||
&second_session.services.mcp_thread_init,
|
||||
&second_session.services.thread_extension_data,
|
||||
/*available_environment_ids*/ &[],
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
*lifecycle_observed
|
||||
@@ -610,6 +647,72 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_capability_roots_round_trip_through_fork() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let mut config = test_config().await;
|
||||
config.codex_home = temp_dir.path().join("codex-home").abs();
|
||||
config.cwd = config.codex_home.abs();
|
||||
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
|
||||
|
||||
let manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let selected_roots = vec![SelectedCapabilityRoot {
|
||||
id: "demo@1".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "build".to_string(),
|
||||
path: PathUri::parse("file:///plugins/demo").expect("plugin root URI"),
|
||||
},
|
||||
}];
|
||||
let inherited = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config,
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::Forked(vec![RolloutItem::SessionMeta(
|
||||
SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
selected_capability_roots: selected_roots.clone(),
|
||||
..SessionMeta::default()
|
||||
},
|
||||
git: None,
|
||||
},
|
||||
)]),
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
metrics_service_name: None,
|
||||
parent_trace: None,
|
||||
environments: Vec::new(),
|
||||
thread_extension_init: Default::default(),
|
||||
supports_openai_form_elicitation: false,
|
||||
})
|
||||
.await
|
||||
.expect("start inherited fork");
|
||||
inherited.thread.ensure_rollout_materialized().await;
|
||||
inherited
|
||||
.thread
|
||||
.flush_rollout()
|
||||
.await
|
||||
.expect("flush inherited fork");
|
||||
let inherited_history = RolloutRecorder::get_rollout_history(
|
||||
&inherited
|
||||
.thread
|
||||
.rollout_path()
|
||||
.expect("inherited fork rollout path"),
|
||||
)
|
||||
.await
|
||||
.expect("read inherited fork rollout");
|
||||
|
||||
assert_eq!(
|
||||
inherited_history.get_selected_capability_roots(),
|
||||
selected_roots
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
@@ -647,6 +750,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
let source = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: source_config,
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -930,6 +1034,7 @@ async fn resume_stopped_thread_from_rollout_preserves_thread_source() {
|
||||
let source = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: Some(ThreadSource::User),
|
||||
|
||||
@@ -124,11 +124,12 @@ impl McpHandler {
|
||||
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
call_id,
|
||||
payload,
|
||||
..
|
||||
} = invocation;
|
||||
let turn = Arc::clone(&step_context.turn);
|
||||
|
||||
let payload = match payload {
|
||||
ToolPayload::Function { arguments } => arguments,
|
||||
@@ -143,7 +144,7 @@ impl McpHandler {
|
||||
// TODO(sayan): Use StepContext for MCP file arguments when MCP follows dynamic environments.
|
||||
let result = handle_mcp_tool_call(
|
||||
Arc::clone(&session),
|
||||
&turn,
|
||||
&step_context,
|
||||
call_id.clone(),
|
||||
self.tool_info.server_name.clone(),
|
||||
self.tool_info.tool.name.to_string(),
|
||||
|
||||
@@ -53,11 +53,13 @@ impl ListMcpResourceTemplatesHandler {
|
||||
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
call_id,
|
||||
payload,
|
||||
..
|
||||
} = invocation;
|
||||
let turn = std::sync::Arc::clone(&step_context.turn);
|
||||
let manager = step_context.mcp.manager();
|
||||
|
||||
let arguments = match payload {
|
||||
ToolPayload::Function { arguments } => arguments,
|
||||
@@ -89,7 +91,7 @@ impl ListMcpResourceTemplatesHandler {
|
||||
let params = cursor
|
||||
.clone()
|
||||
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
|
||||
let result = session
|
||||
let result = manager
|
||||
.list_resource_templates(&server_name, params)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
@@ -108,10 +110,7 @@ impl ListMcpResourceTemplatesHandler {
|
||||
));
|
||||
}
|
||||
|
||||
let templates = session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
let templates = manager
|
||||
.list_all_resource_templates(|server_name| {
|
||||
model_can_access_mcp_server(turn.as_ref(), server_name)
|
||||
})
|
||||
|
||||
@@ -53,11 +53,13 @@ impl ListMcpResourcesHandler {
|
||||
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
call_id,
|
||||
payload,
|
||||
..
|
||||
} = invocation;
|
||||
let turn = std::sync::Arc::clone(&step_context.turn);
|
||||
let manager = step_context.mcp.manager();
|
||||
|
||||
let arguments = match payload {
|
||||
ToolPayload::Function { arguments } => arguments,
|
||||
@@ -89,7 +91,7 @@ impl ListMcpResourcesHandler {
|
||||
let params = cursor
|
||||
.clone()
|
||||
.map(|value| PaginatedRequestParams::default().with_cursor(Some(value)));
|
||||
let result = session
|
||||
let result = manager
|
||||
.list_resources(&server_name, params)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
@@ -106,10 +108,7 @@ impl ListMcpResourcesHandler {
|
||||
));
|
||||
}
|
||||
|
||||
let resources = session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
let resources = manager
|
||||
.list_all_resources(|server_name| {
|
||||
model_can_access_mcp_server(turn.as_ref(), server_name)
|
||||
})
|
||||
|
||||
@@ -52,11 +52,13 @@ impl ReadMcpResourceHandler {
|
||||
) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
|
||||
let ToolInvocation {
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
call_id,
|
||||
payload,
|
||||
..
|
||||
} = invocation;
|
||||
let turn = std::sync::Arc::clone(&step_context.turn);
|
||||
let manager = step_context.mcp.manager();
|
||||
|
||||
let arguments = match payload {
|
||||
ToolPayload::Function { arguments } => arguments,
|
||||
@@ -84,7 +86,7 @@ impl ReadMcpResourceHandler {
|
||||
|
||||
let payload_result: Result<ReadResourcePayload, FunctionCallError> = async {
|
||||
ensure_model_can_access_mcp_server(turn.as_ref(), &server)?;
|
||||
let result = session
|
||||
let result = manager
|
||||
.read_resource(&server, ReadResourceRequestParams::new(uri.clone()))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_analytics::PluginInstallRequestSource;
|
||||
use codex_analytics::PluginInstallRequested;
|
||||
@@ -94,10 +95,12 @@ impl RequestPluginInstallHandler {
|
||||
let ToolInvocation {
|
||||
payload,
|
||||
session,
|
||||
turn,
|
||||
step_context,
|
||||
call_id,
|
||||
..
|
||||
} = invocation;
|
||||
let turn = Arc::clone(&step_context.turn);
|
||||
let manager = step_context.mcp.manager();
|
||||
|
||||
let arguments = match payload {
|
||||
ToolPayload::Function { arguments } => arguments,
|
||||
@@ -227,7 +230,8 @@ impl RequestPluginInstallHandler {
|
||||
|
||||
let auth = session.services.auth_manager.auth().await;
|
||||
let completed = if user_confirmed {
|
||||
verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await
|
||||
verify_request_plugin_install_completed(&session, &turn, manager, &tool, auth.as_ref())
|
||||
.await
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@@ -345,13 +349,14 @@ fn disabled_install_request(tool: &DiscoverableTool) -> ToolSuggestDisabledTool
|
||||
async fn verify_request_plugin_install_completed(
|
||||
session: &crate::session::session::Session,
|
||||
turn: &crate::session::turn_context::TurnContext,
|
||||
manager: &codex_mcp::McpConnectionManager,
|
||||
tool: &DiscoverableTool,
|
||||
auth: Option<&codex_login::CodexAuth>,
|
||||
) -> bool {
|
||||
match tool {
|
||||
DiscoverableTool::Connector(connector) => refresh_missing_requested_connectors(
|
||||
session,
|
||||
turn,
|
||||
manager,
|
||||
auth,
|
||||
std::slice::from_ref(&connector.id),
|
||||
connector.id.as_str(),
|
||||
@@ -370,8 +375,8 @@ async fn verify_request_plugin_install_completed(
|
||||
plugin.id.as_str(),
|
||||
),
|
||||
refresh_missing_requested_connectors(
|
||||
session,
|
||||
turn,
|
||||
manager,
|
||||
auth,
|
||||
&plugin.app_connector_ids,
|
||||
plugin.id.as_str(),
|
||||
@@ -393,8 +398,8 @@ async fn verify_request_plugin_install_completed(
|
||||
session.services.plugins_manager.as_ref(),
|
||||
);
|
||||
let _ = refresh_missing_requested_connectors(
|
||||
session,
|
||||
turn,
|
||||
manager,
|
||||
auth,
|
||||
&plugin.app_connector_ids,
|
||||
plugin.id.as_str(),
|
||||
@@ -435,8 +440,8 @@ fn is_remote_plugin_install_suggestion(plugin_id: &str) -> bool {
|
||||
}
|
||||
|
||||
async fn refresh_missing_requested_connectors(
|
||||
session: &crate::session::session::Session,
|
||||
turn: &crate::session::turn_context::TurnContext,
|
||||
manager: &codex_mcp::McpConnectionManager,
|
||||
auth: Option<&codex_login::CodexAuth>,
|
||||
expected_connector_ids: &[String],
|
||||
tool_id: &str,
|
||||
@@ -445,7 +450,6 @@ async fn refresh_missing_requested_connectors(
|
||||
return Some(Vec::new());
|
||||
}
|
||||
|
||||
let manager = session.services.mcp_connection_manager.load_full();
|
||||
let mcp_tools = manager.list_all_tools().await;
|
||||
let accessible_connectors = connectors::with_app_enabled_state(
|
||||
connectors::accessible_connectors_from_mcp_tools(&mcp_tools),
|
||||
|
||||
@@ -6,6 +6,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use crate::exec::ExecCapturePolicy;
|
||||
use crate::exec::ExecParams;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_env::inject_permission_profile_env;
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::maybe_emit_implicit_skill_invocation;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
@@ -99,15 +100,19 @@ impl ShellCommandHandler {
|
||||
let use_login_shell = Self::resolve_use_login_shell(params.login, allow_login_shell)?;
|
||||
let command = Self::base_command(shell, ¶ms.command, use_login_shell);
|
||||
|
||||
let mut 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 env, active_permission_profile.as_ref());
|
||||
|
||||
Ok(ExecParams {
|
||||
command,
|
||||
cwd,
|
||||
expiration: params.timeout_ms.into(),
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
env: create_env(
|
||||
&turn_context.config.permissions.shell_environment_policy,
|
||||
Some(session.thread_id),
|
||||
),
|
||||
env,
|
||||
network: turn_context.network.clone(),
|
||||
network_environment_id: Some(turn_environment.environment_id.clone()),
|
||||
sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::ShellCommandToolCallParams;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::config::PermissionProfileSnapshot;
|
||||
use crate::exec_env::CODEX_PERMISSION_PROFILE_ENV_VAR;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_env::inject_permission_profile_env;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::session::step_context::StepContext;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
@@ -71,7 +75,15 @@ fn assert_safe(shell: &Shell, command: &str) {
|
||||
|
||||
#[tokio::test]
|
||||
async fn shell_command_handler_to_exec_params_uses_selected_environment() {
|
||||
let (session, turn_context) = make_session_and_context().await;
|
||||
let (session, mut turn_context) = make_session_and_context().await;
|
||||
let permission_profile = turn_context.config.permissions.permission_profile().clone();
|
||||
Arc::make_mut(&mut turn_context.config)
|
||||
.permissions
|
||||
.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active(
|
||||
permission_profile,
|
||||
ActivePermissionProfile::new("test-profile"),
|
||||
))
|
||||
.expect("set active permission profile");
|
||||
|
||||
let command = "echo hello".to_string();
|
||||
let workdir = Some("subdir".to_string());
|
||||
@@ -99,10 +111,12 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
|
||||
PathUri::from_abs_path(&selected_cwd),
|
||||
Some(selected_shell),
|
||||
);
|
||||
let expected_env = create_env(
|
||||
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());
|
||||
|
||||
let params = ShellCommandToolCallParams {
|
||||
command,
|
||||
@@ -129,6 +143,12 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() {
|
||||
assert_eq!(exec_params.command, expected_command);
|
||||
assert_eq!(exec_params.cwd, expected_cwd);
|
||||
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)
|
||||
);
|
||||
assert_eq!(exec_params.network, turn_context.network);
|
||||
assert_eq!(
|
||||
exec_params.network_environment_id.as_deref(),
|
||||
|
||||
@@ -110,8 +110,8 @@ async fn parallel_support_does_not_match_namespaced_local_tool_names() -> anyhow
|
||||
let step_context = StepContext::for_test(Arc::clone(&turn));
|
||||
let mcp_tools = session
|
||||
.services
|
||||
.mcp_connection_manager
|
||||
.load_full()
|
||||
.latest_mcp_runtime()
|
||||
.manager()
|
||||
.list_all_tools()
|
||||
.await;
|
||||
let router = ToolRouter::from_context(
|
||||
|
||||
@@ -4,6 +4,7 @@ Module: runtimes
|
||||
Concrete ToolRuntime implementations for specific tools. Each runtime stays
|
||||
small and focused and reuses the orchestrator for approvals + sandbox + retry.
|
||||
*/
|
||||
use crate::exec_env::CODEX_PERMISSION_PROFILE_ENV_VAR;
|
||||
use crate::exec_env::CODEX_THREAD_ID_ENV_VAR;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::shell::Shell;
|
||||
@@ -287,10 +288,14 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
|
||||
.map(|arg| format!(" '{}'", shell_single_quote(arg)))
|
||||
.collect::<String>();
|
||||
let mut override_env = explicit_env_overrides.clone();
|
||||
if let Some(thread_id) = env.get(CODEX_THREAD_ID_ENV_VAR) {
|
||||
override_env.insert(CODEX_THREAD_ID_ENV_VAR.to_string(), thread_id.clone());
|
||||
for key in [CODEX_THREAD_ID_ENV_VAR, CODEX_PERMISSION_PROFILE_ENV_VAR] {
|
||||
if let Some(value) = env.get(key) {
|
||||
override_env.insert(key.to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
let (override_captures, override_exports) = build_override_exports(&override_env);
|
||||
// Do not let a snapshot resurrect a stale profile when no named profile is active.
|
||||
let (override_captures, override_exports) =
|
||||
build_override_exports(&override_env, &[CODEX_PERMISSION_PROFILE_ENV_VAR]);
|
||||
let (proxy_captures, proxy_exports) = build_proxy_env_exports();
|
||||
let runtime_path_prepend_exports =
|
||||
runtime_path_prepends.shell_exports_after_snapshot(explicit_env_overrides);
|
||||
@@ -313,13 +318,18 @@ pub(crate) fn maybe_wrap_shell_lc_with_snapshot(
|
||||
vec![shell_path.to_string(), "-c".to_string(), rewritten_script]
|
||||
}
|
||||
|
||||
fn build_override_exports(explicit_env_overrides: &HashMap<String, String>) -> (String, String) {
|
||||
fn build_override_exports(
|
||||
explicit_env_overrides: &HashMap<String, String>,
|
||||
restore_even_when_absent: &[&str],
|
||||
) -> (String, String) {
|
||||
let mut keys = explicit_env_overrides
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.chain(restore_even_when_absent.iter().copied())
|
||||
.filter(|key| is_valid_shell_variable_name(key))
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
|
||||
build_override_exports_for_keys("__CODEX_SNAPSHOT_OVERRIDE", &keys)
|
||||
}
|
||||
|
||||
@@ -534,6 +534,78 @@ fn maybe_wrap_shell_lc_with_snapshot_restores_codex_thread_id_from_env() {
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "nested-thread");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_wrap_shell_lc_with_snapshot_restores_permission_profile_from_env() {
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
let snapshot_path = dir.path().join("snapshot.sh");
|
||||
std::fs::write(
|
||||
&snapshot_path,
|
||||
"# Snapshot file\nexport CODEX_PERMISSION_PROFILE='parent-profile'\n",
|
||||
)
|
||||
.expect("write snapshot");
|
||||
let (session_shell, shell_snapshot) =
|
||||
shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot_path.abs());
|
||||
let command = vec![
|
||||
"/bin/bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"printenv CODEX_PERMISSION_PROFILE".to_string(),
|
||||
];
|
||||
let env = HashMap::from([(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"current-profile".to_string(),
|
||||
)]);
|
||||
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||
&command,
|
||||
&session_shell,
|
||||
Some(&shell_snapshot),
|
||||
&HashMap::new(),
|
||||
&env,
|
||||
&RuntimePathPrepends::default(),
|
||||
);
|
||||
let output = Command::new(&rewritten[0])
|
||||
.args(&rewritten[1..])
|
||||
.env(CODEX_PERMISSION_PROFILE_ENV_VAR, "current-profile")
|
||||
.output()
|
||||
.expect("run rewritten command");
|
||||
|
||||
assert!(output.status.success(), "command failed: {output:?}");
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "current-profile\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_wrap_shell_lc_with_snapshot_unsets_absent_permission_profile() {
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
let snapshot_path = dir.path().join("snapshot.sh");
|
||||
std::fs::write(
|
||||
&snapshot_path,
|
||||
"# Snapshot file\nexport CODEX_PERMISSION_PROFILE='stale-profile'\n",
|
||||
)
|
||||
.expect("write snapshot");
|
||||
let (session_shell, shell_snapshot) =
|
||||
shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot_path.abs());
|
||||
let command = vec![
|
||||
"/bin/bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"printenv CODEX_PERMISSION_PROFILE".to_string(),
|
||||
];
|
||||
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||
&command,
|
||||
&session_shell,
|
||||
Some(&shell_snapshot),
|
||||
&HashMap::new(),
|
||||
&HashMap::new(),
|
||||
&RuntimePathPrepends::default(),
|
||||
);
|
||||
let output = Command::new(&rewritten[0])
|
||||
.args(&rewritten[1..])
|
||||
.env_remove(CODEX_PERMISSION_PROFILE_ENV_VAR)
|
||||
.output()
|
||||
.expect("run rewritten command");
|
||||
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert_eq!(output.stdout, b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maybe_wrap_shell_lc_with_snapshot_restores_proxy_env_from_process_env() {
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
|
||||
@@ -686,9 +686,12 @@ async fn environment_tools_follow_the_step_context() {
|
||||
|
||||
let environments = turn.environments.clone();
|
||||
turn.environments.turn_environments.clear();
|
||||
let turn = Arc::new(turn);
|
||||
let step_context = Arc::new(StepContext::new(
|
||||
Arc::new(turn),
|
||||
Arc::clone(&turn),
|
||||
environments,
|
||||
Vec::new(),
|
||||
crate::session::McpRuntimeSnapshot::new_uninitialized_for_test(&turn.config),
|
||||
/*loaded_agents_md*/ None,
|
||||
));
|
||||
|
||||
|
||||
@@ -13,8 +13,10 @@ use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::codex_thread::BackgroundTerminalInfo;
|
||||
use crate::exec_env::CODEX_PERMISSION_PROFILE_ENV_VAR;
|
||||
use crate::exec_env::CODEX_THREAD_ID_ENV_VAR;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::exec_env::inject_permission_profile_env;
|
||||
use crate::exec_policy::ExecApprovalRequest;
|
||||
use crate::sandboxing::ExecOptions;
|
||||
use crate::sandboxing::ExecRequest;
|
||||
@@ -109,15 +111,19 @@ fn apply_unified_exec_env(mut env: HashMap<String, String>) -> HashMap<String, S
|
||||
fn exec_env_policy_from_shell_policy(
|
||||
policy: &ShellEnvironmentPolicy,
|
||||
) -> codex_exec_server::ExecEnvPolicy {
|
||||
let mut exclude = policy
|
||||
.exclude
|
||||
.iter()
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
exclude.push(CODEX_PERMISSION_PROFILE_ENV_VAR.to_string());
|
||||
let mut r#set = policy.r#set.clone();
|
||||
r#set.retain(|key, _| !key.eq_ignore_ascii_case(CODEX_PERMISSION_PROFILE_ENV_VAR));
|
||||
codex_exec_server::ExecEnvPolicy {
|
||||
inherit: policy.inherit.clone(),
|
||||
ignore_default_excludes: policy.ignore_default_excludes,
|
||||
exclude: policy
|
||||
.exclude
|
||||
.iter()
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect(),
|
||||
r#set: policy.r#set.clone(),
|
||||
exclude,
|
||||
r#set,
|
||||
include_only: policy
|
||||
.include_only
|
||||
.iter()
|
||||
@@ -132,7 +138,10 @@ fn env_overlay_for_exec_server(
|
||||
) -> HashMap<String, String> {
|
||||
request_env
|
||||
.iter()
|
||||
.filter(|(key, value)| local_policy_env.get(*key) != Some(*value))
|
||||
.filter(|(key, value)| {
|
||||
key.as_str() == CODEX_PERMISSION_PROFILE_ENV_VAR
|
||||
|| local_policy_env.get(*key) != Some(*value)
|
||||
})
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect()
|
||||
}
|
||||
@@ -1110,6 +1119,8 @@ impl UnifiedExecProcessManager {
|
||||
CODEX_THREAD_ID_ENV_VAR.to_string(),
|
||||
context.session.thread_id.to_string(),
|
||||
);
|
||||
let active_permission_profile = context.turn.config.permissions.active_permission_profile();
|
||||
inject_permission_profile_env(&mut env, active_permission_profile.as_ref());
|
||||
let env = apply_unified_exec_env(env);
|
||||
let exec_server_env_config = ExecServerEnvConfig {
|
||||
policy: exec_env_policy_from_shell_policy(
|
||||
|
||||
@@ -42,12 +42,20 @@ fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
||||
("HOME".to_string(), "/client-home".to_string()),
|
||||
("PATH".to_string(), "/client-path".to_string()),
|
||||
("SHELL_SET".to_string(), "policy".to_string()),
|
||||
(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"current-profile".to_string(),
|
||||
),
|
||||
]);
|
||||
let request_env = HashMap::from([
|
||||
("HOME".to_string(), "/client-home".to_string()),
|
||||
("PATH".to_string(), "/sandbox-path".to_string()),
|
||||
("SHELL_SET".to_string(), "policy".to_string()),
|
||||
("CODEX_THREAD_ID".to_string(), "thread-1".to_string()),
|
||||
(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"current-profile".to_string(),
|
||||
),
|
||||
(
|
||||
"CODEX_SANDBOX_NETWORK_DISABLED".to_string(),
|
||||
"1".to_string(),
|
||||
@@ -59,6 +67,10 @@ fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
||||
HashMap::from([
|
||||
("PATH".to_string(), "/sandbox-path".to_string()),
|
||||
("CODEX_THREAD_ID".to_string(), "thread-1".to_string()),
|
||||
(
|
||||
CODEX_PERMISSION_PROFILE_ENV_VAR.to_string(),
|
||||
"current-profile".to_string(),
|
||||
),
|
||||
(
|
||||
"CODEX_SANDBOX_NETWORK_DISABLED".to_string(),
|
||||
"1".to_string()
|
||||
@@ -67,6 +79,31 @@ fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_env_policy_excludes_runtime_permission_profile() {
|
||||
let policy = ShellEnvironmentPolicy {
|
||||
r#set: HashMap::from([
|
||||
(
|
||||
"codex_permission_profile".to_string(),
|
||||
"stale-profile".to_string(),
|
||||
),
|
||||
("KEEP".to_string(), "value".to_string()),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
exec_env_policy_from_shell_policy(&policy),
|
||||
codex_exec_server::ExecEnvPolicy {
|
||||
inherit: policy.inherit,
|
||||
ignore_default_excludes: policy.ignore_default_excludes,
|
||||
exclude: vec![CODEX_PERMISSION_PROFILE_ENV_VAR.to_string()],
|
||||
r#set: HashMap::from([("KEEP".to_string(), "value".to_string())]),
|
||||
include_only: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
|
||||
let cwd: codex_utils_absolute_path::AbsolutePathBuf = std::env::current_dir()
|
||||
|
||||
@@ -658,6 +658,7 @@ impl TestCodexBuilder {
|
||||
Box::pin(
|
||||
thread_manager.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
|
||||
@@ -10,6 +10,7 @@ use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
|
||||
use crate::test_codex::TestCodex;
|
||||
use crate::test_codex::TestCodexBuilder;
|
||||
use crate::test_codex::test_codex;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -19,12 +20,7 @@ pub struct ZshForkRuntime {
|
||||
}
|
||||
|
||||
impl ZshForkRuntime {
|
||||
fn apply_to_config(
|
||||
&self,
|
||||
config: &mut Config,
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
) {
|
||||
fn apply_to_config(&self, config: &mut Config, approval_policy: AskForApproval) {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ShellTool)
|
||||
@@ -37,10 +33,6 @@ impl ZshForkRuntime {
|
||||
config.main_execve_wrapper_exe = Some(self.main_execve_wrapper_exe.clone());
|
||||
config.permissions.allow_login_shell = false;
|
||||
config.permissions.approval_policy = Constrained::allow_any(approval_policy);
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile)
|
||||
.expect("set permission profile");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,10 +78,13 @@ pub async fn build_zsh_fork_test<F>(
|
||||
where
|
||||
F: FnOnce(&Path) + Send + 'static,
|
||||
{
|
||||
let mut builder = test_codex()
|
||||
let mut builder = zsh_fork_test_builder(runtime, approval_policy)
|
||||
.with_pre_build_hook(pre_build_hook)
|
||||
.with_config(move |config| {
|
||||
runtime.apply_to_config(config, approval_policy, permission_profile);
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile)
|
||||
.expect("set permission profile");
|
||||
});
|
||||
builder.build(server).await
|
||||
}
|
||||
@@ -104,10 +99,13 @@ pub async fn build_unified_exec_zsh_fork_test<F>(
|
||||
where
|
||||
F: FnOnce(&Path) + Send + 'static,
|
||||
{
|
||||
let mut builder = test_codex()
|
||||
let mut builder = zsh_fork_test_builder(runtime, approval_policy)
|
||||
.with_pre_build_hook(pre_build_hook)
|
||||
.with_config(move |config| {
|
||||
runtime.apply_to_config(config, approval_policy, permission_profile);
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(permission_profile)
|
||||
.expect("set permission profile");
|
||||
config.use_experimental_unified_exec_tool = true;
|
||||
config
|
||||
.features
|
||||
@@ -121,6 +119,15 @@ where
|
||||
builder.build(server).await
|
||||
}
|
||||
|
||||
pub fn zsh_fork_test_builder(
|
||||
runtime: ZshForkRuntime,
|
||||
approval_policy: AskForApproval,
|
||||
) -> TestCodexBuilder {
|
||||
test_codex().with_config(move |config| {
|
||||
runtime.apply_to_config(config, approval_policy);
|
||||
})
|
||||
}
|
||||
|
||||
fn find_test_zsh_path() -> Result<Option<PathBuf>> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let dotslash_zsh = repo_root.join("codex-rs/app-server/tests/suite/zsh");
|
||||
|
||||
@@ -486,6 +486,7 @@ async fn loads_user_instructions_without_a_primary_environment() -> Result<()> {
|
||||
.thread_manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: test.config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -691,6 +692,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
|
||||
.thread_manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: test.config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
|
||||
@@ -10,6 +10,7 @@ use codex_features::Feature;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
use codex_protocol::approvals::NetworkPolicyAmendment;
|
||||
use codex_protocol::approvals::NetworkPolicyRuleAction;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
@@ -47,6 +48,7 @@ use core_test_support::wait_for_event_with_timeout;
|
||||
use core_test_support::zsh_fork::build_zsh_fork_test;
|
||||
use core_test_support::zsh_fork::restrictive_workspace_write_profile;
|
||||
use core_test_support::zsh_fork::zsh_fork_runtime;
|
||||
use core_test_support::zsh_fork::zsh_fork_test_builder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use regex_lite::Regex;
|
||||
use serde_json::Value;
|
||||
@@ -131,6 +133,8 @@ enum ActionKind {
|
||||
|
||||
const DEFAULT_UNIFIED_EXEC_JUSTIFICATION: &str =
|
||||
"Requires escalated permissions to bypass the sandbox in tests.";
|
||||
const WORKSPACE_PERMISSION_PROFILE_CONFIG: &str = r#"default_permissions = ":workspace"
|
||||
"#;
|
||||
|
||||
impl ActionKind {
|
||||
fn policy_src(&self) -> Option<&'static str> {
|
||||
@@ -640,6 +644,7 @@ enum ScenarioGroup {
|
||||
UnifiedExec,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
struct CommandResult {
|
||||
exit_code: Option<i64>,
|
||||
stdout: String,
|
||||
@@ -683,6 +688,52 @@ async fn submit_turn(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn submit_turn_preserving_active_permission_profile(
|
||||
test: &TestCodex,
|
||||
prompt: &str,
|
||||
approval_policy: AskForApproval,
|
||||
) -> Result<()> {
|
||||
let session_model = test.session_configured.model.clone();
|
||||
|
||||
test.codex
|
||||
.submit(Op::UserInput {
|
||||
items: vec![UserInput::Text {
|
||||
text: prompt.into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
additional_context: Default::default(),
|
||||
thread_settings: codex_protocol::protocol::ThreadSettingsOverrides {
|
||||
environments: Some(local_selections(test.config.cwd.clone())),
|
||||
approval_policy: Some(approval_policy),
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
collaboration_mode: Some(codex_protocol::config_types::CollaborationMode {
|
||||
mode: codex_protocol::config_types::ModeKind::Default,
|
||||
settings: codex_protocol::config_types::Settings {
|
||||
model: session_model,
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_active_workspace_permission_profile(test: &TestCodex) {
|
||||
assert_eq!(
|
||||
test.session_configured
|
||||
.active_permission_profile
|
||||
.as_ref()
|
||||
.map(|profile| profile.id.as_str()),
|
||||
Some(BUILT_IN_PERMISSION_PROFILE_WORKSPACE)
|
||||
);
|
||||
}
|
||||
|
||||
fn parse_result(item: &Value) -> CommandResult {
|
||||
let output_str = item
|
||||
.get("output")
|
||||
@@ -2696,6 +2747,325 @@ async fn matched_prefix_rule_runs_unsandboxed_under_zsh_fork() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verifies that an allowlisted script retains the originating named profile
|
||||
/// when its shell tool call requests escalated, unsandboxed execution.
|
||||
///
|
||||
/// Tool owners use this pattern when a trusted wrapper must run outside the
|
||||
/// current sandbox, but then needs to launch child commands back inside the
|
||||
/// same sandbox with `codex sandbox -P`. The nested invocation must also pass
|
||||
/// `--include-managed-config` so it continues to honor enterprise requirements.
|
||||
/// The test proves both halves of that contract: the wrapper writes outside the
|
||||
/// `:workspace` sandbox, while its inherited profile name remains `:workspace`.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[cfg(unix)]
|
||||
async fn allowed_escalated_shell_command_inherits_active_permission_profile() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
fs::write(
|
||||
home.path().join("config.toml"),
|
||||
WORKSPACE_PERMISSION_PROFILE_CONFIG,
|
||||
)?;
|
||||
|
||||
let script_dir = tempfile::tempdir_in(std::env::current_dir()?)?;
|
||||
let script_path = script_dir.path().join("print-permission-profile.sh");
|
||||
let outside_path = script_dir.path().join("unsandboxed-marker");
|
||||
fs::write(
|
||||
&script_path,
|
||||
format!(
|
||||
r#"#!/bin/sh
|
||||
# Print the inherited profile so the test can verify that it reached this script.
|
||||
printenv CODEX_PERMISSION_PROFILE
|
||||
touch {outside_path:?}
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
|
||||
let rules_dir = home.path().join("rules");
|
||||
fs::create_dir_all(&rules_dir)?;
|
||||
let script_pattern = serde_json::to_string(&script_path.to_string_lossy())?;
|
||||
fs::write(
|
||||
rules_dir.join("default.rules"),
|
||||
format!(r#"prefix_rule(pattern=["/bin/sh", {script_pattern}], decision="allow")"#),
|
||||
)?;
|
||||
|
||||
let approval_policy = AskForApproval::OnRequest;
|
||||
let mut builder = test_codex().with_home(home).with_config(move |config| {
|
||||
config.permissions.approval_policy = Constrained::allow_any(approval_policy);
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
assert!(!outside_path.starts_with(test.config.cwd.as_path()));
|
||||
assert_active_workspace_permission_profile(&test);
|
||||
|
||||
let call_id = "allowed-escalated-shell-inherits-permission-profile";
|
||||
let command = format!("/bin/sh {script_path:?}");
|
||||
let event = shell_event(
|
||||
call_id,
|
||||
&command,
|
||||
/*timeout_ms*/ 5_000,
|
||||
SandboxPermissions::RequireEscalated,
|
||||
)?;
|
||||
let _ = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-escalated-profile-1"),
|
||||
event,
|
||||
ev_completed("resp-escalated-profile-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let results = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_assistant_message("msg-escalated-profile-1", "done"),
|
||||
ev_completed("resp-escalated-profile-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
submit_turn_preserving_active_permission_profile(
|
||||
&test,
|
||||
"run the allowed script with escalated permissions",
|
||||
approval_policy,
|
||||
)
|
||||
.await?;
|
||||
|
||||
wait_for_completion_without_approval(&test).await;
|
||||
|
||||
let result = parse_result(&results.single_request().function_call_output(call_id));
|
||||
assert_eq!(
|
||||
result,
|
||||
CommandResult {
|
||||
exit_code: Some(0),
|
||||
stdout: format!("{BUILT_IN_PERMISSION_PROFILE_WORKSPACE}\n"),
|
||||
},
|
||||
"the unsandboxed script should inherit CODEX_PERMISSION_PROFILE from the shell command"
|
||||
);
|
||||
assert!(
|
||||
outside_path.exists(),
|
||||
"allowed escalated script should run outside the :workspace sandbox"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Verifies that zsh-fork applies an inner script's allow rule even when the
|
||||
/// model invokes an outer wrapper, and that the escalated script retains the
|
||||
/// named profile needed to reconstruct the original sandbox remotely without
|
||||
/// dropping managed enterprise requirements. The script treats the inherited
|
||||
/// environment value as untrusted and accepts only explicitly allowlisted
|
||||
/// profile names before passing one to `codex sandbox -P`.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[cfg(unix)]
|
||||
async fn zsh_fork_inner_allowed_script_inherits_active_permission_profile() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let Some(runtime) = zsh_fork_runtime("zsh-fork remote sandbox wrapper test")? else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
const HOST: &str = "builder.example.com";
|
||||
let approval_policy = AskForApproval::OnRequest;
|
||||
let script_dir = tempfile::tempdir_in(std::env::current_dir()?)?;
|
||||
let wrapper_path = script_dir.path().join("remote-bash");
|
||||
let remote_bash_path = script_dir.path().join("remote_bash.py");
|
||||
let outside_path = script_dir.path().join("remote-bash-unsandboxed-marker");
|
||||
let outside_path_literal = serde_json::to_string(&outside_path.to_string_lossy())?;
|
||||
fs::write(
|
||||
&remote_bash_path,
|
||||
format!(
|
||||
r#"#!/usr/bin/env python3
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
ALLOWED_HOSTS = ("builder.example.com",)
|
||||
ALLOWED_PROFILES = (":workspace",)
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Print an ssh command that recreates the current Codex sandbox remotely."
|
||||
)
|
||||
parser.add_argument("--host", required=True)
|
||||
try:
|
||||
separator = sys.argv.index("--")
|
||||
except ValueError:
|
||||
parser.error("the remote command must follow --")
|
||||
args = parser.parse_args(sys.argv[1:separator])
|
||||
args.command = sys.argv[separator + 1:]
|
||||
if not args.command:
|
||||
parser.error("the remote command must not be empty")
|
||||
if not re.fullmatch(r"[a-z0-9.-]+", args.host) or args.host not in ALLOWED_HOSTS:
|
||||
parser.error("host is not allowlisted")
|
||||
return args
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
profile_name = os.environ.get("CODEX_PERMISSION_PROFILE")
|
||||
if not profile_name:
|
||||
raise SystemExit("CODEX_PERMISSION_PROFILE must not be empty")
|
||||
if profile_name not in ALLOWED_PROFILES:
|
||||
raise SystemExit("CODEX_PERMISSION_PROFILE is not allowlisted")
|
||||
|
||||
shell_command = shlex.join(args.command)
|
||||
sandbox_command = shlex.join(
|
||||
[
|
||||
"codex",
|
||||
"sandbox",
|
||||
"-P",
|
||||
profile_name,
|
||||
"--include-managed-config",
|
||||
"--",
|
||||
"bash",
|
||||
"-lc",
|
||||
shell_command,
|
||||
]
|
||||
)
|
||||
print(shlex.join(["ssh", args.host, sandbox_command]))
|
||||
|
||||
# Test-only proof that this inner script was allowed to run unsandboxed.
|
||||
Path({outside_path_literal}).write_text("unsandboxed", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
let remote_bash_exec = shlex::try_join([remote_bash_path.to_string_lossy().as_ref()])?;
|
||||
fs::write(
|
||||
&wrapper_path,
|
||||
format!(
|
||||
r#"#!/usr/bin/env zsh
|
||||
exec {remote_bash_exec} "$@"
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
for path in [&wrapper_path, &remote_bash_path] {
|
||||
let mut permissions = fs::metadata(path)?.permissions();
|
||||
permissions.set_mode(0o755);
|
||||
fs::set_permissions(path, permissions)?;
|
||||
}
|
||||
|
||||
let remote_bash_pattern = serde_json::to_string(&remote_bash_path.to_string_lossy())?;
|
||||
let rules = format!(r#"prefix_rule(pattern=[{remote_bash_pattern}], decision="allow")"#);
|
||||
let server = start_mock_server().await;
|
||||
let mut builder =
|
||||
zsh_fork_test_builder(runtime, approval_policy).with_pre_build_hook(move |home| {
|
||||
fs::write(
|
||||
home.join("config.toml"),
|
||||
WORKSPACE_PERMISSION_PROFILE_CONFIG,
|
||||
)
|
||||
.expect("write config");
|
||||
let rules_dir = home.join("rules");
|
||||
fs::create_dir_all(&rules_dir).expect("create rules dir");
|
||||
fs::write(rules_dir.join("default.rules"), rules).expect("write rules");
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
assert!(!outside_path.starts_with(test.config.cwd.as_path()));
|
||||
assert_active_workspace_permission_profile(&test);
|
||||
|
||||
let command = shlex::try_join([
|
||||
wrapper_path.to_string_lossy().as_ref(),
|
||||
"--host",
|
||||
HOST,
|
||||
"--",
|
||||
"printf",
|
||||
"%s",
|
||||
"hello world",
|
||||
])?;
|
||||
let call_id = "zsh-fork-remote-sandbox-wrapper";
|
||||
let event = shell_event(
|
||||
call_id,
|
||||
&command,
|
||||
/*timeout_ms*/ 30_000,
|
||||
SandboxPermissions::UseDefault,
|
||||
)?;
|
||||
let _ = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("resp-zsh-fork-remote-wrapper-1"),
|
||||
event,
|
||||
ev_completed("resp-zsh-fork-remote-wrapper-1"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let results = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_assistant_message("msg-zsh-fork-remote-wrapper-1", "done"),
|
||||
ev_completed("resp-zsh-fork-remote-wrapper-2"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
submit_turn_preserving_active_permission_profile(
|
||||
&test,
|
||||
"run the remote sandbox wrapper",
|
||||
approval_policy,
|
||||
)
|
||||
.await?;
|
||||
wait_for_completion_without_approval(&test).await;
|
||||
|
||||
let result = parse_result(&results.single_request().function_call_output(call_id));
|
||||
assert_eq!(
|
||||
result.exit_code.unwrap_or(0),
|
||||
0,
|
||||
"the inner remote_bash.py script should run successfully: {}",
|
||||
result.stdout
|
||||
);
|
||||
let ssh_argv = shlex::split(result.stdout.trim()).context("parse printed ssh command")?;
|
||||
assert_eq!(
|
||||
ssh_argv.len(),
|
||||
3,
|
||||
"expected ssh HOST LONG_COMMAND, got: {}",
|
||||
result.stdout
|
||||
);
|
||||
assert_eq!(
|
||||
ssh_argv[..2],
|
||||
["ssh", HOST],
|
||||
"remote_bash.py should target only the allowlisted host"
|
||||
);
|
||||
let sandbox_argv = shlex::split(&ssh_argv[2]).context("parse remote sandbox command")?;
|
||||
assert_eq!(
|
||||
sandbox_argv.len(),
|
||||
9,
|
||||
"expected codex sandbox ... bash -lc CMD"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_argv[..8],
|
||||
[
|
||||
"codex",
|
||||
"sandbox",
|
||||
"-P",
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
|
||||
"--include-managed-config",
|
||||
"--",
|
||||
"bash",
|
||||
"-lc",
|
||||
],
|
||||
"remote_bash.py should use the allowlisted inherited profile and managed configuration to reconstruct the Codex sandbox"
|
||||
);
|
||||
let command_argv = shlex::split(&sandbox_argv[8]).context("parse remote bash command")?;
|
||||
assert_eq!(
|
||||
command_argv,
|
||||
["printf", "%s", "hello world"],
|
||||
"remote_bash.py should preserve every argument after --"
|
||||
);
|
||||
assert!(
|
||||
outside_path.exists(),
|
||||
"the inner allowlisted script should run outside the :workspace sandbox"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
#[cfg(unix)]
|
||||
async fn invalid_requested_prefix_rule_falls_back_for_compound_command() -> Result<()> {
|
||||
|
||||
@@ -12,6 +12,7 @@ use codex_core::SleepFuture;
|
||||
use codex_core::TimeFuture;
|
||||
use codex_core::TimeProvider;
|
||||
use codex_core::config::CurrentTimeReminderConfig;
|
||||
use codex_features::CurrentTimeReminderDeliveryMode;
|
||||
use codex_features::CurrentTimeSource;
|
||||
use codex_features::Feature;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
@@ -39,6 +40,7 @@ use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
const FIRST_REMINDER: &str = "It is 2026-06-17 17:34:15 UTC.";
|
||||
const EARLIER_REMINDER: &str = "It is 2026-06-17 17:33:15 UTC.";
|
||||
const SECOND_REMINDER: &str = "It is 2026-06-17 17:35:15 UTC.";
|
||||
const THIRD_REMINDER: &str = "It is 2026-06-17 17:36:15 UTC.";
|
||||
const FIRST_TIME_UNIX_SECONDS: i64 = 1_781_717_655;
|
||||
@@ -162,6 +164,107 @@ async fn current_time_reminders_follow_time_interval_and_persist_in_history() ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn zero_current_time_reminder_interval_delivers_when_time_moves_backward() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
|
||||
sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let time_provider = Arc::new(TestTimeProvider::default());
|
||||
let test = test_codex()
|
||||
.with_config(|config| {
|
||||
enable_current_time_reminder(config, /*interval*/ 0, CurrentTimeSource::External)
|
||||
})
|
||||
.with_external_time_provider(time_provider.clone())
|
||||
.build(&server)
|
||||
.await?;
|
||||
|
||||
test.submit_turn("first turn").await?;
|
||||
time_provider
|
||||
.current_time
|
||||
.store(FIRST_TIME_UNIX_SECONDS - 60, Ordering::Relaxed);
|
||||
test.submit_turn("second turn").await?;
|
||||
|
||||
let requests = responses.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_eq!(current_time_reminders(&requests[0]), vec![FIRST_REMINDER]);
|
||||
assert_eq!(
|
||||
current_time_reminders(&requests[1]),
|
||||
vec![FIRST_REMINDER, EARLIER_REMINDER]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn current_time_reminders_can_follow_only_user_or_tool_outputs() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let tool_args = json!({
|
||||
"command": "echo current time",
|
||||
"timeout_ms": 1_000,
|
||||
});
|
||||
let mut continue_response = ev_completed("resp-2");
|
||||
// Ask for another inference without recording a new user message or tool output.
|
||||
continue_response["response"]["end_turn"] = json!(false);
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("resp-1"),
|
||||
ev_function_call(
|
||||
"current-time-tool-call",
|
||||
"shell_command",
|
||||
&serde_json::to_string(&tool_args)?,
|
||||
),
|
||||
ev_completed("resp-1"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_response_created("resp-2"),
|
||||
ev_assistant_message("msg-2", "continue"),
|
||||
continue_response,
|
||||
]),
|
||||
sse(vec![ev_response_created("resp-3"), ev_completed("resp-3")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let test = test_codex()
|
||||
.with_config(|config| {
|
||||
enable_current_time_reminder(config, /*interval*/ 0, CurrentTimeSource::External);
|
||||
config
|
||||
.current_time_reminder
|
||||
.as_mut()
|
||||
.expect("current-time reminder should be configured")
|
||||
.delivery_mode = CurrentTimeReminderDeliveryMode::AfterUserOrToolOutput;
|
||||
})
|
||||
.with_external_time_provider(Arc::new(TestTimeProvider::default()))
|
||||
.build(&server)
|
||||
.await?;
|
||||
|
||||
test.submit_turn_with_permission_profile("first turn", PermissionProfile::Disabled)
|
||||
.await?;
|
||||
|
||||
let requests = responses.requests();
|
||||
assert_eq!(requests.len(), 3);
|
||||
assert_eq!(current_time_reminders(&requests[0]), vec![FIRST_REMINDER]);
|
||||
assert_eq!(
|
||||
current_time_reminders(&requests[1]),
|
||||
vec![FIRST_REMINDER, SECOND_REMINDER]
|
||||
);
|
||||
assert_eq!(
|
||||
current_time_reminders(&requests[2]),
|
||||
vec![FIRST_REMINDER, SECOND_REMINDER]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn system_time_source_adds_current_time_reminder() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -221,6 +324,11 @@ async fn current_time_reminder_is_refreshed_after_compaction() -> Result<()> {
|
||||
/*interval*/ 3_000,
|
||||
CurrentTimeSource::External,
|
||||
);
|
||||
config
|
||||
.current_time_reminder
|
||||
.as_mut()
|
||||
.expect("current-time reminder should be configured")
|
||||
.delivery_mode = CurrentTimeReminderDeliveryMode::AfterUserOrToolOutput;
|
||||
})
|
||||
.with_external_time_provider(Arc::new(TestTimeProvider::default()))
|
||||
.build(&server)
|
||||
|
||||
@@ -16,7 +16,7 @@ use core_test_support::test_codex::test_codex;
|
||||
use core_test_support::wait_for_mcp_server;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn refresh_shuts_down_superseded_mcp_stdio_server() -> anyhow::Result<()> {
|
||||
async fn refresh_keeps_superseded_mcp_server_alive_for_in_flight_calls() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
@@ -84,7 +84,7 @@ async fn refresh_shuts_down_superseded_mcp_stdio_server() -> anyhow::Result<()>
|
||||
"sync",
|
||||
Some(serde_json::json!({
|
||||
"barrier": barrier,
|
||||
"sleep_after_ms": 30_000
|
||||
"sleep_after_ms": 300_000
|
||||
})),
|
||||
/*meta*/ None,
|
||||
)
|
||||
@@ -119,9 +119,16 @@ async fn refresh_shuts_down_superseded_mcp_stdio_server() -> anyhow::Result<()>
|
||||
|
||||
let replacement_pid = wait_for_pid_file(&pid_file).await?;
|
||||
assert_ne!(replacement_pid, superseded_pid);
|
||||
assert!(process_is_alive(&superseded_pid)?);
|
||||
long_call.abort();
|
||||
assert!(
|
||||
long_call
|
||||
.await
|
||||
.expect_err("call should be aborted")
|
||||
.is_cancelled()
|
||||
);
|
||||
wait_for_process_exit(&superseded_pid).await?;
|
||||
assert!(process_is_alive(&replacement_pid)?);
|
||||
assert!(long_call.await?.is_err());
|
||||
|
||||
fixture.codex.shutdown_and_wait().await?;
|
||||
wait_for_process_exit(&replacement_pid).await
|
||||
|
||||
@@ -75,6 +75,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R
|
||||
model_provider: None,
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
@@ -127,6 +128,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re
|
||||
model_provider: None,
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
|
||||
@@ -1059,7 +1059,11 @@ async fn remote_models_request_times_out_after_5s() -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let model = timeout(
|
||||
Duration::from_secs(7),
|
||||
manager.get_default_model(&None, RefreshStrategy::OnlineIfUncached),
|
||||
manager.get_default_model(
|
||||
&None,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let elapsed = start.elapsed();
|
||||
@@ -1127,7 +1131,11 @@ async fn remote_models_hide_picker_only_models() -> Result<()> {
|
||||
);
|
||||
|
||||
let selected = manager
|
||||
.get_default_model(&None, RefreshStrategy::OnlineIfUncached)
|
||||
.get_default_model(
|
||||
&None,
|
||||
/*allow_provider_model_fallback*/ false,
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(selected, bundled_default_model_slug());
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ use codex_config::types::McpServerTransportConfig;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::HttpRedirectPolicy;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::MCP_SANDBOX_STATE_META_CAPABILITY;
|
||||
@@ -2934,6 +2935,7 @@ async fn wait_for_remote_streamable_http_server(
|
||||
headers: Vec::new(),
|
||||
body: None,
|
||||
timeout_ms: Some(remaining.as_millis().clamp(1, 1_000) as u64),
|
||||
redirect_policy: HttpRedirectPolicy::Follow,
|
||||
request_id: "buffered-request".to_string(),
|
||||
stream_response: false,
|
||||
};
|
||||
|
||||
@@ -372,6 +372,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> {
|
||||
model_provider: None,
|
||||
base_instructions: None,
|
||||
dynamic_tools: None,
|
||||
selected_capability_roots: Vec::new(),
|
||||
memory_mode: None,
|
||||
multi_agent_version: None,
|
||||
context_window: None,
|
||||
|
||||
@@ -761,6 +761,7 @@ async fn subagent_stop_replaces_stop_and_skips_internal_subagents() -> Result<()
|
||||
.thread_manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: test.config.clone(),
|
||||
allow_provider_model_fallback: false,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: Some(SessionSource::SubAgent(SubAgentSource::Review)),
|
||||
thread_source: None,
|
||||
|
||||
Reference in New Issue
Block a user