From 70e6930d9b62ecfd043da58105d814a5c4c3f0aa Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 25 Jun 2026 02:26:04 +0100 Subject: [PATCH] Prepare selected capability snapshots --- codex-rs/Cargo.lock | 4 + codex-rs/connectors/src/lib.rs | 1 + codex-rs/connectors/src/snapshot.rs | 30 +++ codex-rs/core-plugins/src/lib.rs | 2 + .../core-plugins/src/selected_capabilities.rs | 73 +++++++ .../src/selected_capabilities_tests.rs | 4 + codex-rs/ext/connectors/Cargo.toml | 7 + codex-rs/ext/connectors/src/lib.rs | 6 +- codex-rs/ext/connectors/src/selected.rs | 179 +++++++++++++++--- codex-rs/ext/connectors/tests/selected.rs | 139 ++++++++++++++ .../ext/extension-api/src/contributors.rs | 13 ++ codex-rs/ext/extension-api/src/lib.rs | 1 + codex-rs/ext/extension-api/src/registry.rs | 31 +++ codex-rs/ext/mcp/Cargo.toml | 2 +- codex-rs/ext/mcp/src/executor_plugin.rs | 102 ++++++---- codex-rs/ext/mcp/tests/executor_plugin_mcp.rs | 47 ++++- 16 files changed, 571 insertions(+), 70 deletions(-) create mode 100644 codex-rs/ext/connectors/tests/selected.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 0121d173cd..3f1de6e1ce 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2603,12 +2603,16 @@ version = "0.0.0" dependencies = [ "codex-connectors", "codex-core-plugins", + "codex-exec-server", "codex-extension-api", "codex-plugin", "codex-protocol", "codex-utils-path-uri", + "pretty_assertions", "serde_json", + "tempfile", "thiserror 2.0.18", + "tokio", "tracing", ] diff --git a/codex-rs/connectors/src/lib.rs b/codex-rs/connectors/src/lib.rs index f77936e88f..c4e98b69d2 100644 --- a/codex-rs/connectors/src/lib.rs +++ b/codex-rs/connectors/src/lib.rs @@ -32,6 +32,7 @@ pub use directory_cache::ConnectorDirectoryCacheContext; pub use plugin_config::parse_plugin_app_config; pub use plugin_config::parse_plugin_app_config_value; pub use snapshot::ConnectorSnapshot; +pub use snapshot::ConnectorSnapshotState; pub use snapshot::PluginConnectorSource; pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600); diff --git a/codex-rs/connectors/src/snapshot.rs b/codex-rs/connectors/src/snapshot.rs index bf14f8e0f0..9f9e4c4706 100644 --- a/codex-rs/connectors/src/snapshot.rs +++ b/codex-rs/connectors/src/snapshot.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; use std::collections::HashSet; +use std::sync::Mutex; +use std::sync::PoisonError; use codex_plugin::AppConnectorId; use codex_plugin::AppDeclaration; @@ -77,6 +79,34 @@ pub struct ConnectorSnapshot { plugin_display_names_by_connector_id: HashMap>, } +/// Mutable holder for the connector snapshot published at a runtime boundary. +#[derive(Debug, Default)] +pub struct ConnectorSnapshotState { + snapshot: Mutex, +} + +impl ConnectorSnapshotState { + /// Creates a holder with the supplied active snapshot. + pub fn new(snapshot: ConnectorSnapshot) -> Self { + Self { + snapshot: Mutex::new(snapshot), + } + } + + /// Returns the currently published connector snapshot. + pub fn snapshot(&self) -> ConnectorSnapshot { + self.snapshot + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Replaces the active connector snapshot. + pub fn publish(&self, snapshot: ConnectorSnapshot) { + *self.snapshot.lock().unwrap_or_else(PoisonError::into_inner) = snapshot; + } +} + impl ConnectorSnapshot { /// Builds a connector snapshot from package-scoped declarations. pub fn from_plugin_sources(sources: impl IntoIterator) -> Self { diff --git a/codex-rs/core-plugins/src/lib.rs b/codex-rs/core-plugins/src/lib.rs index be557936d7..29a2cbcf74 100644 --- a/codex-rs/core-plugins/src/lib.rs +++ b/codex-rs/core-plugins/src/lib.rs @@ -63,6 +63,8 @@ pub use provider::ResolvedExecutorPlugin; pub use provider::ResolvedSelectedCapabilityRoot; pub use remote::RecommendedPlugin; pub use remote::RecommendedPluginsMode; +pub use selected_capabilities::SelectedCapabilityActivation; +pub use selected_capabilities::SelectedCapabilityActivationSnapshot; pub use selected_capabilities::SelectedCapabilityBindingSnapshot; pub use selected_capabilities::SelectedCapabilityBindingStatus; pub use selected_capabilities::SelectedCapabilityBindings; diff --git a/codex-rs/core-plugins/src/selected_capabilities.rs b/codex-rs/core-plugins/src/selected_capabilities.rs index 8b0b9f7e9e..1f016c9414 100644 --- a/codex-rs/core-plugins/src/selected_capabilities.rs +++ b/codex-rs/core-plugins/src/selected_capabilities.rs @@ -114,6 +114,62 @@ impl SelectedCapabilitySnapshot { } } +/// One coherent selected-capability generation published for runtime use. +#[derive(Clone)] +pub struct SelectedCapabilityActivationSnapshot { + selected_capabilities: SelectedCapabilitySnapshot, +} + +impl SelectedCapabilityActivationSnapshot { + /// Returns the selected-capability generation represented by this activation. + pub fn generation(&self) -> u64 { + self.selected_capabilities.generation() + } + + /// Returns the exact selected-root snapshot used to build this activation. + pub fn selected_capabilities(&self) -> &SelectedCapabilitySnapshot { + &self.selected_capabilities + } +} + +/// Thread-owned selected-capability generation visible to runtime consumers. +pub struct SelectedCapabilityActivation { + state: Mutex, +} + +impl SelectedCapabilityActivation { + /// Creates an activation from one selected-root snapshot. + pub fn new(selected_capabilities: SelectedCapabilitySnapshot) -> Self { + Self { + state: Mutex::new(SelectedCapabilityActivationSnapshot { + selected_capabilities, + }), + } + } + + /// Returns the currently published runtime generation. + pub fn snapshot(&self) -> SelectedCapabilityActivationSnapshot { + self.state + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Publishes `selected_capabilities` atomically. + /// + /// Returns whether the published generation advanced. + pub fn publish(&self, selected_capabilities: SelectedCapabilitySnapshot) -> bool { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + if selected_capabilities.generation() <= state.generation() { + return false; + } + *state = SelectedCapabilityActivationSnapshot { + selected_capabilities, + }; + true + } +} + /// Thread-owned, nonblocking selected-capability resolution state. /// /// Each selected root resolves once against its original environment. Callers @@ -246,6 +302,23 @@ impl SelectedCapabilityBindings { Self { inner } } + /// Returns the all-pending generation captured before background work runs. + pub fn initial_snapshot(&self) -> SelectedCapabilitySnapshot { + SelectedCapabilitySnapshot { + generation: 0, + entries: self + .inner + .roots + .iter() + .cloned() + .map(|selected_root| SelectedCapabilityBindingSnapshot { + selected_root, + status: SelectedCapabilityBindingStatus::Pending, + }) + .collect(), + } + } + /// Captures current states without waiting for pending executors. pub fn snapshot(&self) -> SelectedCapabilitySnapshot { let state = self.inner.state(); diff --git a/codex-rs/core-plugins/src/selected_capabilities_tests.rs b/codex-rs/core-plugins/src/selected_capabilities_tests.rs index b671713a7b..ee74dadd09 100644 --- a/codex-rs/core-plugins/src/selected_capabilities_tests.rs +++ b/codex-rs/core-plugins/src/selected_capabilities_tests.rs @@ -42,6 +42,7 @@ async fn snapshots_preserve_root_order_and_advance_on_terminal_transitions() { ); let initial = bindings.snapshot(); + let activation = SelectedCapabilityActivation::new(initial.clone()); assert_eq!(initial.generation(), 0); assert_eq!( initial @@ -88,6 +89,9 @@ async fn snapshots_preserve_root_order_and_advance_on_terminal_transitions() { &second.file_system(), &environment.get_filesystem() )); + assert!(activation.publish(after_second.clone())); + assert_eq!(activation.snapshot().generation(), 1); + assert!(!activation.publish(initial)); assert!( first_tx diff --git a/codex-rs/ext/connectors/Cargo.toml b/codex-rs/ext/connectors/Cargo.toml index b639d48f29..1caa61d2dc 100644 --- a/codex-rs/ext/connectors/Cargo.toml +++ b/codex-rs/ext/connectors/Cargo.toml @@ -22,4 +22,11 @@ codex-protocol = { workspace = true } codex-utils-path-uri = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +tokio = { workspace = true, features = ["sync"] } tracing = { workspace = true } + +[dev-dependencies] +codex-exec-server = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] } diff --git a/codex-rs/ext/connectors/src/lib.rs b/codex-rs/ext/connectors/src/lib.rs index 9b1ee41988..0ccd3736d6 100644 --- a/codex-rs/ext/connectors/src/lib.rs +++ b/codex-rs/ext/connectors/src/lib.rs @@ -11,7 +11,7 @@ pub use selected::SelectedExecutorConnectorProvider; pub fn install_selected_executor_connectors( builder: &mut codex_extension_api::ExtensionRegistryBuilder, ) { - builder.thread_extension_init_contributor(std::sync::Arc::new( - SelectedExecutorConnectorProvider::new(), - )); + let provider = std::sync::Arc::new(SelectedExecutorConnectorProvider::new()); + builder.thread_extension_init_contributor(provider.clone()); + builder.runtime_snapshot_contributor(provider); } diff --git a/codex-rs/ext/connectors/src/selected.rs b/codex-rs/ext/connectors/src/selected.rs index 7bd20b13b4..9f15c652eb 100644 --- a/codex-rs/ext/connectors/src/selected.rs +++ b/codex-rs/ext/connectors/src/selected.rs @@ -1,14 +1,40 @@ use codex_connectors::ConnectorSnapshot; +use codex_connectors::ConnectorSnapshotState; use codex_connectors::PluginConnectorSource; +use codex_core_plugins::SelectedCapabilityActivation; use codex_core_plugins::SelectedCapabilityBindings; +use codex_core_plugins::SelectedCapabilitySnapshot; use codex_extension_api::ExtensionDataInit; use codex_extension_api::ExtensionFuture; +use codex_extension_api::RuntimeSnapshotContributor; use codex_extension_api::ThreadExtensionInitContributor; +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::PoisonError; +use tokio::sync::OnceCell; use crate::ExecutorPluginConnectorProvider; +#[derive(Default)] +struct SelectedExecutorConnectorCache { + sources: Mutex>>>>, +} + +impl SelectedExecutorConnectorCache { + fn source(&self, selection_order: usize) -> Arc>> { + Arc::clone( + self.sources + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(selection_order) + .or_default(), + ) + } +} + /// Resolves connector declarations from thread-selected executor plugins. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct SelectedExecutorConnectorProvider { connector_provider: ExecutorPluginConnectorProvider, } @@ -16,54 +42,147 @@ pub struct SelectedExecutorConnectorProvider { impl SelectedExecutorConnectorProvider { /// Creates a provider for already-bound selected capability roots. pub fn new() -> Self { - Self { - connector_provider: ExecutorPluginConnectorProvider, - } + Self::default() } - /// Resolves one immutable connector snapshot in selected-root order. + /// Resolves one immutable connector snapshot after all selected roots settle. + /// + /// Thread initialization uses generation snapshots instead so a pending executor does not + /// block session startup. This method retains the explicit wait-for-all behavior for callers + /// that request a complete snapshot directly. pub async fn snapshot_for_bindings( &self, bindings: &SelectedCapabilityBindings, ) -> ConnectorSnapshot { - let mut sources = Vec::new(); - let snapshot = bindings.resolve_all().await; + self.snapshot_for_selected_capabilities( + &bindings.resolve_all().await, + &SelectedExecutorConnectorCache::default(), + ) + .await + } - for selected_root in snapshot.ready() { - let Some(plugin) = selected_root.plugin() else { - continue; - }; - match self.connector_provider.load(selected_root).await { - Ok(declarations) => sources.push(PluginConnectorSource::new( - plugin.selected_root_id(), - plugin.manifest().display_name(), - declarations, - )), - Err(err) => { - tracing::warn!( - selected_root = selected_root.selected_root().id, - error = %err, - "failed to load selected executor plugin connectors" - ); - } - } + /// Resolves one immutable connector snapshot in selected-root order. + async fn snapshot_for_selected_capabilities( + &self, + selected_capabilities: &SelectedCapabilitySnapshot, + cache: &SelectedExecutorConnectorCache, + ) -> ConnectorSnapshot { + for selected_root in selected_capabilities.ready() { + let selection_order = selected_root.selection_order(); + cache + .source(selection_order) + .get_or_init(|| async { + let plugin = selected_root.plugin()?; + match self.connector_provider.load(selected_root).await { + Ok(declarations) => Some(PluginConnectorSource::new( + plugin.selected_root_id(), + plugin.manifest().display_name(), + declarations, + )), + Err(err) => { + tracing::warn!( + selected_root = selected_root.selected_root().id, + error = %err, + "failed to load selected executor plugin connectors" + ); + None + } + } + }) + .await; } - ConnectorSnapshot::from_plugin_sources(sources) + ConnectorSnapshot::from_plugin_sources(selected_capabilities.ready().filter_map( + |selected_root| { + cache + .source(selected_root.selection_order()) + .get() + .cloned() + .flatten() + }, + )) } } impl ThreadExtensionInitContributor for SelectedExecutorConnectorProvider { fn initialize<'a>(&'a self, thread_init: &'a mut ExtensionDataInit) -> ExtensionFuture<'a, ()> { Box::pin(async move { - if thread_init.get::().is_some() { + if let Some(snapshot) = thread_init.get::() { + let snapshot = snapshot.as_ref().clone(); + match thread_init.get::() { + Some(state) => state.publish(snapshot), + None => { + thread_init.insert(ConnectorSnapshotState::new(snapshot)); + } + } return; } - let Some(bindings) = thread_init.get::() else { + + let Some(activation) = thread_init.get::() else { + let Some(bindings) = thread_init.get::() else { + return; + }; + let snapshot = self.snapshot_for_bindings(bindings.as_ref()).await; + thread_init.insert(snapshot.clone()); + thread_init.insert(ConnectorSnapshotState::new(snapshot)); return; }; - let snapshot = self.snapshot_for_bindings(bindings.as_ref()).await; - thread_init.insert(snapshot); + if thread_init.get::().is_none() { + thread_init.insert(ConnectorSnapshotState::default()); + } + let Some(connector_state) = thread_init.get::() else { + return; + }; + if thread_init + .get::() + .is_none() + { + thread_init.insert(SelectedExecutorConnectorCache::default()); + } + let Some(cache) = thread_init.get::() else { + return; + }; + let selected_capabilities = activation.snapshot().selected_capabilities().clone(); + let connector_snapshot = self + .snapshot_for_selected_capabilities(&selected_capabilities, cache.as_ref()) + .await; + connector_state.publish(connector_snapshot); }) } } + +impl RuntimeSnapshotContributor for SelectedExecutorConnectorProvider { + fn prepare<'a>(&'a self, candidate: &'a mut ExtensionDataInit) -> ExtensionFuture<'a, ()> { + Box::pin(async move { + let Some(activation) = candidate.get::() else { + return; + }; + candidate.insert(ConnectorSnapshotState::default()); + let Some(connector_state) = candidate.get::() else { + return; + }; + if let Some(snapshot) = candidate.get::() { + connector_state.publish(snapshot.as_ref().clone()); + return; + } + let Some(cache) = candidate.get::() else { + return; + }; + let selected_capabilities = activation.snapshot().selected_capabilities().clone(); + let connector_snapshot = self + .snapshot_for_selected_capabilities(&selected_capabilities, cache.as_ref()) + .await; + connector_state.publish(connector_snapshot); + }) + } + + fn commit(&self, candidate: &ExtensionDataInit, active: &ExtensionDataInit) { + let Some(candidate_state) = candidate.get::() else { + return; + }; + let Some(active_state) = active.get::() else { + return; + }; + active_state.publish(candidate_state.snapshot()); + } +} diff --git a/codex-rs/ext/connectors/tests/selected.rs b/codex-rs/ext/connectors/tests/selected.rs new file mode 100644 index 0000000000..173abdaf03 --- /dev/null +++ b/codex-rs/ext/connectors/tests/selected.rs @@ -0,0 +1,139 @@ +use codex_connectors::ConnectorSnapshot; +use codex_connectors::ConnectorSnapshotState; +use codex_connectors::PluginConnectorSource; +use codex_core_plugins::SelectedCapabilityBindings; +use codex_exec_server::EnvironmentManager; +use codex_exec_server::LOCAL_ENVIRONMENT_ID; +use codex_exec_server::REMOTE_ENVIRONMENT_ID; +use codex_extension_api::ExtensionDataInit; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_plugin::AppConnectorId; +use codex_plugin::AppDeclaration; +use codex_protocol::capabilities::CapabilityRootLocation; +use codex_protocol::capabilities::SelectedCapabilityRoot; +use codex_utils_path_uri::PathUri; +use pretty_assertions::assert_eq; +use std::sync::Arc; +use std::time::Duration; +use tokio::net::TcpListener; +use tokio::time::timeout; + +type TestResult = Result<(), Box>; + +#[tokio::test] +async fn bindings_only_initialization_preserves_legacy_snapshot_output() -> TestResult { + let plugin_root = tempfile::tempdir()?; + std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?; + std::fs::write( + plugin_root.path().join(".codex-plugin/plugin.json"), + r#"{"name":"calendar","apps":"./.app.json","interface":{"displayName":"Calendar"}}"#, + )?; + std::fs::write( + plugin_root.path().join(".app.json"), + r#"{"apps":{"calendar":{"id":"calendar"}}}"#, + )?; + let bindings = SelectedCapabilityBindings::new( + vec![SelectedCapabilityRoot { + id: "calendar@1".to_string(), + location: CapabilityRootLocation::Environment { + environment_id: LOCAL_ENVIRONMENT_ID.to_string(), + path: PathUri::from_host_native_path(plugin_root.path())?, + }, + }], + Arc::new(EnvironmentManager::default_for_tests()), + ); + let mut builder = ExtensionRegistryBuilder::<()>::new(); + codex_connectors_extension::install_selected_executor_connectors(&mut builder); + let registry = builder.build(); + let mut thread_init = ExtensionDataInit::new(); + thread_init.insert(bindings); + + registry.initialize_thread_data(&mut thread_init).await; + + let expected = ConnectorSnapshot::from_plugin_sources([PluginConnectorSource::new( + "calendar@1", + "Calendar", + [AppDeclaration { + name: "calendar".to_string(), + connector_id: AppConnectorId("calendar".to_string()), + category: None, + }], + )]); + assert_eq!( + thread_init + .get::() + .expect("legacy snapshot") + .as_ref(), + &expected + ); + let state = thread_init + .get::() + .expect("connector state"); + assert_eq!(state.snapshot(), expected); + + let mut candidate = thread_init.clone(); + registry.prepare_runtime_snapshot(&mut candidate).await; + registry.commit_runtime_snapshot(&candidate, &thread_init); + assert_eq!(state.snapshot(), expected); + + Ok(()) +} + +#[tokio::test] +async fn explicit_snapshot_initialization_does_not_wait_for_pending_bindings() -> TestResult { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let environment_manager = Arc::new( + EnvironmentManager::create_for_tests( + Some(format!("ws://{}", listener.local_addr()?)), + /*local_runtime_paths*/ None, + ) + .await, + ); + let bindings = SelectedCapabilityBindings::new( + vec![SelectedCapabilityRoot { + id: "pending@1".to_string(), + location: CapabilityRootLocation::Environment { + environment_id: REMOTE_ENVIRONMENT_ID.to_string(), + path: PathUri::parse("file:///plugins/pending")?, + }, + }], + environment_manager, + ); + assert!(!bindings.snapshot().is_terminal()); + let expected = + ConnectorSnapshot::from_plugin_sources([PluginConnectorSource::from_connector_ids( + "explicit@1", + "Explicit", + [AppConnectorId("explicit".to_string())], + )]); + let mut builder = ExtensionRegistryBuilder::<()>::new(); + codex_connectors_extension::install_selected_executor_connectors(&mut builder); + let registry = builder.build(); + let mut thread_init = ExtensionDataInit::new(); + thread_init.insert(bindings); + thread_init.insert(expected.clone()); + + timeout( + Duration::from_millis(100), + registry.initialize_thread_data(&mut thread_init), + ) + .await + .expect("explicit snapshot should bypass pending bindings"); + + assert_eq!( + thread_init + .get::() + .expect("explicit snapshot") + .as_ref(), + &expected + ); + assert_eq!( + thread_init + .get::() + .expect("connector state") + .snapshot(), + expected + ); + + Ok(()) +} diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index f23a393deb..9c9a992637 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -54,6 +54,19 @@ pub trait ThreadExtensionInitContributor: Send + Sync { fn initialize<'a>(&'a self, thread_init: &'a mut ExtensionDataInit) -> ExtensionFuture<'a, ()>; } +/// Extension contribution that prepares dynamic thread state before a host +/// captures a runtime snapshot. +/// +/// Implementations derive coherent immutable views inside a host-owned +/// candidate. The host decides whether and when to publish that candidate. +pub trait RuntimeSnapshotContributor: Send + Sync { + /// Projects extension-owned state without waiting for unrelated pending work. + fn prepare<'a>(&'a self, candidate: &'a mut ExtensionDataInit) -> ExtensionFuture<'a, ()>; + + /// Publishes prepared state synchronously after the host accepts the candidate. + fn commit(&self, candidate: &ExtensionDataInit, active: &ExtensionDataInit); +} + /// Extension contribution that resolves runtime MCP servers from host config. /// /// Contributors run in registration order. Later contributions for the same diff --git a/codex-rs/ext/extension-api/src/lib.rs b/codex-rs/ext/extension-api/src/lib.rs index 9e2aa82133..c42623919b 100644 --- a/codex-rs/ext/extension-api/src/lib.rs +++ b/codex-rs/ext/extension-api/src/lib.rs @@ -40,6 +40,7 @@ pub use contributors::McpServerContributionContext; pub use contributors::McpServerContributor; pub use contributors::PromptFragment; pub use contributors::PromptSlot; +pub use contributors::RuntimeSnapshotContributor; pub use contributors::ThreadExtensionInitContributor; pub use contributors::ThreadIdleInput; pub use contributors::ThreadLifecycleContributor; diff --git a/codex-rs/ext/extension-api/src/registry.rs b/codex-rs/ext/extension-api/src/registry.rs index 1f4575ec2b..1a015942d2 100644 --- a/codex-rs/ext/extension-api/src/registry.rs +++ b/codex-rs/ext/extension-api/src/registry.rs @@ -9,6 +9,7 @@ use crate::ExtensionData; use crate::ExtensionEventSink; use crate::McpServerContributor; use crate::NoopExtensionEventSink; +use crate::RuntimeSnapshotContributor; use crate::ThreadExtensionInitContributor; use crate::ThreadLifecycleContributor; use crate::TokenUsageContributor; @@ -23,6 +24,7 @@ pub struct ExtensionRegistryBuilder { event_sink: Arc, thread_lifecycle_contributors: Vec>>, thread_init_contributors: Vec>, + runtime_snapshot_contributors: Vec>, turn_lifecycle_contributors: Vec>, config_contributors: Vec>>, token_usage_contributors: Vec>, @@ -41,6 +43,7 @@ impl Default for ExtensionRegistryBuilder { event_sink: Arc::new(NoopExtensionEventSink), thread_lifecycle_contributors: Vec::new(), thread_init_contributors: Vec::new(), + runtime_snapshot_contributors: Vec::new(), turn_lifecycle_contributors: Vec::new(), config_contributors: Vec::new(), token_usage_contributors: Vec::new(), @@ -95,6 +98,14 @@ impl ExtensionRegistryBuilder { self.thread_init_contributors.push(contributor); } + /// Registers one dynamic runtime-snapshot contributor. + pub fn runtime_snapshot_contributor( + &mut self, + contributor: Arc, + ) { + self.runtime_snapshot_contributors.push(contributor); + } + /// Registers one turn-lifecycle contributor. pub fn turn_lifecycle_contributor(&mut self, contributor: Arc) { self.turn_lifecycle_contributors.push(contributor); @@ -146,6 +157,7 @@ impl ExtensionRegistryBuilder { event_sink: self.event_sink, thread_lifecycle_contributors: self.thread_lifecycle_contributors, thread_init_contributors: self.thread_init_contributors, + runtime_snapshot_contributors: self.runtime_snapshot_contributors, turn_lifecycle_contributors: self.turn_lifecycle_contributors, config_contributors: self.config_contributors, token_usage_contributors: self.token_usage_contributors, @@ -165,6 +177,7 @@ pub struct ExtensionRegistry { event_sink: Arc, thread_lifecycle_contributors: Vec>>, thread_init_contributors: Vec>, + runtime_snapshot_contributors: Vec>, turn_lifecycle_contributors: Vec>, config_contributors: Vec>>, token_usage_contributors: Vec>, @@ -195,6 +208,24 @@ impl ExtensionRegistry { } } + /// Prepares dynamic extension state for one coherent runtime snapshot. + pub async fn prepare_runtime_snapshot(&self, candidate: &mut crate::ExtensionDataInit) { + for contributor in &self.runtime_snapshot_contributors { + contributor.prepare(candidate).await; + } + } + + /// Publishes prepared extension state after the host accepts a runtime snapshot. + pub fn commit_runtime_snapshot( + &self, + candidate: &crate::ExtensionDataInit, + active: &crate::ExtensionDataInit, + ) { + for contributor in &self.runtime_snapshot_contributors { + contributor.commit(candidate, active); + } + } + /// Returns the registered turn-lifecycle contributors. pub fn turn_lifecycle_contributors(&self) -> &[Arc] { &self.turn_lifecycle_contributors diff --git a/codex-rs/ext/mcp/Cargo.toml b/codex-rs/ext/mcp/Cargo.toml index b98c0905db..2b394e1c02 100644 --- a/codex-rs/ext/mcp/Cargo.toml +++ b/codex-rs/ext/mcp/Cargo.toml @@ -33,4 +33,4 @@ tokio = { workspace = true, features = ["sync"] } codex-login = { workspace = true } pretty_assertions = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "time"] } diff --git a/codex-rs/ext/mcp/src/executor_plugin.rs b/codex-rs/ext/mcp/src/executor_plugin.rs index 30811d867e..54475f5430 100644 --- a/codex-rs/ext/mcp/src/executor_plugin.rs +++ b/codex-rs/ext/mcp/src/executor_plugin.rs @@ -1,4 +1,5 @@ use codex_core::config::Config; +use codex_core_plugins::SelectedCapabilityActivation; use codex_core_plugins::SelectedCapabilityBindings; use codex_extension_api::ExtensionDataInit; use codex_extension_api::ExtensionFuture; @@ -7,6 +8,9 @@ use codex_extension_api::McpServerContributionContext; use codex_extension_api::McpServerContributor; use codex_extension_api::ThreadExtensionInitContributor; use std::collections::HashMap; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::PoisonError; use tokio::sync::OnceCell; use self::provider::ExecutorPluginMcpProvider; @@ -27,7 +31,19 @@ struct SelectedPluginMcpServers { #[derive(Default)] pub(crate) struct SelectedExecutorPluginMcpState { - snapshot: OnceCell>, + plugins: Mutex>>>>, +} + +impl SelectedExecutorPluginMcpState { + fn plugin(&self, selection_order: usize) -> Arc>> { + Arc::clone( + self.plugins + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(selection_order) + .or_default(), + ) + } } pub(crate) fn seed_thread_state(thread_init: &mut ExtensionDataInit) { @@ -39,7 +55,8 @@ pub(crate) struct SelectedExecutorPluginMcpInitializer; impl ThreadExtensionInitContributor for SelectedExecutorPluginMcpInitializer { fn initialize<'a>(&'a self, thread_init: &'a mut ExtensionDataInit) -> ExtensionFuture<'a, ()> { Box::pin(async move { - if thread_init.get::().is_some() + if (thread_init.get::().is_some() + || thread_init.get::().is_some()) && thread_init .get::() .is_none() @@ -61,35 +78,47 @@ impl SelectedExecutorPluginMcpContributor { } } - async fn resolve_snapshot( + async fn resolve_selected_root( &self, - bindings: &SelectedCapabilityBindings, - ) -> Vec { - let mut snapshot = Vec::new(); - let bindings = bindings.resolve_all().await; - - for selected_root in bindings.ready() { - let Some(plugin) = selected_root.plugin() else { - continue; - }; - match self.mcp_provider.load(selected_root).await { - Ok(servers) => snapshot.push(SelectedPluginMcpServers { - plugin_id: plugin.selected_root_id().to_string(), - plugin_display_name: plugin.manifest().display_name().to_string(), - selection_order: selected_root.selection_order(), - servers, - }), - Err(err) => { - tracing::warn!( - selected_root = selected_root.selected_root().id, - error = %err, - "failed to load selected executor plugin MCP servers" - ); - } + selected_root: &codex_core_plugins::ResolvedSelectedCapabilityRoot, + ) -> Option { + let plugin = selected_root.plugin()?; + match self.mcp_provider.load(selected_root).await { + Ok(servers) => Some(SelectedPluginMcpServers { + plugin_id: plugin.selected_root_id().to_string(), + plugin_display_name: plugin.manifest().display_name().to_string(), + selection_order: selected_root.selection_order(), + servers, + }), + Err(err) => { + tracing::warn!( + selected_root = selected_root.selected_root().id, + error = %err, + "failed to load selected executor plugin MCP servers" + ); + None } } + } - snapshot + async fn snapshot_for_selected_capabilities( + &self, + selected_capabilities: &codex_core_plugins::SelectedCapabilitySnapshot, + state: &SelectedExecutorPluginMcpState, + ) -> Vec { + let mut plugins = Vec::new(); + for selected_root in selected_capabilities.ready() { + let selection_order = selected_root.selection_order(); + let plugin = state + .plugin(selection_order) + .get_or_init(|| self.resolve_selected_root(selected_root)) + .await + .clone(); + if let Some(plugin) = plugin { + plugins.push(plugin); + } + } + plugins } } @@ -106,20 +135,25 @@ impl McpServerContributor for SelectedExecutorPluginMcpContributor { let Some(thread_init) = context.thread_init() else { return Vec::new(); }; - let Some(bindings) = thread_init.get::() else { - return Vec::new(); - }; let Some(state) = thread_init.get::() else { tracing::warn!("selected executor plugin MCP state was not initialized"); return Vec::new(); }; - let snapshot = state - .snapshot - .get_or_init(|| self.resolve_snapshot(bindings.as_ref())) + let selected_capabilities = match thread_init.get::() { + Some(activation) => activation.snapshot().selected_capabilities().clone(), + None => { + let Some(bindings) = thread_init.get::() else { + return Vec::new(); + }; + bindings.resolve_all().await + } + }; + let snapshot = self + .snapshot_for_selected_capabilities(&selected_capabilities, state.as_ref()) .await; let mut contributions = Vec::new(); - for plugin in snapshot { + for plugin in &snapshot { let mut servers = plugin.servers.iter().cloned().collect::>(); context .config() diff --git a/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs b/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs index 5d5bd55aaf..98951c4b18 100644 --- a/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs +++ b/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs @@ -4,6 +4,7 @@ use codex_core::config::ConfigBuilder; use codex_core_plugins::SelectedCapabilityBindings; use codex_exec_server::EnvironmentManager; use codex_exec_server::LOCAL_ENVIRONMENT_ID; +use codex_exec_server::REMOTE_ENVIRONMENT_ID; use codex_extension_api::ExtensionDataInit; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::McpServerContribution; @@ -13,6 +14,9 @@ use codex_protocol::capabilities::SelectedCapabilityRoot; use codex_utils_path_uri::PathUri; use pretty_assertions::assert_eq; use std::sync::Arc; +use std::time::Duration; +use tokio::net::TcpListener; +use tokio::time::timeout; type TestResult = Result<(), Box>; @@ -92,6 +96,44 @@ command = "expected-command" Ok(()) } +#[tokio::test] +async fn bindings_only_initialization_does_not_wait_for_pending_executor() -> TestResult { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let environment_manager = Arc::new( + EnvironmentManager::create_for_tests( + Some(format!("ws://{}", listener.local_addr()?)), + /*local_runtime_paths*/ None, + ) + .await, + ); + let bindings = SelectedCapabilityBindings::new( + vec![SelectedCapabilityRoot { + id: "pending-root".to_string(), + location: CapabilityRootLocation::Environment { + environment_id: REMOTE_ENVIRONMENT_ID.to_string(), + path: PathUri::parse("file:///plugins/pending")?, + }, + }], + environment_manager, + ); + assert!(!bindings.snapshot().is_terminal()); + + let mut builder = ExtensionRegistryBuilder::new(); + codex_mcp_extension::install_executor_plugins(&mut builder); + let registry = builder.build(); + let mut thread_init = ExtensionDataInit::new(); + thread_init.insert(bindings); + + timeout( + Duration::from_millis(100), + registry.initialize_thread_data(&mut thread_init), + ) + .await + .expect("bindings-only initialization should remain lazy"); + + Ok(()) +} + async fn selected_plugin_contributions( config: &Config, plugin_root: &std::path::Path, @@ -107,10 +149,11 @@ async fn selected_plugin_contributions( path: PathUri::from_host_native_path(plugin_root)?, }, }]; - thread_init.insert(SelectedCapabilityBindings::new( + let bindings = SelectedCapabilityBindings::new( selected_roots.clone(), Arc::new(EnvironmentManager::default_for_tests()), - )); + ); + thread_init.insert(bindings); thread_init.insert(selected_roots); registry.initialize_thread_data(&mut thread_init).await;