mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Prepare selected capability snapshots
This commit is contained in:
Generated
+4
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<String, Vec<String>>,
|
||||
}
|
||||
|
||||
/// Mutable holder for the connector snapshot published at a runtime boundary.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ConnectorSnapshotState {
|
||||
snapshot: Mutex<ConnectorSnapshot>,
|
||||
}
|
||||
|
||||
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<Item = PluginConnectorSource>) -> Self {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<SelectedCapabilityActivationSnapshot>,
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -11,7 +11,7 @@ pub use selected::SelectedExecutorConnectorProvider;
|
||||
pub fn install_selected_executor_connectors<C: Sync>(
|
||||
builder: &mut codex_extension_api::ExtensionRegistryBuilder<C>,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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<HashMap<usize, Arc<OnceCell<Option<PluginConnectorSource>>>>>,
|
||||
}
|
||||
|
||||
impl SelectedExecutorConnectorCache {
|
||||
fn source(&self, selection_order: usize) -> Arc<OnceCell<Option<PluginConnectorSource>>> {
|
||||
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::<ConnectorSnapshot>().is_some() {
|
||||
if let Some(snapshot) = thread_init.get::<ConnectorSnapshot>() {
|
||||
let snapshot = snapshot.as_ref().clone();
|
||||
match thread_init.get::<ConnectorSnapshotState>() {
|
||||
Some(state) => state.publish(snapshot),
|
||||
None => {
|
||||
thread_init.insert(ConnectorSnapshotState::new(snapshot));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(bindings) = thread_init.get::<SelectedCapabilityBindings>() else {
|
||||
|
||||
let Some(activation) = thread_init.get::<SelectedCapabilityActivation>() else {
|
||||
let Some(bindings) = thread_init.get::<SelectedCapabilityBindings>() 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::<ConnectorSnapshotState>().is_none() {
|
||||
thread_init.insert(ConnectorSnapshotState::default());
|
||||
}
|
||||
let Some(connector_state) = thread_init.get::<ConnectorSnapshotState>() else {
|
||||
return;
|
||||
};
|
||||
if thread_init
|
||||
.get::<SelectedExecutorConnectorCache>()
|
||||
.is_none()
|
||||
{
|
||||
thread_init.insert(SelectedExecutorConnectorCache::default());
|
||||
}
|
||||
let Some(cache) = thread_init.get::<SelectedExecutorConnectorCache>() 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::<SelectedCapabilityActivation>() else {
|
||||
return;
|
||||
};
|
||||
candidate.insert(ConnectorSnapshotState::default());
|
||||
let Some(connector_state) = candidate.get::<ConnectorSnapshotState>() else {
|
||||
return;
|
||||
};
|
||||
if let Some(snapshot) = candidate.get::<ConnectorSnapshot>() {
|
||||
connector_state.publish(snapshot.as_ref().clone());
|
||||
return;
|
||||
}
|
||||
let Some(cache) = candidate.get::<SelectedExecutorConnectorCache>() 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::<ConnectorSnapshotState>() else {
|
||||
return;
|
||||
};
|
||||
let Some(active_state) = active.get::<ConnectorSnapshotState>() else {
|
||||
return;
|
||||
};
|
||||
active_state.publish(candidate_state.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<dyn std::error::Error>>;
|
||||
|
||||
#[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::<ConnectorSnapshot>()
|
||||
.expect("legacy snapshot")
|
||||
.as_ref(),
|
||||
&expected
|
||||
);
|
||||
let state = thread_init
|
||||
.get::<ConnectorSnapshotState>()
|
||||
.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::<ConnectorSnapshot>()
|
||||
.expect("explicit snapshot")
|
||||
.as_ref(),
|
||||
&expected
|
||||
);
|
||||
assert_eq!(
|
||||
thread_init
|
||||
.get::<ConnectorSnapshotState>()
|
||||
.expect("connector state")
|
||||
.snapshot(),
|
||||
expected
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<C: Sync> {
|
||||
event_sink: Arc<dyn ExtensionEventSink>,
|
||||
thread_lifecycle_contributors: Vec<Arc<dyn ThreadLifecycleContributor<C>>>,
|
||||
thread_init_contributors: Vec<Arc<dyn ThreadExtensionInitContributor>>,
|
||||
runtime_snapshot_contributors: Vec<Arc<dyn RuntimeSnapshotContributor>>,
|
||||
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
|
||||
config_contributors: Vec<Arc<dyn ConfigContributor<C>>>,
|
||||
token_usage_contributors: Vec<Arc<dyn TokenUsageContributor>>,
|
||||
@@ -41,6 +43,7 @@ impl<C: Sync> Default for ExtensionRegistryBuilder<C> {
|
||||
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<C: Sync> ExtensionRegistryBuilder<C> {
|
||||
self.thread_init_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one dynamic runtime-snapshot contributor.
|
||||
pub fn runtime_snapshot_contributor(
|
||||
&mut self,
|
||||
contributor: Arc<dyn RuntimeSnapshotContributor>,
|
||||
) {
|
||||
self.runtime_snapshot_contributors.push(contributor);
|
||||
}
|
||||
|
||||
/// Registers one turn-lifecycle contributor.
|
||||
pub fn turn_lifecycle_contributor(&mut self, contributor: Arc<dyn TurnLifecycleContributor>) {
|
||||
self.turn_lifecycle_contributors.push(contributor);
|
||||
@@ -146,6 +157,7 @@ impl<C: Sync> ExtensionRegistryBuilder<C> {
|
||||
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<C: Sync> {
|
||||
event_sink: Arc<dyn ExtensionEventSink>,
|
||||
thread_lifecycle_contributors: Vec<Arc<dyn ThreadLifecycleContributor<C>>>,
|
||||
thread_init_contributors: Vec<Arc<dyn ThreadExtensionInitContributor>>,
|
||||
runtime_snapshot_contributors: Vec<Arc<dyn RuntimeSnapshotContributor>>,
|
||||
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
|
||||
config_contributors: Vec<Arc<dyn ConfigContributor<C>>>,
|
||||
token_usage_contributors: Vec<Arc<dyn TokenUsageContributor>>,
|
||||
@@ -195,6 +208,24 @@ impl<C: Sync> ExtensionRegistry<C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<dyn TurnLifecycleContributor>] {
|
||||
&self.turn_lifecycle_contributors
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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<Vec<SelectedPluginMcpServers>>,
|
||||
plugins: Mutex<HashMap<usize, Arc<OnceCell<Option<SelectedPluginMcpServers>>>>>,
|
||||
}
|
||||
|
||||
impl SelectedExecutorPluginMcpState {
|
||||
fn plugin(&self, selection_order: usize) -> Arc<OnceCell<Option<SelectedPluginMcpServers>>> {
|
||||
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::<SelectedCapabilityBindings>().is_some()
|
||||
if (thread_init.get::<SelectedCapabilityActivation>().is_some()
|
||||
|| thread_init.get::<SelectedCapabilityBindings>().is_some())
|
||||
&& thread_init
|
||||
.get::<SelectedExecutorPluginMcpState>()
|
||||
.is_none()
|
||||
@@ -61,35 +78,47 @@ impl SelectedExecutorPluginMcpContributor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_snapshot(
|
||||
async fn resolve_selected_root(
|
||||
&self,
|
||||
bindings: &SelectedCapabilityBindings,
|
||||
) -> Vec<SelectedPluginMcpServers> {
|
||||
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<SelectedPluginMcpServers> {
|
||||
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<SelectedPluginMcpServers> {
|
||||
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<Config> for SelectedExecutorPluginMcpContributor {
|
||||
let Some(thread_init) = context.thread_init() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(bindings) = thread_init.get::<SelectedCapabilityBindings>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(state) = thread_init.get::<SelectedExecutorPluginMcpState>() 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::<SelectedCapabilityActivation>() {
|
||||
Some(activation) => activation.snapshot().selected_capabilities().clone(),
|
||||
None => {
|
||||
let Some(bindings) = thread_init.get::<SelectedCapabilityBindings>() 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::<HashMap<_, _>>();
|
||||
context
|
||||
.config()
|
||||
|
||||
@@ -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<dyn std::error::Error>>;
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user