Merge branch 'main' of github.com:openai/codex into dev/mzeng/codex_apps_mcp_declare

# Conflicts:
#	codex-rs/Cargo.lock
#	codex-rs/codex-mcp/Cargo.toml
#	codex-rs/codex-mcp/src/connection_manager.rs
#	codex-rs/codex-mcp/src/connection_manager_tests.rs
#	codex-rs/codex-mcp/src/rmcp_client.rs
#	codex-rs/codex-mcp/src/tools.rs
#	codex-rs/core/src/connectors_tests.rs
#	codex-rs/core/src/mcp_tool_exposure_test.rs
#	codex-rs/core/src/tools/handlers/tool_search.rs
#	codex-rs/core/src/tools/spec_tests.rs
This commit is contained in:
Matthew Zeng
2026-05-12 14:48:05 -07:00
939 changed files with 47255 additions and 16342 deletions
+22 -4
View File
@@ -1196,19 +1196,37 @@ impl PluginsManager {
if !self.restriction_product_matches(plugin.policy.products.as_deref()) {
return None;
}
let installed = installed_plugins.contains(&plugin_key);
let enabled = enabled_plugins.contains(&plugin_key);
let mut interface = plugin.interface;
if installed
&& matches!(&plugin.source, MarketplacePluginSource::Git { .. })
&& let Ok(plugin_id) =
PluginId::new(plugin.name.clone(), marketplace_name.clone())
&& let Some(plugin_root) = self.store.active_plugin_root(&plugin_id)
&& let Some(manifest) = load_plugin_manifest(plugin_root.as_path())
{
let marketplace_category = interface
.as_ref()
.and_then(|interface| interface.category.clone());
interface = plugin_interface_with_marketplace_category(
manifest.interface,
marketplace_category,
);
}
Some(ConfiguredMarketplacePlugin {
// Enabled state is keyed by `<plugin>@<marketplace>`, so duplicate
// plugin entries from duplicate marketplace files intentionally
// resolve to the first discovered source.
id: plugin_key.clone(),
installed: installed_plugins.contains(&plugin_key),
enabled: enabled_plugins.contains(&plugin_key),
id: plugin_key,
installed,
enabled,
name: plugin.name,
source: plugin.source,
policy: plugin.policy,
interface: plugin.interface,
keywords: plugin.keywords,
interface,
})
})
.collect::<Vec<_>>();
+110
View File
@@ -2043,6 +2043,116 @@ enabled = false
);
}
#[tokio::test]
async fn list_marketplaces_installed_git_source_reads_metadata_from_cache_without_cloning() {
let tmp = tempfile::tempdir().unwrap();
let repo_root = tmp.path().join("repo");
let missing_remote_repo = tmp.path().join("missing-remote-plugin-repo");
let missing_remote_repo_url = url::Url::from_directory_path(&missing_remote_repo)
.unwrap()
.to_string();
fs::create_dir_all(repo_root.join(".git")).unwrap();
write_file(
&repo_root.join(".agents/plugins/marketplace.json"),
&format!(
r#"{{
"name": "debug",
"plugins": [
{{
"name": "toolkit",
"source": {{
"source": "git-subdir",
"url": "{missing_remote_repo_url}",
"path": "plugins/toolkit"
}},
"category": "Developer Tools"
}}
]
}}"#
),
);
let cached_plugin_root = tmp.path().join("plugins/cache/debug/toolkit/local");
write_file(
&cached_plugin_root.join(".codex-plugin/plugin.json"),
r##"{
"name": "toolkit",
"interface": {
"displayName": "Toolkit",
"shortDescription": "Search cached data",
"category": "Cached Category",
"brandColor": "#3B82F6",
"composerIcon": "./assets/icon.png",
"logo": "./assets/logo.png",
"screenshots": ["./assets/screenshot.png"]
}
}"##,
);
write_file(
&tmp.path().join(CONFIG_TOML_FILE),
r#"[features]
plugins = true
[plugins."toolkit@debug"]
enabled = true
"#,
);
let config = load_config(tmp.path(), &repo_root).await;
let marketplaces = PluginsManager::new(tmp.path().to_path_buf())
.list_marketplaces_for_config(&config, &[AbsolutePathBuf::try_from(repo_root).unwrap()])
.unwrap()
.marketplaces;
let marketplace = marketplaces
.into_iter()
.find(|marketplace| marketplace.name == "debug")
.expect("debug marketplace should be listed");
assert_eq!(
marketplace.plugins,
vec![ConfiguredMarketplacePlugin {
id: "toolkit@debug".to_string(),
name: "toolkit".to_string(),
source: MarketplacePluginSource::Git {
url: missing_remote_repo_url,
path: Some("plugins/toolkit".to_string()),
ref_name: None,
sha: None,
},
policy: MarketplacePluginPolicy {
installation: MarketplacePluginInstallPolicy::Available,
authentication: MarketplacePluginAuthPolicy::OnInstall,
products: None,
},
interface: Some(PluginManifestInterface {
display_name: Some("Toolkit".to_string()),
short_description: Some("Search cached data".to_string()),
category: Some("Developer Tools".to_string()),
brand_color: Some("#3B82F6".to_string()),
composer_icon: Some(
AbsolutePathBuf::try_from(cached_plugin_root.join("assets/icon.png")).unwrap(),
),
logo: Some(
AbsolutePathBuf::try_from(cached_plugin_root.join("assets/logo.png")).unwrap(),
),
screenshots: vec![
AbsolutePathBuf::try_from(cached_plugin_root.join("assets/screenshot.png"))
.unwrap(),
],
..Default::default()
}),
keywords: Vec::new(),
installed: true,
enabled: true,
}]
);
assert!(
!tmp.path()
.join("plugins/.marketplace-plugin-source-staging")
.exists()
);
}
#[tokio::test]
async fn sync_plugins_from_remote_returns_default_when_feature_disabled() {
let tmp = tempfile::tempdir().unwrap();
+105 -51
View File
@@ -32,9 +32,12 @@ pub use remote_installed_plugin_sync::sync_remote_installed_plugin_bundles_once;
pub use share::RemotePluginShareAccessPolicy;
pub use share::RemotePluginShareDiscoverability;
pub use share::RemotePluginSharePrincipal;
pub use share::RemotePluginSharePrincipalRole;
pub use share::RemotePluginSharePrincipalType;
pub use share::RemotePluginShareSaveResult;
pub use share::RemotePluginShareTarget;
pub use share::RemotePluginShareTargetRole;
pub use share::RemotePluginShareUpdateDiscoverability;
pub use share::RemotePluginShareUpdateTargetsResult;
pub use share::delete_remote_plugin_share;
pub use share::list_remote_plugin_shares;
@@ -84,6 +87,7 @@ pub struct RemoteInstalledPlugin {
#[derive(Debug, Clone, PartialEq)]
pub struct RemotePluginSummary {
pub id: String,
pub remote_plugin_id: String,
pub name: String,
pub share_context: Option<RemotePluginShareContext>,
pub installed: bool,
@@ -98,16 +102,16 @@ pub struct RemotePluginSummary {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemotePluginShareContext {
pub remote_plugin_id: String,
pub discoverability: RemotePluginShareDiscoverability,
pub share_url: Option<String>,
pub creator_account_user_id: Option<String>,
pub creator_name: Option<String>,
pub share_targets: Option<Vec<RemotePluginSharePrincipal>>,
pub share_principals: Option<Vec<RemotePluginSharePrincipal>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RemotePluginShareSummary {
pub summary: RemotePluginSummary,
pub share_url: Option<String>,
pub local_plugin_path: Option<AbsolutePathBuf>,
}
@@ -360,6 +364,8 @@ struct RemotePluginDirectoryItem {
name: String,
scope: RemotePluginScope,
#[serde(default)]
discoverability: Option<RemotePluginShareDiscoverability>,
#[serde(default)]
creator_account_user_id: Option<String>,
#[serde(default)]
creator_name: Option<String>,
@@ -374,12 +380,37 @@ struct RemotePluginDirectoryItem {
release: RemotePluginReleaseResponse,
}
fn remote_plugin_canonical_marketplace_name(
plugin: &RemotePluginDirectoryItem,
) -> Result<&'static str, RemotePluginCatalogError> {
match plugin.scope {
RemotePluginScope::Global => Ok(REMOTE_GLOBAL_MARKETPLACE_NAME),
RemotePluginScope::Workspace => match workspace_plugin_discoverability(plugin)? {
RemotePluginShareDiscoverability::Listed => Ok(REMOTE_WORKSPACE_MARKETPLACE_NAME),
RemotePluginShareDiscoverability::Unlisted
| RemotePluginShareDiscoverability::Private => {
Ok(REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME)
}
},
}
}
fn workspace_plugin_discoverability(
plugin: &RemotePluginDirectoryItem,
) -> Result<RemotePluginShareDiscoverability, RemotePluginCatalogError> {
plugin.discoverability.ok_or_else(|| {
RemotePluginCatalogError::UnexpectedResponse(format!(
"workspace plugin `{}` did not include discoverability",
plugin.id
))
})
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginDirectorySharePrincipal {
principal_type: RemotePluginSharePrincipalType,
principal_id: String,
#[serde(default)]
role: Option<String>,
role: RemotePluginSharePrincipalRole,
name: String,
}
@@ -443,7 +474,7 @@ pub async fn fetch_remote_marketplaces(
directory_plugins,
installed_plugins,
/*include_installed_only*/ true,
)
)?
}
RemoteMarketplaceSource::WorkspaceDirectory => {
let scope = RemotePluginScope::Workspace;
@@ -455,7 +486,7 @@ pub async fn fetch_remote_marketplaces(
directory_plugins,
workspace_installed_plugins.clone().unwrap_or_default(),
/*include_installed_only*/ false,
)
)?
}
RemoteMarketplaceSource::SharedWithMe => build_remote_marketplace(
REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME,
@@ -463,7 +494,7 @@ pub async fn fetch_remote_marketplaces(
fetch_shared_workspace_plugins(config, auth).await?,
workspace_installed_plugins.clone().unwrap_or_default(),
/*include_installed_only*/ false,
),
)?,
};
if let Some(marketplace) = marketplace {
marketplaces.push(marketplace);
@@ -479,7 +510,7 @@ fn build_remote_marketplace(
directory_plugins: Vec<RemotePluginDirectoryItem>,
installed_plugins: Vec<RemotePluginInstalledItem>,
include_installed_only: bool,
) -> Option<RemoteMarketplace> {
) -> Result<Option<RemoteMarketplace>, RemotePluginCatalogError> {
let directory_plugins = directory_plugins
.into_iter()
.map(|plugin| (plugin.id.clone(), plugin))
@@ -499,7 +530,7 @@ fn build_remote_marketplace(
.cloned()
.collect::<BTreeSet<_>>();
if plugin_ids.is_empty() {
return None;
return Ok(None);
}
let mut plugins = plugin_ids
@@ -509,9 +540,10 @@ fn build_remote_marketplace(
let installed_plugin = installed_plugins.get(&plugin_id);
directory_plugin
.or_else(|| installed_plugin.map(|plugin| &plugin.plugin))
.map(|plugin| build_remote_plugin_summary(plugin, installed_plugin))
.map(|plugin| (plugin, installed_plugin))
})
.collect::<Vec<_>>();
.map(|(plugin, installed_plugin)| build_remote_plugin_summary(plugin, installed_plugin))
.collect::<Result<Vec<_>, _>>()?;
plugins.sort_by(|left, right| {
remote_plugin_display_name(left)
.to_ascii_lowercase()
@@ -519,11 +551,11 @@ fn build_remote_marketplace(
.then_with(|| remote_plugin_display_name(left).cmp(remote_plugin_display_name(right)))
.then_with(|| left.id.cmp(&right.id))
});
Some(RemoteMarketplace {
Ok(Some(RemoteMarketplace {
name: name.to_string(),
display_name: display_name.to_string(),
plugins,
})
}))
}
pub async fn fetch_remote_installed_plugins(
@@ -545,12 +577,9 @@ pub async fn fetch_remote_installed_plugins(
let (global, workspace) = tokio::try_join!(global, workspace)?;
let mut installed_plugins = [global, workspace]
.into_iter()
.flat_map(|(scope, plugins)| {
plugins
.into_iter()
.map(move |plugin| remote_installed_plugin_to_info(scope, &plugin))
})
.collect::<Vec<_>>();
.flat_map(|(_scope, plugins)| plugins)
.map(|plugin| remote_installed_plugin_to_info(&plugin))
.collect::<Result<Vec<_>, _>>()?;
installed_plugins.sort_by(|left, right| {
left.marketplace_name
.cmp(&right.marketplace_name)
@@ -575,6 +604,19 @@ pub async fn fetch_remote_plugin_detail(
.await
}
pub async fn fetch_remote_plugin_share_context(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
plugin_id: &str,
) -> Result<Option<RemotePluginShareContext>, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let plugin = fetch_plugin_detail(
config, auth, plugin_id, /*include_download_urls*/ false,
)
.await?;
remote_plugin_share_context(&plugin)
}
pub async fn fetch_remote_plugin_detail_with_download_urls(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
@@ -637,7 +679,7 @@ async fn fetch_remote_plugin_detail_with_download_url_option(
let auth = ensure_chatgpt_auth(auth)?;
let plugin = fetch_plugin_detail(config, auth, plugin_id, include_download_urls).await?;
let scope = plugin.scope;
let marketplace_name = scope.marketplace_name().to_string();
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
// Remote plugin IDs uniquely identify remote plugins, so the caller-provided
// marketplace name is not validated here. The backend detail response is the
// source of truth for the plugin's actual scope/marketplace.
@@ -686,7 +728,7 @@ async fn build_remote_plugin_detail(
Ok(RemotePluginDetail {
marketplace_name,
marketplace_display_name: scope.marketplace_display_name().to_string(),
summary: build_remote_plugin_summary(&plugin, installed_plugin.as_ref()),
summary: build_remote_plugin_summary(&plugin, installed_plugin.as_ref())?,
description: non_empty_string(Some(&plugin.release.description)),
release_version: plugin.release.version,
bundle_download_url: plugin.release.bundle_download_url,
@@ -738,7 +780,7 @@ pub async fn uninstall_remote_plugin(
config, auth, plugin_id, /*include_download_urls*/ false,
)
.await?;
let marketplace_name = plugin.scope.marketplace_name().to_string();
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
let plugin_name = plugin.name;
let base_url = config.chatgpt_base_url.trim_end_matches('/');
@@ -822,11 +864,20 @@ fn remove_remote_plugin_cache(
fn build_remote_plugin_summary(
plugin: &RemotePluginDirectoryItem,
installed_plugin: Option<&RemotePluginInstalledItem>,
) -> RemotePluginSummary {
RemotePluginSummary {
id: plugin.id.clone(),
) -> Result<RemotePluginSummary, RemotePluginCatalogError> {
let marketplace_name = remote_plugin_canonical_marketplace_name(plugin)?;
let plugin_id =
PluginId::new(plugin.name.clone(), marketplace_name.to_string()).map_err(|err| {
RemotePluginCatalogError::UnexpectedResponse(format!(
"invalid remote plugin config id for `{}` in `{marketplace_name}`: {err}",
plugin.name
))
})?;
Ok(RemotePluginSummary {
id: plugin_id.as_key(),
remote_plugin_id: plugin.id.clone(),
name: plugin.name.clone(),
share_context: remote_plugin_share_context(plugin),
share_context: remote_plugin_share_context(plugin)?,
installed: installed_plugin.is_some(),
enabled: installed_plugin.is_some_and(|plugin| plugin.enabled),
install_policy: plugin.installation_policy,
@@ -834,48 +885,51 @@ fn build_remote_plugin_summary(
availability: plugin.availability,
interface: remote_plugin_interface_to_info(plugin),
keywords: plugin.release.keywords.clone(),
}
})
}
fn remote_plugin_share_context(
plugin: &RemotePluginDirectoryItem,
) -> Option<RemotePluginShareContext> {
) -> Result<Option<RemotePluginShareContext>, RemotePluginCatalogError> {
match plugin.scope {
RemotePluginScope::Global => None,
RemotePluginScope::Workspace => Some(RemotePluginShareContext {
remote_plugin_id: plugin.id.clone(),
share_url: plugin.share_url.clone(),
creator_account_user_id: plugin.creator_account_user_id.clone(),
creator_name: plugin.creator_name.clone(),
share_targets: plugin.share_principals.as_ref().map(|principals| {
principals
.iter()
.filter(|principal| principal.role.as_deref() == Some("reader"))
.map(|principal| RemotePluginSharePrincipal {
principal_type: principal.principal_type,
principal_id: principal.principal_id.clone(),
name: principal.name.clone(),
})
.collect()
}),
}),
RemotePluginScope::Global => Ok(None),
RemotePluginScope::Workspace => {
let discoverability = workspace_plugin_discoverability(plugin)?;
Ok(Some(RemotePluginShareContext {
remote_plugin_id: plugin.id.clone(),
discoverability,
share_url: plugin.share_url.clone(),
creator_account_user_id: plugin.creator_account_user_id.clone(),
creator_name: plugin.creator_name.clone(),
share_principals: plugin.share_principals.as_ref().map(|share_principals| {
share_principals
.iter()
.map(|principal| RemotePluginSharePrincipal {
principal_type: principal.principal_type,
principal_id: principal.principal_id.clone(),
role: principal.role,
name: principal.name.clone(),
})
.collect()
}),
}))
}
}
}
fn remote_installed_plugin_to_info(
scope: RemotePluginScope,
installed_plugin: &RemotePluginInstalledItem,
) -> RemoteInstalledPlugin {
) -> Result<RemoteInstalledPlugin, RemotePluginCatalogError> {
let plugin = &installed_plugin.plugin;
// Remote per-skill disabled state (`disabled_skill_names`) is intentionally
// not projected into skills/list yet; local skills.config remains the
// supported source for skill enablement.
RemoteInstalledPlugin {
marketplace_name: scope.marketplace_name().to_string(),
Ok(RemoteInstalledPlugin {
marketplace_name: remote_plugin_canonical_marketplace_name(plugin)?.to_string(),
id: plugin.id.clone(),
name: plugin.name.clone(),
enabled: installed_plugin.enabled,
}
})
}
fn remote_plugin_interface_to_info(plugin: &RemotePluginDirectoryItem) -> Option<PluginInterface> {
@@ -1,10 +1,12 @@
use super::REMOTE_GLOBAL_MARKETPLACE_NAME;
use super::REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME;
use super::REMOTE_WORKSPACE_MARKETPLACE_NAME;
use super::RemotePluginCatalogError;
use super::RemotePluginScope;
use super::RemotePluginServiceConfig;
use super::ensure_chatgpt_auth;
use super::fetch_installed_plugins_for_scope_with_download_url;
use super::remote_plugin_canonical_marketplace_name;
use crate::store::PLUGINS_CACHE_DIR;
use crate::store::PluginStore;
use crate::store::PluginStoreError;
@@ -150,14 +152,18 @@ pub async fn sync_remote_installed_plugin_bundles_once(
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
(
REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
]);
let mut installed_plugin_ids = BTreeSet::new();
let mut failed_remote_plugin_ids = BTreeSet::new();
for (scope, installed_plugins) in [global, workspace] {
let marketplace_name = scope.marketplace_name().to_string();
for (_scope, installed_plugins) in [global, workspace] {
for installed_plugin in installed_plugins {
let plugin = installed_plugin.plugin;
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
installed_plugin_names_by_marketplace
.entry(marketplace_name.clone())
.or_default()
@@ -292,6 +298,7 @@ fn remove_stale_remote_plugin_caches(
for marketplace_name in [
REMOTE_GLOBAL_MARKETPLACE_NAME,
REMOTE_WORKSPACE_MARKETPLACE_NAME,
REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME,
] {
let marketplace_root = codex_home.join(PLUGINS_CACHE_DIR).join(marketplace_name);
if !marketplace_root.exists() {
@@ -449,6 +456,10 @@ mod tests {
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
(
REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
]);
let guard = mark_remote_plugin_cache_mutation_in_flight(
@@ -487,4 +498,42 @@ mod tests {
assert_eq!(removed, vec!["linear@chatgpt-global".to_string()]);
assert!(!cached_manifest.exists());
}
#[test]
fn stale_remote_plugin_cleanup_removes_shared_with_me_cache() {
let codex_home = tempfile::tempdir().expect("create codex home");
let cached_manifest = codex_home
.path()
.join(PLUGINS_CACHE_DIR)
.join(REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME)
.join("private-plugin")
.join("1.2.3")
.join(".codex-plugin")
.join("plugin.json");
std::fs::create_dir_all(cached_manifest.parent().expect("manifest parent"))
.expect("create cached plugin manifest parent");
std::fs::write(&cached_manifest, r#"{"name":"private-plugin"}"#)
.expect("write cached plugin manifest");
let installed_plugin_names_by_marketplace =
BTreeMap::<String, BTreeSet<String>>::from_iter([
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
(
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
(
REMOTE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
BTreeSet::new(),
),
]);
let removed = remove_stale_remote_plugin_caches(
codex_home.path(),
&installed_plugin_names_by_marketplace,
)
.expect("cleanup shared-with-me cache");
assert_eq!(removed, vec!["private-plugin@shared-with-me".to_string()]);
assert!(!cached_manifest.exists());
}
}
+115 -20
View File
@@ -32,7 +32,7 @@ pub struct RemotePluginShareAccessPolicy {
pub share_targets: Option<Vec<RemotePluginShareTarget>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RemotePluginShareDiscoverability {
Listed,
@@ -40,6 +40,13 @@ pub enum RemotePluginShareDiscoverability {
Private,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RemotePluginShareUpdateDiscoverability {
Unlisted,
Private,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RemotePluginSharePrincipalType {
@@ -52,18 +59,36 @@ pub enum RemotePluginSharePrincipalType {
pub struct RemotePluginShareTarget {
pub principal_type: RemotePluginSharePrincipalType,
pub principal_id: String,
pub role: RemotePluginShareTargetRole,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct RemotePluginSharePrincipal {
pub principal_type: RemotePluginSharePrincipalType,
pub principal_id: String,
pub role: RemotePluginSharePrincipalRole,
pub name: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RemotePluginShareTargetRole {
Reader,
Editor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RemotePluginSharePrincipalRole {
Reader,
Editor,
Owner,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemotePluginShareUpdateTargetsResult {
pub principals: Vec<RemotePluginSharePrincipal>,
pub discoverability: RemotePluginShareDiscoverability,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -100,12 +125,14 @@ struct RemoteWorkspacePluginCreateResponse {
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct RemotePluginShareUpdateTargetsRequest {
discoverability: RemotePluginShareUpdateDiscoverability,
targets: Vec<RemotePluginShareTarget>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct RemotePluginShareUpdateTargetsResponse {
principals: Vec<RemotePluginSharePrincipal>,
discoverability: RemotePluginShareDiscoverability,
}
pub async fn save_remote_plugin_share(
@@ -137,6 +164,9 @@ pub async fn save_remote_plugin_share(
.etag
.ok_or(RemotePluginCatalogError::MissingUploadEtag)?;
put_workspace_plugin_upload(&upload.upload_url, archive_bytes).await?;
let share_targets = access_policy.share_targets;
let share_targets =
ensure_unlisted_workspace_target(auth, access_policy.discoverability, share_targets)?;
let response = finalize_workspace_plugin_upload(
config,
auth,
@@ -145,7 +175,7 @@ pub async fn save_remote_plugin_share(
file_id: upload.file_id,
etag,
discoverability: access_policy.discoverability,
share_targets: access_policy.share_targets,
share_targets,
},
)
.await?;
@@ -190,33 +220,54 @@ pub async fn list_remote_plugin_shares(
.map(|plugin| (plugin.plugin.id.clone(), plugin))
.collect::<BTreeMap<_, _>>();
let local_plugin_paths =
local_paths::load_plugin_share_local_paths(codex_home).unwrap_or_else(|err| {
warn!("failed to load plugin share local path mapping: {err}");
BTreeMap::new()
});
local_paths::load_plugin_share_local_paths(codex_home).map_err(|err| {
RemotePluginCatalogError::UnexpectedResponse(format!(
"failed to load plugin share local path mapping: {err}"
))
})?;
Ok(created_plugins
created_plugins
.into_iter()
.map(|plugin| {
let summary = build_remote_plugin_summary(&plugin, installed_by_id.get(&plugin.id));
let local_plugin_path = local_plugin_paths.get(&plugin.id).cloned();
RemotePluginShareSummary {
summary,
share_url: plugin.share_url,
local_plugin_path,
let summary = build_remote_plugin_summary(&plugin, installed_by_id.get(&plugin.id))?;
if summary
.share_context
.as_ref()
.and_then(|context| context.share_principals.as_ref())
.is_none()
{
return Err(RemotePluginCatalogError::UnexpectedResponse(format!(
"created workspace plugin `{}` did not include share_principals",
plugin.id
)));
}
let local_plugin_path = local_plugin_paths.get(&plugin.id).cloned();
Ok(RemotePluginShareSummary {
summary,
local_plugin_path,
})
})
.collect())
.collect()
}
pub fn load_plugin_share_remote_ids_by_local_path(
codex_home: &Path,
) -> io::Result<BTreeMap<AbsolutePathBuf, String>> {
let local_paths = local_paths::load_plugin_share_local_paths(codex_home)?;
Ok(local_paths
local_paths
.into_iter()
.map(|(remote_plugin_id, local_plugin_path)| (local_plugin_path, remote_plugin_id))
.collect())
.map(|(remote_plugin_id, local_plugin_path)| {
if !is_valid_remote_plugin_id(&remote_plugin_id) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"invalid remote plugin id in share local path mapping: {remote_plugin_id}"
),
));
}
Ok((local_plugin_path, remote_plugin_id))
})
.collect()
}
pub async fn delete_remote_plugin_share(
@@ -245,19 +296,63 @@ pub async fn update_remote_plugin_share_targets(
auth: Option<&CodexAuth>,
remote_plugin_id: &str,
targets: Vec<RemotePluginShareTarget>,
discoverability: RemotePluginShareUpdateDiscoverability,
) -> Result<RemotePluginShareUpdateTargetsResult, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let target_discoverability = match discoverability {
RemotePluginShareUpdateDiscoverability::Unlisted => {
RemotePluginShareDiscoverability::Unlisted
}
RemotePluginShareUpdateDiscoverability::Private => {
RemotePluginShareDiscoverability::Private
}
};
let targets =
ensure_unlisted_workspace_target(auth, Some(target_discoverability), Some(targets))?
.unwrap_or_default();
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/public/plugins/{remote_plugin_id}/shares");
let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/shares");
let client = build_reqwest_client();
let request = authenticated_request(client.put(&url), auth)?
.json(&RemotePluginShareUpdateTargetsRequest { targets });
let request = authenticated_request(client.put(&url), auth)?.json(
&RemotePluginShareUpdateTargetsRequest {
discoverability,
targets,
},
);
let response: RemotePluginShareUpdateTargetsResponse = send_and_decode(request, &url).await?;
Ok(RemotePluginShareUpdateTargetsResult {
principals: response.principals,
discoverability: response.discoverability,
})
}
fn ensure_unlisted_workspace_target(
auth: &CodexAuth,
discoverability: Option<RemotePluginShareDiscoverability>,
targets: Option<Vec<RemotePluginShareTarget>>,
) -> Result<Option<Vec<RemotePluginShareTarget>>, RemotePluginCatalogError> {
if discoverability != Some(RemotePluginShareDiscoverability::Unlisted) {
return Ok(targets);
}
let account_id = auth.get_account_id().ok_or_else(|| {
RemotePluginCatalogError::UnexpectedResponse(
"workspace plugin share requires an account id".to_string(),
)
})?;
let mut targets = targets.unwrap_or_default();
if !targets.iter().any(|target| {
target.principal_type == RemotePluginSharePrincipalType::Workspace
&& target.principal_id == account_id
}) {
targets.push(RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::Workspace,
principal_id: account_id,
role: RemotePluginShareTargetRole::Reader,
});
}
Ok(Some(targets))
}
async fn fetch_created_workspace_plugins(
config: &RemotePluginServiceConfig,
auth: &CodexAuth,
+64 -29
View File
@@ -93,6 +93,7 @@ fn remote_plugin_json(plugin_id: &str) -> serde_json::Value {
"id": plugin_id,
"name": "demo-plugin",
"scope": "WORKSPACE",
"discoverability": "PRIVATE",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"release": {
@@ -116,6 +117,7 @@ fn remote_plugin_json_with_share_url_and_principals(
let serde_json::Value::Object(fields) = &mut plugin else {
unreachable!("plugin json should be an object");
};
fields.insert("discoverability".to_string(), json!("PRIVATE"));
fields.insert("share_url".to_string(), json!(share_url));
fields.insert("share_principals".to_string(), share_principals);
plugin
@@ -204,15 +206,17 @@ async fn save_remote_plugin_share_creates_workspace_plugin() {
.and(body_json(json!({
"file_id": "file_123",
"etag": "\"upload_etag_123\"",
"discoverability": "PRIVATE",
"discoverability": "UNLISTED",
"share_targets": [
{
"principal_type": "user",
"principal_id": "user-1",
"role": "reader",
},
{
"principal_type": "workspace",
"principal_id": "workspace-1",
"principal_id": "account_id",
"role": "reader",
},
],
})))
@@ -231,17 +235,12 @@ async fn save_remote_plugin_share_creates_workspace_plugin() {
&plugin_path,
/*remote_plugin_id*/ None,
RemotePluginShareAccessPolicy {
discoverability: Some(RemotePluginShareDiscoverability::Private),
share_targets: Some(vec![
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
},
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::Workspace,
principal_id: "workspace-1".to_string(),
},
]),
discoverability: Some(RemotePluginShareDiscoverability::Unlisted),
share_targets: Some(vec![RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginShareTargetRole::Reader,
}]),
},
)
.await
@@ -401,18 +400,26 @@ async fn update_remote_plugin_share_targets_updates_targets() {
let auth = test_auth();
Mock::given(method("PUT"))
.and(path("/backend-api/public/plugins/plugins_123/shares"))
.and(path("/backend-api/ps/plugins/plugins_123/shares"))
.and(header("authorization", "Bearer Access Token"))
.and(header("chatgpt-account-id", "account_id"))
.and(body_json(json!({
"discoverability": "UNLISTED",
"targets": [
{
"principal_type": "user",
"principal_id": "user-1",
"role": "editor",
},
{
"principal_type": "group",
"principal_id": "group-1",
"role": "reader",
},
{
"principal_type": "workspace",
"principal_id": "account_id",
"role": "reader",
},
],
})))
@@ -421,14 +428,17 @@ async fn update_remote_plugin_share_targets_updates_targets() {
{
"principal_type": "user",
"principal_id": "user-1",
"role": "editor",
"name": "Gavin",
},
{
"principal_type": "group",
"principal_id": "group-1",
"role": "reader",
"name": "Engineering",
},
],
"discoverability": "UNLISTED",
})))
.expect(1)
.mount(&server)
@@ -442,12 +452,15 @@ async fn update_remote_plugin_share_targets_updates_targets() {
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginShareTargetRole::Editor,
},
RemotePluginShareTarget {
principal_type: RemotePluginSharePrincipalType::Group,
principal_id: "group-1".to_string(),
role: RemotePluginShareTargetRole::Reader,
},
],
RemotePluginShareUpdateDiscoverability::Unlisted,
)
.await
.unwrap();
@@ -459,14 +472,17 @@ async fn update_remote_plugin_share_targets_updates_targets() {
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-1".to_string(),
role: RemotePluginSharePrincipalRole::Editor,
name: "Gavin".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::Group,
principal_id: "group-1".to_string(),
role: RemotePluginSharePrincipalRole::Reader,
name: "Engineering".to_string(),
},
],
discoverability: RemotePluginShareDiscoverability::Unlisted,
}
);
}
@@ -542,11 +558,6 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
"role": "editor",
"name": "Editor",
},
{
"principal_type": "user",
"principal_id": "user-missing-role",
"name": "Missing Role",
},
]),
)],
"pagination": empty_pagination_json(),
@@ -574,20 +585,31 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
vec![
RemotePluginShareSummary {
summary: RemotePluginSummary {
id: "plugins_123".to_string(),
id: "demo-plugin@shared-with-me".to_string(),
remote_plugin_id: "plugins_123".to_string(),
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_123".to_string(),
discoverability: RemotePluginShareDiscoverability::Private,
share_url: Some(
"https://chatgpt.example/plugins/share/share-key-1".to_string(),
),
creator_account_user_id: None,
creator_name: None,
share_targets: Some(vec![RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-reader".to_string(),
name: "Reader".to_string(),
}]),
share_principals: Some(vec![
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-owner".to_string(),
role: RemotePluginSharePrincipalRole::Owner,
name: "Owner".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-reader".to_string(),
role: RemotePluginSharePrincipalRole::Reader,
name: "Reader".to_string(),
},
]),
}),
installed: false,
enabled: false,
@@ -597,19 +619,33 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
interface: Some(expected_plugin_interface()),
keywords: Vec::new(),
},
share_url: Some("https://chatgpt.example/plugins/share/share-key-1".to_string()),
local_plugin_path: Some(local_plugin_path),
},
RemotePluginShareSummary {
summary: RemotePluginSummary {
id: "plugins_456".to_string(),
id: "demo-plugin@shared-with-me".to_string(),
remote_plugin_id: "plugins_456".to_string(),
name: "demo-plugin".to_string(),
share_context: Some(RemotePluginShareContext {
remote_plugin_id: "plugins_456".to_string(),
discoverability: RemotePluginShareDiscoverability::Private,
share_url: None,
creator_account_user_id: None,
creator_name: None,
share_targets: Some(Vec::new()),
share_principals: Some(vec![
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-owner".to_string(),
role: RemotePluginSharePrincipalRole::Owner,
name: "Owner".to_string(),
},
RemotePluginSharePrincipal {
principal_type: RemotePluginSharePrincipalType::User,
principal_id: "user-editor".to_string(),
role: RemotePluginSharePrincipalRole::Editor,
name: "Editor".to_string(),
},
]),
}),
installed: true,
enabled: true,
@@ -619,7 +655,6 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
interface: Some(expected_plugin_interface()),
keywords: Vec::new(),
},
share_url: None,
local_plugin_path: None,
}
]