Base: codex-main originale (prima del fork aKode)
This commit is contained in:
235
codex-rs/core-plugins/src/agent_plugin_manifest.rs
Normal file
235
codex-rs/core-plugins/src/agent_plugin_manifest.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
use super::RawPluginManifest;
|
||||
use super::RawPluginManifestInterface;
|
||||
use super::RawPluginManifestMcpServers;
|
||||
use super::RawPluginManifestPaths;
|
||||
use super::UriPluginManifest;
|
||||
use super::compatibility_json_error;
|
||||
use super::parse_legacy_plugin_manifest_uri;
|
||||
use super::resolve_openai_onboarding_skill;
|
||||
use super::resolve_raw_plugin_manifest;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_PREFIX;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use codex_utils_plugins::SUPPORTED_AGENT_PLUGIN_SCHEMA_URIS;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
const CODEX_AGENT_PLUGIN_EXTENSION_NAMESPACE: &str = "com.openai";
|
||||
const AGENT_PLUGIN_FIELDS: &[&str] = &[
|
||||
"$schema",
|
||||
"name",
|
||||
"version",
|
||||
"description",
|
||||
"author",
|
||||
"homepage",
|
||||
"repository",
|
||||
"license",
|
||||
"keywords",
|
||||
"extensions",
|
||||
];
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawAgentPluginManifest {
|
||||
#[serde(rename = "$schema")]
|
||||
schema: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
version: Option<String>,
|
||||
#[serde(default)]
|
||||
description: Option<String>,
|
||||
#[serde(default)]
|
||||
author: Option<RawAgentPluginAuthor>,
|
||||
#[serde(default)]
|
||||
homepage: Option<String>,
|
||||
#[serde(default, rename = "repository")]
|
||||
_repository: Option<String>,
|
||||
#[serde(default, rename = "license")]
|
||||
_license: Option<String>,
|
||||
#[serde(default)]
|
||||
keywords: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RawAgentPluginAuthor {
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default, rename = "email")]
|
||||
_email: Option<String>,
|
||||
#[serde(default, rename = "url")]
|
||||
_url: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn parse_agent_plugin_manifest_uri(
|
||||
plugin_root: &PathUri,
|
||||
manifest_path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let value = serde_json::from_str::<JsonValue>(contents)?;
|
||||
let JsonValue::Object(mut object) = value else {
|
||||
return Err(compatibility_json_error(
|
||||
"Agent Plugins root `plugin.json` must contain a JSON object",
|
||||
));
|
||||
};
|
||||
for field in object.keys() {
|
||||
if !AGENT_PLUGIN_FIELDS.contains(&field.as_str()) {
|
||||
tracing::warn!(path = %manifest_path, field, "ignoring unknown Agent Plugins manifest field");
|
||||
}
|
||||
}
|
||||
object.retain(|field, _| AGENT_PLUGIN_FIELDS.contains(&field.as_str()));
|
||||
if object
|
||||
.get("extensions")
|
||||
.is_some_and(|extensions| !extensions.is_object())
|
||||
{
|
||||
tracing::warn!(path = %manifest_path, "ignoring non-object Agent Plugins `extensions` field");
|
||||
object.remove("extensions");
|
||||
}
|
||||
let codex_extension = object
|
||||
.get("extensions")
|
||||
.and_then(JsonValue::as_object)
|
||||
.and_then(|extensions| extensions.get(CODEX_AGENT_PLUGIN_EXTENSION_NAMESPACE))
|
||||
.and_then(|extension| {
|
||||
if extension.is_object() {
|
||||
Some(extension)
|
||||
} else {
|
||||
tracing::warn!(
|
||||
path = %manifest_path,
|
||||
namespace = CODEX_AGENT_PLUGIN_EXTENSION_NAMESPACE,
|
||||
"ignoring non-object Agent Plugins extension"
|
||||
);
|
||||
None
|
||||
}
|
||||
});
|
||||
for field in [
|
||||
"version",
|
||||
"description",
|
||||
"author",
|
||||
"homepage",
|
||||
"repository",
|
||||
"license",
|
||||
] {
|
||||
if object.get(field).is_some_and(JsonValue::is_null) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"Agent Plugins `{field}` must use its declared type when present"
|
||||
)));
|
||||
}
|
||||
}
|
||||
if let Some(author) = object.get("author").and_then(JsonValue::as_object) {
|
||||
for field in ["name", "email", "url"] {
|
||||
if author.get(field).is_some_and(JsonValue::is_null) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"Agent Plugins `author.{field}` must be a string when present"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let onboarding_skill = resolve_openai_onboarding_skill(plugin_root, codex_extension);
|
||||
let codex_extension = codex_extension.map(serde_json::to_string).transpose()?;
|
||||
|
||||
let raw = serde_json::from_value::<RawAgentPluginManifest>(JsonValue::Object(object))?;
|
||||
if !SUPPORTED_AGENT_PLUGIN_SCHEMA_URIS.contains(&raw.schema.as_str()) {
|
||||
let message = if raw.schema.starts_with(AGENT_PLUGIN_SCHEMA_PREFIX) {
|
||||
format!(
|
||||
"unsupported Agent Plugins schema `{}`; supported schemas: `{AGENT_PLUGIN_SCHEMA_URI}`",
|
||||
raw.schema
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"root `plugin.json` is not an Agent Plugins manifest; expected `$schema` `{AGENT_PLUGIN_SCHEMA_URI}`"
|
||||
)
|
||||
};
|
||||
return Err(compatibility_json_error(message));
|
||||
}
|
||||
if !is_valid_agent_plugin_name(&raw.name) {
|
||||
return Err(compatibility_json_error(format!(
|
||||
"invalid Agent Plugins name `{}`; use lowercase letters, numbers, dots, or hyphens",
|
||||
raw.name
|
||||
)));
|
||||
}
|
||||
|
||||
let version = raw.version.and_then(non_empty_trimmed);
|
||||
let description = raw.description.and_then(non_empty_trimmed);
|
||||
let developer_name = raw
|
||||
.author
|
||||
.and_then(|author| author.name)
|
||||
.and_then(non_empty_trimmed);
|
||||
let homepage = raw.homepage.and_then(non_empty_trimmed);
|
||||
let name = raw.name;
|
||||
let mut resolved = resolve_raw_plugin_manifest(
|
||||
plugin_root,
|
||||
manifest_path,
|
||||
RawPluginManifest {
|
||||
name: name.clone(),
|
||||
version,
|
||||
description: description.clone(),
|
||||
keywords: raw.keywords,
|
||||
skills: Some(RawPluginManifestPaths::Path("./skills".to_string())),
|
||||
mcp_servers: Some(RawPluginManifestMcpServers::Path("./mcp.json".to_string())),
|
||||
interface: Some(RawPluginManifestInterface {
|
||||
display_name: Some(name),
|
||||
short_description: description.clone(),
|
||||
long_description: description,
|
||||
developer_name,
|
||||
category: Some("Other".to_string()),
|
||||
website_url: homepage,
|
||||
..RawPluginManifestInterface::default()
|
||||
}),
|
||||
..RawPluginManifest::default()
|
||||
},
|
||||
)?;
|
||||
|
||||
if let Some(extension) = codex_extension.as_deref() {
|
||||
apply_codex_agent_plugin_extension(&mut resolved, plugin_root, manifest_path, extension)?;
|
||||
resolved.paths.onboarding_skill = onboarding_skill;
|
||||
} else if let Some((overlay_path, overlay_contents)) = overlay {
|
||||
apply_codex_agent_plugin_extension(
|
||||
&mut resolved,
|
||||
plugin_root,
|
||||
overlay_path,
|
||||
overlay_contents,
|
||||
)?;
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn non_empty_trimmed(value: String) -> Option<String> {
|
||||
let value = value.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
}
|
||||
|
||||
fn apply_codex_agent_plugin_extension(
|
||||
resolved: &mut UriPluginManifest,
|
||||
plugin_root: &PathUri,
|
||||
source_path: &PathUri,
|
||||
contents: &str,
|
||||
) -> Result<(), serde_json::Error> {
|
||||
let extension = parse_legacy_plugin_manifest_uri(plugin_root, source_path, contents)?;
|
||||
resolved.paths.apps = extension.paths.apps;
|
||||
resolved.paths.hooks = extension.paths.hooks;
|
||||
resolved.paths.onboarding_skill = extension.paths.onboarding_skill;
|
||||
if extension.interface.is_some() {
|
||||
resolved.interface = extension.interface;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_valid_agent_plugin_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= 64
|
||||
&& !name.contains("--")
|
||||
&& !name.contains("..")
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || b".-".contains(&byte))
|
||||
&& name
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
&& name
|
||||
.as_bytes()
|
||||
.last()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
}
|
||||
275
codex-rs/core-plugins/src/agent_plugin_manifest_tests.rs
Normal file
275
codex-rs/core-plugins/src/agent_plugin_manifest_tests.rs
Normal file
@@ -0,0 +1,275 @@
|
||||
use super::PluginManifest;
|
||||
use super::PluginManifestMcpServers;
|
||||
use super::load_plugin_manifest;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_agent_plugin_manifest(plugin_root: &Path, extra_fields: &str) {
|
||||
fs::create_dir_all(plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{
|
||||
"$schema": "{AGENT_PLUGIN_SCHEMA_URI}",
|
||||
"name": "demo-plugin"{extra_fields}
|
||||
}}"#
|
||||
),
|
||||
)
|
||||
.expect("write Agent Plugins manifest");
|
||||
}
|
||||
|
||||
fn load_manifest(plugin_root: &Path) -> PluginManifest {
|
||||
load_plugin_manifest(plugin_root).expect("load plugin manifest")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_portable_metadata_and_fixed_components() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "release-2026-07",
|
||||
"description": "Portable demo",
|
||||
"author": {"name": "Portable Author"},
|
||||
"homepage": "https://example.com/plugin",
|
||||
"keywords": ["portable"]"#,
|
||||
);
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.name, "demo-plugin");
|
||||
assert_eq!(manifest.version.as_deref(), Some("release-2026-07"));
|
||||
assert_eq!(manifest.description.as_deref(), Some("Portable demo"));
|
||||
assert_eq!(manifest.keywords, vec!["portable"]);
|
||||
assert_eq!(
|
||||
manifest.paths.skills,
|
||||
vec![
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("skills"))
|
||||
.expect("skills path")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.mcp_servers,
|
||||
Some(PluginManifestMcpServers::Path(
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("mcp.json"))
|
||||
.expect("MCP path")
|
||||
))
|
||||
);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.display_name.as_deref(), Some("demo-plugin"));
|
||||
assert_eq!(
|
||||
interface.short_description.as_deref(),
|
||||
Some("Portable demo")
|
||||
);
|
||||
assert_eq!(interface.long_description.as_deref(), Some("Portable demo"));
|
||||
assert_eq!(interface.developer_name.as_deref(), Some("Portable Author"));
|
||||
assert_eq!(
|
||||
interface.website_url.as_deref(),
|
||||
Some("https://example.com/plugin")
|
||||
);
|
||||
assert_eq!(interface.category.as_deref(), Some("Other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_invent_optional_metadata() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(&plugin_root, "");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.version, None);
|
||||
assert_eq!(manifest.description, None);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.display_name.as_deref(), Some("demo-plugin"));
|
||||
assert_eq!(interface.short_description, None);
|
||||
assert_eq!(interface.long_description, None);
|
||||
assert_eq!(interface.developer_name, None);
|
||||
assert_eq!(interface.website_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_empty_optional_metadata() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "",
|
||||
"description": " ",
|
||||
"author": {"name": " ", "email": ""},
|
||||
"homepage": "",
|
||||
"keywords": [""]"#,
|
||||
);
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.version, None);
|
||||
assert_eq!(manifest.description, None);
|
||||
assert_eq!(manifest.keywords, vec![""]);
|
||||
let interface = manifest.interface.expect("default portable interface");
|
||||
assert_eq!(interface.short_description, None);
|
||||
assert_eq!(interface.long_description, None);
|
||||
assert_eq!(interface.developer_name, None);
|
||||
assert_eq!(interface.website_url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_dotted_names_and_ignores_extensions() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("acme-tools");
|
||||
fs::create_dir_all(&plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{
|
||||
"$schema":"{AGENT_PLUGIN_SCHEMA_URI}",
|
||||
"name":"acme.tools",
|
||||
"extensions":{{
|
||||
"com.example.client":{{"future":true}},
|
||||
"com.example.unimplemented":"ignored"
|
||||
}}
|
||||
}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
|
||||
assert_eq!(load_manifest(&plugin_root).name, "acme.tools");
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"acme.tools","extensions":false}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest with invalid extensions");
|
||||
assert_eq!(load_manifest(&plugin_root).name, "acme.tools");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_overlong_name_and_wrong_metadata_types() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
fs::create_dir_all(&plugin_root).expect("create plugin root");
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"{}"}}"#,
|
||||
"a".repeat(65)
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","homepage":42}}"#),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","version":null}}"#),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
format!(
|
||||
r#"{{"$schema":"{AGENT_PLUGIN_SCHEMA_URI}","name":"demo-plugin","author":{{"name":null}}}}"#
|
||||
),
|
||||
)
|
||||
.expect("write manifest");
|
||||
assert_eq!(load_plugin_manifest(&plugin_root), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_codex_overlay_keeps_portable_components_fixed() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"version": "portable-version",
|
||||
"description": "Portable description""#,
|
||||
);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create overlay dir");
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "different-name",
|
||||
"version": "9.9.9",
|
||||
"description": "Codex description",
|
||||
"skills": [],
|
||||
"mcpServers": null,
|
||||
"interface": {"displayName": "Codex Demo"}
|
||||
}"#,
|
||||
)
|
||||
.expect("write overlay");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(manifest.name, "demo-plugin");
|
||||
assert_eq!(manifest.version.as_deref(), Some("portable-version"));
|
||||
assert_eq!(
|
||||
manifest.description.as_deref(),
|
||||
Some("Portable description")
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.skills,
|
||||
vec![
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("skills"))
|
||||
.expect("skills path")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
manifest.paths.mcp_servers,
|
||||
Some(PluginManifestMcpServers::Path(
|
||||
AbsolutePathBuf::from_absolute_path_checked(plugin_root.join("mcp.json"))
|
||||
.expect("MCP path")
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
manifest
|
||||
.interface
|
||||
.and_then(|interface| interface.display_name),
|
||||
Some("Codex Demo".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_openai_extension_precedes_legacy_overlay() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let plugin_root = tmp.path().join("demo-plugin");
|
||||
write_agent_plugin_manifest(
|
||||
&plugin_root,
|
||||
r#",
|
||||
"extensions": {
|
||||
"com.openai": {
|
||||
"interface": {"displayName": "Inline Codex"}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create overlay dir");
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"interface":{"displayName":"Legacy Codex"}}"#,
|
||||
)
|
||||
.expect("write overlay");
|
||||
|
||||
let manifest = load_manifest(&plugin_root);
|
||||
|
||||
assert_eq!(
|
||||
manifest
|
||||
.interface
|
||||
.and_then(|interface| interface.display_name),
|
||||
Some("Inline Codex".to_string())
|
||||
);
|
||||
}
|
||||
99
codex-rs/core-plugins/src/agent_plugin_mcp_overlay.rs
Normal file
99
codex-rs/core-plugins/src/agent_plugin_mcp_overlay.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::load_mcp_servers_from_file;
|
||||
use super::load_mcp_servers_from_manifest_object;
|
||||
use super::plugin_mcp_config_paths;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::manifest::PluginManifestMcpServers;
|
||||
use crate::manifest::parse_plugin_manifest;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use tracing::warn;
|
||||
|
||||
pub(super) async fn apply_codex_env_overlay(
|
||||
plugin_root: &Path,
|
||||
agent_servers: &mut HashMap<String, McpServerConfig>,
|
||||
) {
|
||||
if agent_servers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let overlay_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
let Ok(contents) = tokio::fs::read_to_string(&overlay_path).await else {
|
||||
return;
|
||||
};
|
||||
let overlay_manifest = match parse_plugin_manifest(plugin_root, &overlay_path, &contents) {
|
||||
Ok(manifest) => manifest,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
path = %overlay_path.display(),
|
||||
"failed to parse Codex Agent Plugin MCP overlay: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let overlay_servers = match &overlay_manifest.paths.mcp_servers {
|
||||
Some(PluginManifestMcpServers::Object(servers)) => {
|
||||
load_mcp_servers_from_manifest_object(plugin_root, servers).mcp_servers
|
||||
}
|
||||
Some(PluginManifestMcpServers::Path(_)) | None => {
|
||||
let mut servers = HashMap::new();
|
||||
for path in plugin_mcp_config_paths(plugin_root, &overlay_manifest.paths) {
|
||||
servers.extend(
|
||||
load_mcp_servers_from_file(
|
||||
plugin_root,
|
||||
/*plugin_data_root*/ None,
|
||||
PluginManifestFormat::Legacy,
|
||||
&path,
|
||||
)
|
||||
.await
|
||||
.mcp_servers,
|
||||
);
|
||||
}
|
||||
servers
|
||||
}
|
||||
};
|
||||
|
||||
for (name, overlay_server) in overlay_servers {
|
||||
let Some(agent_server) = agent_servers.get_mut(&name) else {
|
||||
continue;
|
||||
};
|
||||
let (
|
||||
McpServerTransportConfig::Stdio { env, env_vars, .. },
|
||||
McpServerTransportConfig::Stdio {
|
||||
env_vars: mut overlay_env_vars,
|
||||
..
|
||||
},
|
||||
) = (&mut agent_server.transport, overlay_server.transport)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
overlay_env_vars.retain(|variable| !variable.is_remote_source());
|
||||
|
||||
if let Some(env) = env {
|
||||
env.retain(|name, value| {
|
||||
let Some(reference) = value
|
||||
.strip_prefix("${")
|
||||
.and_then(|reference| reference.strip_suffix('}'))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
!overlay_env_vars.iter().any(|variable| {
|
||||
environment_names_match(name, variable.name())
|
||||
&& environment_names_match(reference, variable.name())
|
||||
})
|
||||
});
|
||||
}
|
||||
env_vars.extend(overlay_env_vars);
|
||||
}
|
||||
}
|
||||
|
||||
fn environment_names_match(left: &str, right: &str) -> bool {
|
||||
if cfg!(windows) {
|
||||
left.eq_ignore_ascii_case(right)
|
||||
} else {
|
||||
left == right
|
||||
}
|
||||
}
|
||||
42
codex-rs/core-plugins/src/app_mcp_routing.rs
Normal file
42
codex-rs/core-plugins/src/app_mcp_routing.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use codex_plugin::AppDeclaration;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub fn apps_route_available(auth_mode: Option<AuthMode>) -> bool {
|
||||
auth_mode.is_some_and(AuthMode::uses_codex_backend)
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_supports_apps(format: PluginManifestFormat, plugin_id: &PluginId) -> bool {
|
||||
// The remote curated installer overwrites app declarations with plugin-service metadata.
|
||||
// Keep portable app declarations inactive for other Agent Plugins.
|
||||
format == PluginManifestFormat::Legacy
|
||||
|| plugin_id.marketplace_name == REMOTE_GLOBAL_MARKETPLACE_NAME
|
||||
}
|
||||
|
||||
pub(crate) fn apply_app_mcp_routing_policy<M>(
|
||||
apps: &mut Vec<AppDeclaration>,
|
||||
mcp_servers: &mut HashMap<String, M>,
|
||||
auth_mode: Option<AuthMode>,
|
||||
plugin_active: bool,
|
||||
) {
|
||||
if !apps_route_available(auth_mode) {
|
||||
apps.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if plugin_active && !apps.is_empty() {
|
||||
let app_declaration_names = apps
|
||||
.iter()
|
||||
.map(|app| app.name.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
mcp_servers.retain(|name, _| !app_declaration_names.contains(name.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "app_mcp_routing_tests.rs"]
|
||||
mod tests;
|
||||
99
codex-rs/core-plugins/src/app_mcp_routing_tests.rs
Normal file
99
codex-rs/core-plugins/src/app_mcp_routing_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use super::*;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn app(name: &str) -> AppDeclaration {
|
||||
AppDeclaration {
|
||||
name: name.to_string(),
|
||||
connector_id: AppConnectorId(format!("connector_{name}")),
|
||||
category: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_servers(mcp_servers: impl IntoIterator<Item = (&'static str, i32)>) -> HashMap<String, i32> {
|
||||
mcp_servers
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name.to_string(), value))
|
||||
.collect::<HashMap<_, _>>()
|
||||
}
|
||||
|
||||
fn sorted_app_names(apps: &[AppDeclaration]) -> Vec<String> {
|
||||
let mut names = apps.iter().map(|app| app.name.clone()).collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
fn sorted_mcp_server_names(mcp_servers: &HashMap<String, i32>) -> Vec<String> {
|
||||
let mut names = mcp_servers.keys().cloned().collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apps_route_available_tracks_auth_mode() {
|
||||
assert!(apps_route_available(Some(AuthMode::Chatgpt)));
|
||||
assert!(apps_route_available(Some(AuthMode::AgentIdentity)));
|
||||
assert!(!apps_route_available(Some(AuthMode::ApiKey)));
|
||||
assert!(!apps_route_available(/*auth_mode*/ None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_mcp_routing_clears_apps_when_apps_route_is_unavailable() {
|
||||
let mut apps = vec![app("linear")];
|
||||
let mut mcp_servers = mcp_servers([("linear", 1), ("docs", 2)]);
|
||||
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut apps,
|
||||
&mut mcp_servers,
|
||||
Some(AuthMode::ApiKey),
|
||||
/*plugin_active*/ true,
|
||||
);
|
||||
|
||||
assert!(apps.is_empty());
|
||||
assert_eq!(
|
||||
sorted_mcp_server_names(&mcp_servers),
|
||||
vec!["docs".to_string(), "linear".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_mcp_routing_preserves_apps_and_removes_conflicting_mcp_with_apps_route() {
|
||||
let mut apps = vec![app("linear"), app("notion")];
|
||||
let mut mcp_servers = mcp_servers([("linear", 1), ("docs", 2), ("notion", 3)]);
|
||||
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut apps,
|
||||
&mut mcp_servers,
|
||||
Some(AuthMode::Chatgpt),
|
||||
/*plugin_active*/ true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sorted_app_names(&apps),
|
||||
vec!["linear".to_string(), "notion".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
sorted_mcp_server_names(&mcp_servers),
|
||||
vec!["docs".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_mcp_routing_preserves_mcp_conflicts_when_plugin_is_inactive() {
|
||||
let mut apps = vec![app("linear")];
|
||||
let mut mcp_servers = mcp_servers([("linear", 1), ("docs", 2)]);
|
||||
|
||||
apply_app_mcp_routing_policy(
|
||||
&mut apps,
|
||||
&mut mcp_servers,
|
||||
Some(AuthMode::Chatgpt),
|
||||
/*plugin_active*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(sorted_app_names(&apps), vec!["linear".to_string()]);
|
||||
assert_eq!(
|
||||
sorted_mcp_server_names(&mcp_servers),
|
||||
vec!["docs".to_string(), "linear".to_string()]
|
||||
);
|
||||
}
|
||||
108
codex-rs/core-plugins/src/artifact_operation.rs
Normal file
108
codex-rs/core-plugins/src/artifact_operation.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use crate::PluginCommandAttribution;
|
||||
use crate::command_script_arguments;
|
||||
|
||||
const PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
|
||||
const MAX_EXPECTED_OUTPUT_COUNT: u32 = 100;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ArtifactOperation {
|
||||
pub plugin_name: &'static str,
|
||||
pub script_path: &'static str,
|
||||
pub artifact_type: &'static str,
|
||||
pub operation_kind: &'static str,
|
||||
pub expected_output_count: u32,
|
||||
pub output_format: &'static str,
|
||||
}
|
||||
|
||||
struct ArtifactSkill {
|
||||
plugin_name: &'static str,
|
||||
script_path: &'static str,
|
||||
artifact_type: &'static str,
|
||||
output_formats: &'static [&'static str],
|
||||
}
|
||||
|
||||
const ARTIFACT_SKILLS: &[ArtifactSkill] = &[
|
||||
ArtifactSkill {
|
||||
plugin_name: "presentations",
|
||||
script_path: "skills/presentations/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "presentation",
|
||||
output_formats: &["ppt", "pptx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "documents",
|
||||
script_path: "skills/documents/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "document",
|
||||
output_formats: &["doc", "docx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "spreadsheets",
|
||||
script_path: "skills/spreadsheets/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "spreadsheet",
|
||||
output_formats: &["csv", "tsv", "xls", "xlsm", "xlsx"],
|
||||
},
|
||||
ArtifactSkill {
|
||||
plugin_name: "pdf",
|
||||
script_path: "skills/pdf/container_tools/mark_artifact_operation_started.mjs",
|
||||
artifact_type: "pdf",
|
||||
output_formats: &["pdf"],
|
||||
},
|
||||
];
|
||||
|
||||
pub fn recognize_artifact_operation(
|
||||
attribution: Option<&PluginCommandAttribution>,
|
||||
command: &[String],
|
||||
) -> Option<ArtifactOperation> {
|
||||
let attribution = attribution?;
|
||||
if attribution.plugin_id.marketplace_name != PRIMARY_RUNTIME_MARKETPLACE_NAME {
|
||||
return None;
|
||||
}
|
||||
let skill = ARTIFACT_SKILLS.iter().find(|skill| {
|
||||
attribution.plugin_id.plugin_name == skill.plugin_name
|
||||
&& attribution.normalized_relative_path == skill.script_path
|
||||
})?;
|
||||
let script_arguments = command_script_arguments(command)?;
|
||||
let [
|
||||
operation_kind_flag,
|
||||
operation_kind,
|
||||
expected_output_count_flag,
|
||||
expected_output_count,
|
||||
output_format_flag,
|
||||
output_format,
|
||||
] = script_arguments.as_slice()
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if operation_kind_flag != "--operation-kind"
|
||||
|| expected_output_count_flag != "--expected-output-count"
|
||||
|| output_format_flag != "--output-format"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let operation_kind = match operation_kind.as_str() {
|
||||
"create" => "create",
|
||||
"edit" => "edit",
|
||||
_ => return None,
|
||||
};
|
||||
let expected_output_count = expected_output_count.parse::<u32>().ok()?;
|
||||
if !(1..=MAX_EXPECTED_OUTPUT_COUNT).contains(&expected_output_count) {
|
||||
return None;
|
||||
}
|
||||
let output_format = skill
|
||||
.output_formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|known_format| known_format.eq_ignore_ascii_case(output_format))?;
|
||||
|
||||
Some(ArtifactOperation {
|
||||
plugin_name: skill.plugin_name,
|
||||
script_path: skill.script_path,
|
||||
artifact_type: skill.artifact_type,
|
||||
operation_kind,
|
||||
expected_output_count,
|
||||
output_format,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "artifact_operation_tests.rs"]
|
||||
mod tests;
|
||||
151
codex-rs/core-plugins/src/artifact_operation_tests.rs
Normal file
151
codex-rs/core-plugins/src/artifact_operation_tests.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use super::*;
|
||||
use codex_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn recognizes_supported_artifact_markers() {
|
||||
for skill in ARTIFACT_SKILLS {
|
||||
for operation_kind in ["create", "edit"] {
|
||||
let attribution = attribution(skill.plugin_name, skill.script_path);
|
||||
assert_eq!(
|
||||
recognize_artifact_operation(
|
||||
Some(&attribution),
|
||||
&marker_command(
|
||||
skill.script_path,
|
||||
operation_kind,
|
||||
"2",
|
||||
skill.output_formats[0],
|
||||
),
|
||||
),
|
||||
Some(ArtifactOperation {
|
||||
plugin_name: skill.plugin_name,
|
||||
script_path: skill.script_path,
|
||||
artifact_type: skill.artifact_type,
|
||||
operation_kind,
|
||||
expected_output_count: 2,
|
||||
output_format: skill.output_formats[0],
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_untrusted_mismatched_or_invalid_markers() {
|
||||
let presentation = &ARTIFACT_SKILLS[0];
|
||||
let cases = [
|
||||
(
|
||||
None,
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse("documents@openai-primary-runtime").expect("plugin id"),
|
||||
normalized_relative_path: presentation.script_path.to_string(),
|
||||
}),
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
"presentations",
|
||||
"skills/presentations/container_tools/render_slides.mjs",
|
||||
)),
|
||||
marker_command(presentation.script_path, "create", "1", "pptx"),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(presentation.script_path, Vec::new()),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("read", "1", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "0", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "101", "pptx"),
|
||||
),
|
||||
),
|
||||
(
|
||||
Some(attribution(
|
||||
presentation.plugin_name,
|
||||
presentation.script_path,
|
||||
)),
|
||||
command_with_arguments(
|
||||
presentation.script_path,
|
||||
marker_arguments("create", "1", "html"),
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
for (attribution, command) in cases {
|
||||
assert_eq!(
|
||||
recognize_artifact_operation(attribution.as_ref(), &command),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn attribution(plugin_name: &str, script_path: &str) -> PluginCommandAttribution {
|
||||
PluginCommandAttribution {
|
||||
plugin_id: PluginId::parse(&format!("{plugin_name}@openai-primary-runtime"))
|
||||
.expect("plugin id"),
|
||||
normalized_relative_path: script_path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn marker_command(
|
||||
script_path: &str,
|
||||
operation_kind: &str,
|
||||
expected_output_count: &str,
|
||||
output_format: &str,
|
||||
) -> Vec<String> {
|
||||
command_with_arguments(
|
||||
script_path,
|
||||
marker_arguments(operation_kind, expected_output_count, output_format),
|
||||
)
|
||||
}
|
||||
|
||||
fn command_with_arguments(script_path: &str, arguments: Vec<String>) -> Vec<String> {
|
||||
[vec!["node".to_string(), script_path.to_string()], arguments].concat()
|
||||
}
|
||||
|
||||
fn marker_arguments(
|
||||
operation_kind: &str,
|
||||
expected_output_count: &str,
|
||||
output_format: &str,
|
||||
) -> Vec<String> {
|
||||
[
|
||||
"--operation-kind",
|
||||
operation_kind,
|
||||
"--expected-output-count",
|
||||
expected_output_count,
|
||||
"--output-format",
|
||||
output_format,
|
||||
]
|
||||
.map(str::to_string)
|
||||
.to_vec()
|
||||
}
|
||||
141
codex-rs/core-plugins/src/catalog.rs
Normal file
141
codex-rs/core-plugins/src/catalog.rs
Normal file
@@ -0,0 +1,141 @@
|
||||
//! Source-neutral plugin catalogs, reconciliation, and source-aware enablement policy.
|
||||
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_core_plugin_common::PluginIdentity;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// One source's discovery snapshot; only a complete empty catalog establishes absence.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PluginCatalog {
|
||||
pub entries: Vec<PluginCatalogEntry>,
|
||||
pub warnings: Vec<String>,
|
||||
/// Listing omitted entries.
|
||||
pub is_partial: bool,
|
||||
}
|
||||
|
||||
/// Manifest metadata and every location that can supply the same logical plugin.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct PluginCatalogEntry {
|
||||
pub id: PluginIdentity,
|
||||
pub enabled: bool,
|
||||
pub display_name: String,
|
||||
pub version: String,
|
||||
/// Raw MCP server declarations keyed by their authored names.
|
||||
pub mcp_servers: BTreeMap<String, Value>,
|
||||
pub connector_ids: Vec<String>,
|
||||
pub locations: Vec<PluginSourceLocation>,
|
||||
}
|
||||
|
||||
impl PluginCatalogEntry {
|
||||
/// Disabled entries never project. Otherwise Cloud membership supplies enablement;
|
||||
/// executor-only entries require every installation's local plugin ID in the supplied
|
||||
/// config, where omitted enablement retains the configured plugin's default.
|
||||
/// A remote identity alone does not establish Cloud membership.
|
||||
pub fn is_enabled(&self, configured_plugins: &HashMap<String, PluginConfig>) -> bool {
|
||||
if !self.enabled {
|
||||
return false;
|
||||
}
|
||||
let is_cloud_plugin = self
|
||||
.locations
|
||||
.iter()
|
||||
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }));
|
||||
is_cloud_plugin
|
||||
|| self.locations.iter().all(|location| match location {
|
||||
PluginSourceLocation::Executor { plugin_id, .. } => configured_plugins
|
||||
.get(plugin_id)
|
||||
.is_some_and(|plugin| plugin.enabled.unwrap_or(true)),
|
||||
PluginSourceLocation::Cloud { .. } => true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PluginCatalogEntry {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("PluginCatalogEntry")
|
||||
.field("id", &self.id)
|
||||
.field("enabled", &self.enabled)
|
||||
.field("display_name", &self.display_name)
|
||||
.field("version", &self.version)
|
||||
// Declaration values can contain secrets, so only log their keys.
|
||||
.field(
|
||||
"mcp_server_names",
|
||||
&self.mcp_servers.keys().collect::<Vec<_>>(),
|
||||
)
|
||||
.field("connector_ids", &self.connector_ids)
|
||||
.field("locations", &self.locations)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A source that can supply a plugin; cloud URIs are opaque, not local paths.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PluginSourceLocation {
|
||||
Cloud {
|
||||
resource_uri: String,
|
||||
bundle_uri: Option<String>,
|
||||
},
|
||||
Executor {
|
||||
/// Executor environment that owns `root`.
|
||||
environment_id: String,
|
||||
/// Local `name@marketplace` key used for this installation in configuration.
|
||||
plugin_id: String,
|
||||
root: PathUri,
|
||||
},
|
||||
}
|
||||
|
||||
/// Uses Cloud membership and metadata, retaining version-matched installations in order.
|
||||
/// Unavailable or partial Cloud data preserves unmatched executor entries. Complete Cloud
|
||||
/// catalogs disable unmatched remote entries; local entries retain their enablement.
|
||||
pub fn merge_catalogs(
|
||||
executor: Option<&PluginCatalog>,
|
||||
cloud: Option<&PluginCatalog>,
|
||||
) -> PluginCatalog {
|
||||
let Some(executor) = executor else {
|
||||
return cloud.cloned().unwrap_or_default();
|
||||
};
|
||||
let Some(cloud) = cloud else {
|
||||
return executor.clone();
|
||||
};
|
||||
let mut merged = cloud.clone();
|
||||
merged.is_partial |= executor.is_partial;
|
||||
merged.warnings.extend(executor.warnings.iter().cloned());
|
||||
for installation in &executor.entries {
|
||||
if matches!(&installation.id, PluginIdentity::Local { .. }) {
|
||||
merged.entries.push(installation.clone());
|
||||
continue;
|
||||
}
|
||||
// Appended executor entries are not Cloud definitions and cannot authorize each other.
|
||||
let Some(definition) = merged.entries[..cloud.entries.len()]
|
||||
.iter_mut()
|
||||
.find(|definition| definition.id == installation.id)
|
||||
else {
|
||||
let mut unmatched = installation.clone();
|
||||
if !cloud.is_partial {
|
||||
unmatched.enabled = false;
|
||||
}
|
||||
merged.entries.push(unmatched);
|
||||
continue;
|
||||
};
|
||||
if definition.version != installation.version {
|
||||
merged.warnings.push(format!(
|
||||
"plugin `{}` has different cloud and executor versions; retaining the cloud definition",
|
||||
definition.id.as_str(),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
for location in &installation.locations {
|
||||
if !definition.locations.contains(location) {
|
||||
definition.locations.push(location.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_tests.rs"]
|
||||
mod tests;
|
||||
197
codex-rs/core-plugins/src/catalog_tests.rs
Normal file
197
codex-rs/core-plugins/src/catalog_tests.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! Tests Cloud catalog authority, version matching, and installation reconciliation.
|
||||
|
||||
use super::PluginCatalog;
|
||||
use super::PluginCatalogEntry;
|
||||
use super::PluginIdentity;
|
||||
use super::PluginSourceLocation;
|
||||
use super::merge_catalogs;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn executor_plugin(remote_id: &str, environment_id: &str) -> anyhow::Result<PluginCatalogEntry> {
|
||||
let mut entry = cloud_plugin(remote_id);
|
||||
entry.locations = vec![PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
root: PathUri::parse("file:///plugins/example/1.0.0")?,
|
||||
}];
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_catalog_prefers_cloud_and_matches_executor_versions() -> anyhow::Result<()> {
|
||||
let definition = cloud_plugin("plugin_a");
|
||||
let mut first = executor_plugin("plugin_a", "executor-a")?;
|
||||
first.display_name = "Installed display name".to_string();
|
||||
first.mcp_servers.clear();
|
||||
first.connector_ids.clear();
|
||||
let second = executor_plugin("plugin_a", "executor-b")?;
|
||||
let mut incompatible = executor_plugin("plugin_a", "executor-c")?;
|
||||
incompatible.version = "2.0.0".to_string();
|
||||
let mut expected = definition.clone();
|
||||
expected.locations.extend(first.locations.clone());
|
||||
expected.locations.extend(second.locations.clone());
|
||||
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![first.clone(), first, second, incompatible],
|
||||
warnings: vec!["executor warning".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition],
|
||||
warnings: vec!["cloud warning".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![expected],
|
||||
warnings: vec![
|
||||
"cloud warning".to_string(),
|
||||
"executor warning".to_string(),
|
||||
"plugin `plugin_a` has different cloud and executor versions; retaining the cloud definition"
|
||||
.to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_catalog_controls_remote_plugins_but_preserves_local_plugins() -> anyhow::Result<()> {
|
||||
let installed = executor_plugin("plugin_a", "executor-a")?;
|
||||
let mut local = executor_plugin("plugin_a", "executor-b")?;
|
||||
local.id = PluginIdentity::Local {
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
};
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![installed.clone(), local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let local_only = PluginCatalog {
|
||||
entries: vec![local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
// An available Cloud catalog controls remote entries; local entries are unaffected.
|
||||
let mut other_installation = executor_plugin("plugin_a", "executor-c")?;
|
||||
other_installation.version = "2.0.0".to_string();
|
||||
let unmatched = PluginCatalog {
|
||||
entries: vec![installed.clone(), other_installation.clone(), local.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let mut disabled = installed.clone();
|
||||
disabled.enabled = false;
|
||||
other_installation.enabled = false;
|
||||
let disabled_entries = vec![disabled, other_installation, local.clone()];
|
||||
assert_eq!(merge_catalogs(Some(&unmatched), /*cloud*/ None), unmatched);
|
||||
let explicitly_disabled = PluginCatalog {
|
||||
entries: disabled_entries.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&explicitly_disabled), /*cloud*/ None),
|
||||
explicitly_disabled,
|
||||
);
|
||||
for cloud in [
|
||||
Some(PluginCatalog::default()),
|
||||
Some(PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
] {
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&unmatched), cloud.as_ref()),
|
||||
PluginCatalog {
|
||||
entries: if cloud.as_ref().is_some_and(|catalog| catalog.is_partial) {
|
||||
unmatched.entries.clone()
|
||||
} else {
|
||||
disabled_entries.clone()
|
||||
},
|
||||
is_partial: cloud.as_ref().is_some_and(|catalog| catalog.is_partial),
|
||||
warnings: cloud.map(|catalog| catalog.warnings).unwrap_or_default(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let definition = cloud_plugin("plugin_a");
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(merge_catalogs(/*executor*/ None, Some(&cloud)), cloud);
|
||||
assert_eq!(
|
||||
merge_catalogs(/*executor*/ None, /*cloud*/ None),
|
||||
PluginCatalog::default(),
|
||||
);
|
||||
let mut authorized = definition.clone();
|
||||
authorized.locations.extend(installed.locations);
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![authorized, local.clone()],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
// Removing an installation preserves its Cloud definition without the executor route.
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&local_only), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![definition, local],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_cloud_merges_known_plugins_and_preserves_unmatched_enablement() -> anyhow::Result<()> {
|
||||
let definition = cloud_plugin("matched");
|
||||
let matched = executor_plugin("matched", "executor-a")?;
|
||||
let mut denied = executor_plugin("denied", "executor-a")?;
|
||||
denied.enabled = false;
|
||||
let unmatched = executor_plugin("unmatched", "executor-a")?;
|
||||
let executor = PluginCatalog {
|
||||
entries: vec![matched.clone(), denied.clone(), unmatched.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let cloud = PluginCatalog {
|
||||
entries: vec![definition.clone()],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut expected = definition;
|
||||
expected.locations.extend(matched.locations);
|
||||
assert_eq!(
|
||||
merge_catalogs(Some(&executor), Some(&cloud)),
|
||||
PluginCatalog {
|
||||
entries: vec![expected, denied, unmatched],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
438
codex-rs/core-plugins/src/command_migration.rs
Normal file
438
codex-rs/core-plugins/src/command_migration.rs
Normal file
@@ -0,0 +1,438 @@
|
||||
mod plugin;
|
||||
mod render;
|
||||
|
||||
use render::rewrite_terms;
|
||||
use render::slugify_name;
|
||||
use render::yaml_string;
|
||||
use serde_yaml::Value as YamlValue;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const COMMAND_SKILL_PREFIX: &str = "source-command";
|
||||
const MAX_SKILL_NAME_LEN: usize = 64;
|
||||
|
||||
pub(crate) use plugin::migrate_plugin_commands;
|
||||
|
||||
/// Describes source-specific terms that should be rewritten in migrated command skills.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RewriteProfile {
|
||||
doc_file_name: &'static str,
|
||||
term_variants: &'static [&'static str],
|
||||
case_sensitive_term_variants: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl RewriteProfile {
|
||||
pub const fn new(doc_file_name: &'static str, term_variants: &'static [&'static str]) -> Self {
|
||||
Self {
|
||||
doc_file_name,
|
||||
term_variants,
|
||||
case_sensitive_term_variants: &[],
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn with_case_sensitive_term_variants(
|
||||
mut self,
|
||||
term_variants: &'static [&'static str],
|
||||
) -> Self {
|
||||
self.case_sensitive_term_variants = term_variants;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls how migrated commands obtain the description required by a Codex skill.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CommandDescriptionMode {
|
||||
/// Skip source commands that do not declare a non-empty frontmatter description.
|
||||
RequireFrontmatter,
|
||||
/// Derive a stable description from the source command name when frontmatter is absent.
|
||||
UseSourceNameFallback,
|
||||
}
|
||||
|
||||
/// Describes source-specific command migration behavior.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CommandMigrationProfile {
|
||||
rewrite_profile: RewriteProfile,
|
||||
description_mode: CommandDescriptionMode,
|
||||
}
|
||||
|
||||
impl CommandMigrationProfile {
|
||||
pub const fn new(
|
||||
rewrite_profile: RewriteProfile,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
rewrite_profile,
|
||||
description_mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ParsedCommand {
|
||||
description: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct CommandSource {
|
||||
source_file: PathBuf,
|
||||
name: String,
|
||||
source_name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CommandSkillSizeLimit {
|
||||
Unbounded,
|
||||
MaxBytes(usize),
|
||||
}
|
||||
|
||||
pub fn count_missing_commands_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<usize> {
|
||||
Ok(missing_command_names_with_profile(source_commands, target_skills, profile)?.len())
|
||||
}
|
||||
|
||||
pub fn missing_command_names_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<Vec<String>> {
|
||||
Ok(
|
||||
unique_supported_command_sources(source_commands, profile.description_mode)?
|
||||
.into_iter()
|
||||
.filter(|source| !target_skills.join(&source.name).exists())
|
||||
.map(|source| source.name)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn import_commands_with_profile(
|
||||
source_commands: &Path,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
) -> io::Result<Vec<String>> {
|
||||
if !source_commands.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
fs::create_dir_all(target_skills)?;
|
||||
import_command_sources(
|
||||
unique_supported_command_sources(source_commands, profile.description_mode)?,
|
||||
target_skills,
|
||||
profile,
|
||||
CommandSkillSizeLimit::Unbounded,
|
||||
)
|
||||
}
|
||||
|
||||
fn import_command_sources(
|
||||
command_sources: Vec<CommandSource>,
|
||||
target_skills: &Path,
|
||||
profile: CommandMigrationProfile,
|
||||
size_limit: CommandSkillSizeLimit,
|
||||
) -> io::Result<Vec<String>> {
|
||||
if command_sources.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut imported = Vec::new();
|
||||
for CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
} in command_sources
|
||||
{
|
||||
let document = parse_command(&source_file)?;
|
||||
let target_dir = target_skills.join(&name);
|
||||
if target_dir.exists() {
|
||||
continue;
|
||||
}
|
||||
let Some(description) =
|
||||
command_skill_description(&document, &source_name, profile.description_mode)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let rendered = render_command_skill(
|
||||
&document.body,
|
||||
&name,
|
||||
&description,
|
||||
&source_name,
|
||||
profile.rewrite_profile,
|
||||
);
|
||||
if let CommandSkillSizeLimit::MaxBytes(max_bytes) = size_limit
|
||||
&& rendered.len() > max_bytes
|
||||
{
|
||||
continue;
|
||||
}
|
||||
fs::create_dir_all(&target_dir)?;
|
||||
fs::write(target_dir.join("SKILL.md"), rendered)?;
|
||||
imported.push(name);
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
fn unique_supported_command_sources(
|
||||
source_commands: &Path,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> io::Result<Vec<CommandSource>> {
|
||||
Ok(unique_command_sources(supported_command_sources(
|
||||
source_commands,
|
||||
description_mode,
|
||||
)?))
|
||||
}
|
||||
|
||||
fn supported_command_sources(
|
||||
source_commands: &Path,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> io::Result<Vec<CommandSource>> {
|
||||
let mut sources = Vec::new();
|
||||
for source_file in command_source_files(source_commands)? {
|
||||
let document = parse_command(&source_file)?;
|
||||
let source_name = command_source_name(source_commands, &source_file);
|
||||
let Some(name) = command_skill_name_if_supported(
|
||||
&source_name,
|
||||
&source_file,
|
||||
&document,
|
||||
description_mode,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
sources.push(CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
});
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
fn unique_command_sources(command_sources: Vec<CommandSource>) -> Vec<CommandSource> {
|
||||
let mut by_name = BTreeMap::<String, BTreeMap<PathBuf, String>>::new();
|
||||
for source in command_sources {
|
||||
by_name
|
||||
.entry(source.name)
|
||||
.or_default()
|
||||
.insert(source.source_file, source.source_name);
|
||||
}
|
||||
|
||||
by_name
|
||||
.into_iter()
|
||||
.filter_map(|(name, source_files)| {
|
||||
let mut source_files = source_files.into_iter();
|
||||
let (source_file, source_name) = source_files.next()?;
|
||||
if source_files.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(CommandSource {
|
||||
source_file,
|
||||
name,
|
||||
source_name,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn command_source_files(source_commands: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
if source_commands.is_file() {
|
||||
return Ok(
|
||||
if source_commands.extension().and_then(|ext| ext.to_str()) == Some("md") {
|
||||
vec![source_commands.to_path_buf()]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
collect_markdown_files(source_commands, &mut files)?;
|
||||
files.sort();
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collect_markdown_files(dir: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
|
||||
if !dir.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let file_type = entry.file_type()?;
|
||||
if file_type.is_dir() {
|
||||
collect_markdown_files(&path, files)?;
|
||||
} else if file_type.is_file() && path.extension().and_then(|ext| ext.to_str()) == Some("md")
|
||||
{
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_command(source_file: &Path) -> io::Result<ParsedCommand> {
|
||||
Ok(parse_command_content(&fs::read_to_string(source_file)?))
|
||||
}
|
||||
|
||||
fn parse_command_content(content: &str) -> ParsedCommand {
|
||||
let Some(rest) = content
|
||||
.strip_prefix("---\n")
|
||||
.or_else(|| content.strip_prefix("---\r\n"))
|
||||
else {
|
||||
return ParsedCommand {
|
||||
description: None,
|
||||
body: content.to_string(),
|
||||
};
|
||||
};
|
||||
let Some((end, body_start)) = frontmatter_end(rest) else {
|
||||
return ParsedCommand {
|
||||
description: None,
|
||||
body: content.to_string(),
|
||||
};
|
||||
};
|
||||
|
||||
ParsedCommand {
|
||||
description: parse_command_description(&rest[..end]),
|
||||
body: rest[body_start..].to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn frontmatter_end(rest: &str) -> Option<(usize, usize)> {
|
||||
[
|
||||
"\r\n---\r\n",
|
||||
"\r\n---\n",
|
||||
"\n---\r\n",
|
||||
"\n---\n",
|
||||
"\r\n---",
|
||||
"\n---",
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|delimiter| rest.find(delimiter).map(|end| (end, end + delimiter.len())))
|
||||
.min_by_key(|(end, _body_start)| *end)
|
||||
}
|
||||
|
||||
fn parse_command_description(raw_frontmatter: &str) -> Option<String> {
|
||||
let parsed: YamlValue = serde_yaml::from_str(raw_frontmatter).ok()?;
|
||||
let mapping = parsed.as_mapping()?;
|
||||
mapping.iter().find_map(|(key, value)| {
|
||||
if key.as_str()?.trim() == "description" {
|
||||
yaml_scalar(value)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn yaml_scalar(value: &YamlValue) -> Option<String> {
|
||||
match value {
|
||||
YamlValue::String(value) => Some(value.trim().to_string()),
|
||||
YamlValue::Bool(value) => Some(value.to_string()),
|
||||
YamlValue::Number(value) => Some(value.to_string()),
|
||||
YamlValue::Null | YamlValue::Sequence(_) | YamlValue::Mapping(_) | YamlValue::Tagged(_) => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn command_skill_name(source_name: &str) -> String {
|
||||
slugify_name(&format!("{COMMAND_SKILL_PREFIX}-{source_name}"))
|
||||
}
|
||||
|
||||
fn command_skill_name_if_supported(
|
||||
source_name: &str,
|
||||
source_file: &Path,
|
||||
document: &ParsedCommand,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Option<String> {
|
||||
if source_file.file_stem().and_then(|stem| stem.to_str()) == Some("README") {
|
||||
return None;
|
||||
}
|
||||
command_skill_description(document, source_name, description_mode)?;
|
||||
let name = command_skill_name(source_name);
|
||||
if name.chars().count() > MAX_SKILL_NAME_LEN
|
||||
|| has_unsupported_command_template_features(&document.body)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(name)
|
||||
}
|
||||
|
||||
fn command_skill_description(
|
||||
document: &ParsedCommand,
|
||||
source_name: &str,
|
||||
description_mode: CommandDescriptionMode,
|
||||
) -> Option<String> {
|
||||
document
|
||||
.description
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.or_else(|| match description_mode {
|
||||
CommandDescriptionMode::RequireFrontmatter => None,
|
||||
CommandDescriptionMode::UseSourceNameFallback => {
|
||||
Some(format!("Migrated source command `{source_name}`"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn command_source_name(source_commands: &Path, source_file: &Path) -> String {
|
||||
if source_commands.is_file() {
|
||||
return source_file
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
}
|
||||
source_file
|
||||
.strip_prefix(source_commands)
|
||||
.unwrap_or(source_file)
|
||||
.with_extension("")
|
||||
.components()
|
||||
.filter_map(|component| component.as_os_str().to_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-")
|
||||
}
|
||||
|
||||
fn render_command_skill(
|
||||
body: &str,
|
||||
name: &str,
|
||||
description: &str,
|
||||
source_name: &str,
|
||||
rewrite_profile: RewriteProfile,
|
||||
) -> String {
|
||||
let body = rewrite_terms(body.trim(), rewrite_profile);
|
||||
let template_body = if body.is_empty() {
|
||||
"No command template body was found.".to_string()
|
||||
} else {
|
||||
body
|
||||
};
|
||||
format!(
|
||||
"---\nname: {}\ndescription: {}\n---\n\n# {name}\n\nUse this skill when the user asks to run the migrated source command `{source_name}`.\n\n## Command Template\n\n{template_body}\n",
|
||||
yaml_string(name),
|
||||
yaml_string(&rewrite_terms(description, rewrite_profile)),
|
||||
)
|
||||
}
|
||||
|
||||
fn has_unsupported_command_template_features(template: &str) -> bool {
|
||||
template.contains("$ARGUMENTS")
|
||||
|| contains_numbered_argument_placeholder(template)
|
||||
|| (template.contains("{{") && template.contains("}}"))
|
||||
|| template.contains("!`")
|
||||
|| template.contains("! `")
|
||||
|| template
|
||||
.split_whitespace()
|
||||
.any(|token| token.strip_prefix('@').is_some_and(|rest| !rest.is_empty()))
|
||||
}
|
||||
|
||||
fn contains_numbered_argument_placeholder(template: &str) -> bool {
|
||||
let bytes = template.as_bytes();
|
||||
bytes
|
||||
.windows(2)
|
||||
.any(|window| window[0] == b'$' && window[1].is_ascii_digit())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "command_migration_tests.rs"]
|
||||
mod tests;
|
||||
53
codex-rs/core-plugins/src/command_migration/plugin.rs
Normal file
53
codex-rs/core-plugins/src/command_migration/plugin.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use super::CommandDescriptionMode;
|
||||
use super::CommandMigrationProfile;
|
||||
use super::CommandSkillSizeLimit;
|
||||
use super::CommandSource;
|
||||
use super::RewriteProfile;
|
||||
use super::import_command_sources;
|
||||
use super::supported_command_sources;
|
||||
use super::unique_command_sources;
|
||||
use crate::manifest::load_plugin_command_paths;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::migrated_command_skills_root;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
const PLUGIN_COMMANDS_DIR: &str = "commands";
|
||||
const MAX_MIGRATED_COMMAND_SKILL_BYTES: usize = 4_000;
|
||||
|
||||
const PLUGIN_REWRITE_PROFILE: RewriteProfile = RewriteProfile::new("AGENTS.md", &[]);
|
||||
const PLUGIN_MIGRATION_PROFILE: CommandMigrationProfile = CommandMigrationProfile::new(
|
||||
PLUGIN_REWRITE_PROFILE,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
);
|
||||
|
||||
pub(crate) fn migrate_plugin_commands(plugin_root: &Path) -> io::Result<()> {
|
||||
let absolute_plugin_root = AbsolutePathBuf::from_absolute_path(plugin_root)?;
|
||||
let target_skills = migrated_command_skills_root(&absolute_plugin_root);
|
||||
if target_skills.is_dir() {
|
||||
fs::remove_dir_all(&target_skills)?;
|
||||
} else if target_skills.exists() {
|
||||
fs::remove_file(&target_skills)?;
|
||||
}
|
||||
import_command_sources(
|
||||
plugin_command_sources(plugin_root)?,
|
||||
&target_skills,
|
||||
PLUGIN_MIGRATION_PROFILE,
|
||||
CommandSkillSizeLimit::MaxBytes(MAX_MIGRATED_COMMAND_SKILL_BYTES),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plugin_command_sources(plugin_root: &Path) -> io::Result<Vec<CommandSource>> {
|
||||
let command_paths = load_plugin_command_paths(plugin_root)?
|
||||
.unwrap_or_else(|| vec![plugin_root.join(PLUGIN_COMMANDS_DIR)]);
|
||||
let mut sources = Vec::new();
|
||||
for command_path in command_paths {
|
||||
sources.extend(supported_command_sources(
|
||||
&command_path,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)?);
|
||||
}
|
||||
Ok(unique_command_sources(sources))
|
||||
}
|
||||
95
codex-rs/core-plugins/src/command_migration/render.rs
Normal file
95
codex-rs/core-plugins/src/command_migration/render.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use super::RewriteProfile;
|
||||
|
||||
pub(super) fn rewrite_terms(content: &str, profile: RewriteProfile) -> String {
|
||||
let mut rewritten =
|
||||
replace_case_insensitive_with_boundaries(content, profile.doc_file_name, "AGENTS.md");
|
||||
for from in profile.term_variants {
|
||||
rewritten = replace_case_insensitive_with_boundaries(&rewritten, from, "Codex");
|
||||
}
|
||||
for from in profile.case_sensitive_term_variants {
|
||||
rewritten = replace_with_boundaries(&rewritten, from, "Codex");
|
||||
}
|
||||
rewritten
|
||||
}
|
||||
|
||||
fn replace_with_boundaries(input: &str, needle: &str, replacement: &str) -> String {
|
||||
if needle.is_empty() {
|
||||
return input.to_string();
|
||||
}
|
||||
|
||||
replace_with_boundaries_impl(input, needle, replacement, input)
|
||||
}
|
||||
|
||||
fn replace_case_insensitive_with_boundaries(
|
||||
input: &str,
|
||||
needle: &str,
|
||||
replacement: &str,
|
||||
) -> String {
|
||||
let needle_lower = needle.to_ascii_lowercase();
|
||||
if needle_lower.is_empty() {
|
||||
return input.to_string();
|
||||
}
|
||||
let haystack_lower = input.to_ascii_lowercase();
|
||||
replace_with_boundaries_impl(input, &needle_lower, replacement, &haystack_lower)
|
||||
}
|
||||
|
||||
fn replace_with_boundaries_impl(
|
||||
input: &str,
|
||||
needle: &str,
|
||||
replacement: &str,
|
||||
searchable_input: &str,
|
||||
) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut output = String::with_capacity(input.len());
|
||||
let mut last_emitted = 0usize;
|
||||
let mut search_start = 0usize;
|
||||
|
||||
while let Some(relative_pos) = searchable_input[search_start..].find(needle) {
|
||||
let start = search_start + relative_pos;
|
||||
let end = start + needle.len();
|
||||
let boundary_before = start == 0 || !is_word_byte(bytes[start - 1]);
|
||||
let boundary_after = end == bytes.len() || !is_word_byte(bytes[end]);
|
||||
|
||||
if boundary_before && boundary_after {
|
||||
output.push_str(&input[last_emitted..start]);
|
||||
output.push_str(replacement);
|
||||
last_emitted = end;
|
||||
}
|
||||
search_start = start + 1;
|
||||
}
|
||||
|
||||
if last_emitted == 0 {
|
||||
return input.to_string();
|
||||
}
|
||||
output.push_str(&input[last_emitted..]);
|
||||
output
|
||||
}
|
||||
|
||||
pub(super) fn yaml_string(value: &str) -> String {
|
||||
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
|
||||
}
|
||||
|
||||
pub(super) fn slugify_name(value: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut last_was_dash = false;
|
||||
for ch in value.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch.to_ascii_lowercase());
|
||||
last_was_dash = false;
|
||||
} else if !last_was_dash {
|
||||
slug.push('-');
|
||||
last_was_dash = true;
|
||||
}
|
||||
}
|
||||
|
||||
let slug = slug.trim_matches('-').to_string();
|
||||
if slug.is_empty() {
|
||||
"migrated".to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_'
|
||||
}
|
||||
146
codex-rs/core-plugins/src/command_migration_tests.rs
Normal file
146
codex-rs/core-plugins/src/command_migration_tests.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
const TEST_REWRITE_PROFILE: RewriteProfile = RewriteProfile::new(
|
||||
"CLAUDE.md",
|
||||
&[
|
||||
"claude code",
|
||||
"claude-code",
|
||||
"claude_code",
|
||||
"claudecode",
|
||||
"claude",
|
||||
],
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn command_skill_names_must_fit_codex_skill_loader_limit() {
|
||||
let source_name = "this-is-a-deeply-nested-command-with-a-very-long-name";
|
||||
let file = Path::new("commands/this/is/a/deeply/nested/command/with/a/very/long/name.md");
|
||||
let document = parse_command_content("---\ndescription: Review PR\n---\nReview\n");
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
source_name,
|
||||
file,
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_with_overlong_descriptions_are_preserved() {
|
||||
let description = "x".repeat(1025);
|
||||
let document =
|
||||
parse_command_content(&format!("---\ndescription: {description}\n---\nReview\n"));
|
||||
|
||||
assert_eq!(
|
||||
command_skill_name_if_supported(
|
||||
"review",
|
||||
Path::new("commands/review.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
),
|
||||
Some("source-command-review".to_string())
|
||||
);
|
||||
|
||||
let rendered = render_command_skill(
|
||||
&document.body,
|
||||
"source-command-review",
|
||||
&description,
|
||||
"review",
|
||||
TEST_REWRITE_PROFILE,
|
||||
);
|
||||
assert_eq!(
|
||||
parse_command_content(&rendered).description.as_deref(),
|
||||
Some(description.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_with_provider_runtime_expansion_are_skipped() {
|
||||
let document = parse_command_content(
|
||||
"---\ndescription: Deploy\n---\nDeploy $ARGUMENTS from @release.yaml\n",
|
||||
);
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
"deploy",
|
||||
Path::new("commands/deploy.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_without_description_are_skipped() {
|
||||
let document = parse_command_content("Review the current change.\n");
|
||||
|
||||
assert!(
|
||||
command_skill_name_if_supported(
|
||||
"review",
|
||||
Path::new("commands/review.md"),
|
||||
&document,
|
||||
CommandDescriptionMode::RequireFrontmatter,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_can_derive_descriptions_from_source_names() {
|
||||
let root = tempfile::TempDir::new().expect("tempdir");
|
||||
let commands = root.path().join("commands");
|
||||
let target_skills = root.path().join("skills");
|
||||
fs::create_dir_all(&commands).expect("create commands");
|
||||
fs::write(
|
||||
commands.join("review-code.md"),
|
||||
"Review the current change.\n",
|
||||
)
|
||||
.expect("write command");
|
||||
let profile = CommandMigrationProfile::new(
|
||||
TEST_REWRITE_PROFILE,
|
||||
CommandDescriptionMode::UseSourceNameFallback,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
import_commands_with_profile(&commands, &target_skills, profile).unwrap(),
|
||||
vec!["source-command-review-code".to_string()]
|
||||
);
|
||||
let rendered = fs::read_to_string(
|
||||
target_skills
|
||||
.join("source-command-review-code")
|
||||
.join("SKILL.md"),
|
||||
)
|
||||
.expect("read migrated command");
|
||||
assert!(rendered.contains("description: \"Migrated source command `review-code`\""));
|
||||
assert!(rendered.contains("Review the current change."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_slug_collisions_are_skipped() {
|
||||
let root = tempfile::TempDir::new().expect("tempdir");
|
||||
let commands = root.path().join("commands");
|
||||
fs::create_dir_all(&commands).expect("create commands");
|
||||
fs::write(
|
||||
commands.join("foo-bar.md"),
|
||||
"---\ndescription: First\n---\nRun the first command.\n",
|
||||
)
|
||||
.expect("write first command");
|
||||
fs::write(
|
||||
commands.join("foo_bar.md"),
|
||||
"---\ndescription: Second\n---\nRun the second command.\n",
|
||||
)
|
||||
.expect("write second command");
|
||||
|
||||
assert_eq!(
|
||||
unique_supported_command_sources(&commands, CommandDescriptionMode::RequireFrontmatter,)
|
||||
.unwrap(),
|
||||
Vec::<CommandSource>::new()
|
||||
);
|
||||
}
|
||||
231
codex-rs/core-plugins/src/discoverable.rs
Normal file
231
codex-rs/core-plugins/src/discoverable.rs
Normal file
@@ -0,0 +1,231 @@
|
||||
use anyhow::Context;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_config::skill_config_rules_from_stack;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::HashSet;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::marketplace::MarketplacePluginInstallPolicy;
|
||||
use crate::remote::InstalledPluginDisplayAssets;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
|
||||
const TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST: &[&str] = &[
|
||||
"github@openai-curated",
|
||||
"notion@openai-curated",
|
||||
"slack@openai-curated",
|
||||
"gmail@openai-curated",
|
||||
"google-calendar@openai-curated",
|
||||
"google-drive@openai-curated",
|
||||
"openai-developers@openai-curated",
|
||||
"canva@openai-curated",
|
||||
"teams@openai-curated",
|
||||
"sharepoint@openai-curated",
|
||||
"outlook-email@openai-curated",
|
||||
"outlook-calendar@openai-curated",
|
||||
"linear@openai-curated",
|
||||
"figma@openai-curated",
|
||||
"github@openai-curated-remote",
|
||||
"notion@openai-curated-remote",
|
||||
"slack@openai-curated-remote",
|
||||
"gmail@openai-curated-remote",
|
||||
"google-calendar@openai-curated-remote",
|
||||
"google-drive@openai-curated-remote",
|
||||
"openai-developers@openai-curated-remote",
|
||||
"canva@openai-curated-remote",
|
||||
"teams@openai-curated-remote",
|
||||
"sharepoint@openai-curated-remote",
|
||||
"outlook-email@openai-curated-remote",
|
||||
"outlook-calendar@openai-curated-remote",
|
||||
"linear@openai-curated-remote",
|
||||
"figma@openai-curated-remote",
|
||||
"chrome@openai-bundled",
|
||||
"computer-use@openai-bundled",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ToolSuggestPluginDiscoveryInput {
|
||||
pub plugins: PluginsConfigInput,
|
||||
pub configured_plugin_ids: HashSet<String>,
|
||||
pub disabled_plugin_ids: HashSet<String>,
|
||||
pub loaded_plugin_app_connector_ids: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolSuggestDiscoverablePlugin {
|
||||
pub id: String,
|
||||
pub remote_plugin_id: Option<String>,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub has_skills: bool,
|
||||
pub mcp_server_names: Vec<String>,
|
||||
pub app_connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl PluginsManager {
|
||||
pub async fn list_tool_suggest_discoverable_plugins(
|
||||
&self,
|
||||
input: &ToolSuggestPluginDiscoveryInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> anyhow::Result<Vec<ToolSuggestDiscoverablePlugin>> {
|
||||
if !input.plugins.plugins_enabled {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let use_remote_global_catalog =
|
||||
input.plugins.remote_plugin_enabled && auth.is_some_and(CodexAuth::uses_codex_backend);
|
||||
let marketplaces = self
|
||||
.list_marketplaces_for_config(
|
||||
&input.plugins,
|
||||
&[],
|
||||
/*include_openai_curated*/ !use_remote_global_catalog,
|
||||
)
|
||||
.context("failed to list plugin marketplaces for tool suggestions")?
|
||||
.marketplaces;
|
||||
let remote_installed_marketplaces = if use_remote_global_catalog {
|
||||
self.build_remote_installed_plugin_marketplaces_from_cache_with_display_assets(
|
||||
&[REMOTE_GLOBAL_MARKETPLACE_NAME],
|
||||
InstalledPluginDisplayAssets::Skip,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let skill_config_rules = skill_config_rules_from_stack(&input.plugins.config_layer_stack);
|
||||
|
||||
let mut discoverable_plugins = Vec::<ToolSuggestDiscoverablePlugin>::new();
|
||||
for marketplace in marketplaces {
|
||||
let marketplace_name = marketplace.name;
|
||||
|
||||
for plugin in marketplace.plugins {
|
||||
let is_configured_plugin = input.configured_plugin_ids.contains(plugin.id.as_str());
|
||||
let is_fallback_plugin = is_tool_suggest_fallback_plugin(&plugin.id);
|
||||
if plugin.installed
|
||||
|| plugin.policy.installation == MarketplacePluginInstallPolicy::NotAvailable
|
||||
|| input.disabled_plugin_ids.contains(plugin.id.as_str())
|
||||
|| (!is_configured_plugin && !is_fallback_plugin)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let plugin_id = plugin.id.clone();
|
||||
match self
|
||||
.tool_suggest_metadata_for_marketplace_plugin(
|
||||
&marketplace_name,
|
||||
&plugin,
|
||||
&skill_config_rules,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plugin) => {
|
||||
discoverable_plugins.push(ToolSuggestDiscoverablePlugin {
|
||||
id: plugin.config_name,
|
||||
remote_plugin_id: None,
|
||||
name: plugin.display_name,
|
||||
description: plugin.description,
|
||||
has_skills: plugin.has_skills,
|
||||
mcp_server_names: plugin.mcp_server_names,
|
||||
app_connector_ids: plugin
|
||||
.app_connector_ids
|
||||
.into_iter()
|
||||
.map(|connector_id| connector_id.0)
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("failed to load discoverable plugin suggestion {plugin_id}: {err:#}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(remote_installed_marketplaces) = remote_installed_marketplaces.as_ref() {
|
||||
let mut installed_app_connector_ids = self
|
||||
.plugins_for_config(&input.plugins)
|
||||
.await
|
||||
.capability_summaries()
|
||||
.iter()
|
||||
.flat_map(|plugin| plugin.app_connector_ids.iter())
|
||||
.map(|connector_id| connector_id.0.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
installed_app_connector_ids
|
||||
.extend(input.loaded_plugin_app_connector_ids.iter().cloned());
|
||||
let installed_remote_plugin_ids = remote_installed_marketplaces
|
||||
.iter()
|
||||
.flat_map(|marketplace| marketplace.plugins.iter())
|
||||
.map(|plugin| plugin.remote_plugin_id.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
for plugin in
|
||||
self.cached_global_remote_discoverable_plugins_for_config(&input.plugins, auth)
|
||||
{
|
||||
let is_configured_plugin = input
|
||||
.configured_plugin_ids
|
||||
.contains(plugin.config_id.as_str())
|
||||
|| input
|
||||
.configured_plugin_ids
|
||||
.contains(plugin.remote_plugin_id.as_str());
|
||||
let is_fallback_plugin = is_tool_suggest_fallback_plugin(&plugin.config_id);
|
||||
let matches_installed_app = plugin
|
||||
.app_ids
|
||||
.iter()
|
||||
.any(|app_id| installed_app_connector_ids.contains(app_id.as_str()));
|
||||
let is_disabled = input
|
||||
.disabled_plugin_ids
|
||||
.contains(plugin.config_id.as_str())
|
||||
|| input
|
||||
.disabled_plugin_ids
|
||||
.contains(plugin.remote_plugin_id.as_str());
|
||||
if installed_remote_plugin_ids.contains(&plugin.remote_plugin_id)
|
||||
|| plugin.install_policy == PluginInstallPolicy::NotAvailable
|
||||
|| plugin.availability == PluginAvailability::DisabledByAdmin
|
||||
|| is_disabled
|
||||
|| (!is_configured_plugin && !is_fallback_plugin && !matches_installed_app)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
discoverable_plugins.push(ToolSuggestDiscoverablePlugin {
|
||||
id: plugin.config_id,
|
||||
remote_plugin_id: Some(plugin.remote_plugin_id),
|
||||
name: plugin.name,
|
||||
description: plugin.description,
|
||||
has_skills: plugin.has_skills,
|
||||
mcp_server_names: Vec::new(),
|
||||
app_connector_ids: plugin.app_ids,
|
||||
});
|
||||
}
|
||||
}
|
||||
discoverable_plugins.sort_by(|left, right| {
|
||||
left.name
|
||||
.cmp(&right.name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
Ok(discoverable_plugins)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_tool_suggest_fallback_plugin(plugin_id: &str) -> bool {
|
||||
if TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST.contains(&plugin_id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_id) else {
|
||||
return false;
|
||||
};
|
||||
if plugin_id.marketplace_name != OPENAI_API_CURATED_MARKETPLACE_NAME {
|
||||
return false;
|
||||
}
|
||||
|
||||
let default_curated_plugin_id = format!(
|
||||
"{}@{}",
|
||||
plugin_id.plugin_name, OPENAI_CURATED_MARKETPLACE_NAME
|
||||
);
|
||||
TOOL_SUGGEST_DISCOVERABLE_PLUGIN_ALLOWLIST.contains(&default_curated_plugin_id.as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "discoverable_tests.rs"]
|
||||
mod tests;
|
||||
1135
codex-rs/core-plugins/src/discoverable_tests.rs
Normal file
1135
codex-rs/core-plugins/src/discoverable_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
13
codex-rs/core-plugins/src/error_subtype.rs
Normal file
13
codex-rs/core-plugins/src/error_subtype.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use http::StatusCode;
|
||||
|
||||
pub(crate) fn http_status_sub_error_type(status: StatusCode) -> &'static str {
|
||||
match status.as_u16() {
|
||||
401 => "http_401",
|
||||
403 => "http_403",
|
||||
404 => "http_404",
|
||||
409 => "http_409",
|
||||
429 => "http_429",
|
||||
_ if status.is_server_error() => "http_5xx",
|
||||
_ => "http_other",
|
||||
}
|
||||
}
|
||||
98
codex-rs/core-plugins/src/executor_catalog.rs
Normal file
98
codex-rs/core-plugins/src/executor_catalog.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! Converts V2 discovery contents to inert plugin catalogs without additional I/O.
|
||||
|
||||
use crate::PluginCatalog;
|
||||
use crate::PluginCatalogEntry;
|
||||
use crate::PluginIdentity;
|
||||
use crate::PluginSourceLocation;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::ExecutorPlugin;
|
||||
use codex_mcp::parse_plugin_mcp_declarations;
|
||||
|
||||
/// Projects V2 inventories into a plugin catalog without additional filesystem access.
|
||||
pub fn catalog_from_snapshots(
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
) -> PluginCatalog {
|
||||
let mut catalog = PluginCatalog::default();
|
||||
for snapshot in snapshots {
|
||||
let inventory = match &snapshot.result {
|
||||
Ok(inventory) => inventory,
|
||||
Err(error) => {
|
||||
catalog.is_partial = true;
|
||||
catalog.warnings.push(format!(
|
||||
"could not discover plugins in environment `{}`; skipping its plugin inventory: {error}",
|
||||
snapshot.environment_id
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
catalog.warnings.extend(inventory.warnings.iter().cloned());
|
||||
for plugin in &inventory.plugins {
|
||||
let (entry, warnings) = from_discovered_plugin(&snapshot.environment_id, plugin);
|
||||
catalog.entries.push(entry);
|
||||
catalog.warnings.extend(warnings);
|
||||
}
|
||||
}
|
||||
catalog
|
||||
}
|
||||
|
||||
fn from_discovered_plugin(
|
||||
environment_id: &str,
|
||||
plugin: &ExecutorPlugin,
|
||||
) -> (PluginCatalogEntry, Vec<String>) {
|
||||
let plugin_id = &plugin.id;
|
||||
let mut warnings = Vec::new();
|
||||
let mcp_servers = match plugin
|
||||
.files
|
||||
.mcp_config
|
||||
.as_ref()
|
||||
.map(|file| parse_plugin_mcp_declarations(&file.contents))
|
||||
{
|
||||
Some(Ok(servers)) => servers,
|
||||
Some(Err(error)) => {
|
||||
warnings.push(format!("plugin `{plugin_id}` MCP configuration: {error}"));
|
||||
Default::default()
|
||||
}
|
||||
None => Default::default(),
|
||||
};
|
||||
let connector_ids = match plugin
|
||||
.files
|
||||
.apps_config
|
||||
.as_ref()
|
||||
.map(|file| parse_plugin_app_config(&file.contents))
|
||||
{
|
||||
Some(Ok(apps)) => apps.into_iter().map(|app| app.connector_id.0).collect(),
|
||||
Some(Err(error)) => {
|
||||
warnings.push(format!("plugin `{plugin_id}` app configuration: {error}"));
|
||||
Vec::new()
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
(
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: match &plugin.remote_plugin_id {
|
||||
Some(remote_plugin_id) => PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_plugin_id.clone(),
|
||||
},
|
||||
None => PluginIdentity::Local {
|
||||
plugin_id: plugin.id.clone(),
|
||||
},
|
||||
},
|
||||
display_name: plugin.display_name.clone(),
|
||||
version: plugin.version.clone(),
|
||||
mcp_servers,
|
||||
connector_ids,
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: environment_id.to_string(),
|
||||
plugin_id: plugin_id.to_string(),
|
||||
root: plugin.root.clone(),
|
||||
}],
|
||||
},
|
||||
warnings,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_catalog_tests.rs"]
|
||||
mod tests;
|
||||
73
codex-rs/core-plugins/src/executor_catalog_tests.rs
Normal file
73
codex-rs/core-plugins/src/executor_catalog_tests.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Tests conversion of DiscoveryV2 payloads into inert plugin catalogs.
|
||||
|
||||
use super::catalog_from_snapshots;
|
||||
use crate::PluginCatalog;
|
||||
use crate::PluginCatalogEntry;
|
||||
use crate::PluginIdentity;
|
||||
use crate::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::ExecutorPlugin;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn discovered_mcp_contents_populate_catalog() -> anyhow::Result<()> {
|
||||
let root = PathUri::parse("file:///plugins/example/1.0.0")?;
|
||||
let manifest_path = root.join(".codex-plugin/plugin.json")?;
|
||||
let declarations = serde_json::json!({"example": {"command": "node"}});
|
||||
let snapshot = ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: Some("plugin_a".to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: manifest_path.clone(),
|
||||
contents: r#"{"name":"example"}"#.to_string(),
|
||||
},
|
||||
mcp_config: Some(CapabilityTextFile {
|
||||
path: manifest_path,
|
||||
contents: declarations.to_string(),
|
||||
}),
|
||||
apps_config: None,
|
||||
},
|
||||
root: root.clone(),
|
||||
skills: Vec::new(),
|
||||
}],
|
||||
..Default::default()
|
||||
})),
|
||||
};
|
||||
assert_eq!(
|
||||
catalog_from_snapshots(&[snapshot]),
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_a".to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command": "node"}),
|
||||
)]),
|
||||
connector_ids: Vec::new(),
|
||||
locations: vec![PluginSourceLocation::Executor {
|
||||
environment_id: "executor-a".to_string(),
|
||||
plugin_id: "example@marketplace".to_string(),
|
||||
root,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
192
codex-rs/core-plugins/src/executor_hooks.rs
Normal file
192
codex-rs/core-plugins/src/executor_hooks.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
//! Executor-discovered plugin hook admission and trusted MCP routing.
|
||||
|
||||
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
|
||||
use codex_config::HookHandlerConfig;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_mcp::ToolInfo;
|
||||
use codex_plugin::ExecutorPluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::is_allowlisted_bundled_cleanup_hook;
|
||||
use codex_plugin::manifest::PluginManifestHooks;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
|
||||
/// Returns accepted inline hook sources from executor-discovered plugin manifests.
|
||||
/// Each source carries its trusted MCP routing metadata. `lookup_enabled_tool` must use a
|
||||
/// consistent catalog/config snapshot, include app-only tools, and exclude tools disabled by
|
||||
/// app policy.
|
||||
///
|
||||
/// Executor scoped hooks are best-effort because executor capabilities can become available
|
||||
/// after earlier lifecycle events have passed.
|
||||
///
|
||||
/// Note: Executor manifests are not signed yet, so temporarily we only admit the known cleanup
|
||||
/// hooks from the bundled cleanup allowlist and the remote Browser plugin.
|
||||
pub fn executor_plugin_hook_sources<'a>(
|
||||
snapshot: &ExecutorCapabilityDiscoverySnapshot,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshot.roots().iter().filter_map(|entry| {
|
||||
let CapabilityRootLocation::Environment {
|
||||
environment_id,
|
||||
path: plugin_root,
|
||||
} = &entry.selected_root.location;
|
||||
let plugin = entry.result.as_ref().ok()?.plugin.as_ref()?;
|
||||
Some((
|
||||
entry.selected_root.id.as_str(),
|
||||
environment_id.as_str(),
|
||||
plugin_root,
|
||||
plugin,
|
||||
))
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config, lookup_enabled_tool)
|
||||
}
|
||||
|
||||
/// Applies the same inline-hook admission and MCP routing policy to V2 inventories.
|
||||
/// Callers must additionally restrict sources to their accepted plugin installations.
|
||||
pub fn executor_plugin_hook_sources_v2<'a>(
|
||||
snapshots: &[ExecutorCapabilityDiscoveryV2Snapshot],
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let plugins = snapshots.iter().flat_map(|snapshot| {
|
||||
snapshot.result.iter().flat_map(move |inventory| {
|
||||
inventory.plugins.iter().map(move |plugin| {
|
||||
(
|
||||
plugin.id.as_str(),
|
||||
snapshot.environment_id.as_str(),
|
||||
&plugin.root,
|
||||
&plugin.files,
|
||||
)
|
||||
})
|
||||
})
|
||||
});
|
||||
admitted_hook_sources(plugins, plugins_config, lookup_enabled_tool)
|
||||
}
|
||||
|
||||
fn admitted_hook_sources<'a, 'b>(
|
||||
plugins: impl Iterator<Item = (&'b str, &'b str, &'b PathUri, &'b DiscoveredPluginFiles)>,
|
||||
plugins_config: &PluginsConfigToml,
|
||||
lookup_enabled_tool: impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Vec<ExecutorPluginHookSource> {
|
||||
let mut sources = Vec::new();
|
||||
for (plugin_id, environment_id, plugin_root, plugin) in plugins {
|
||||
if !plugins_config.allows_plugin(plugin_id) {
|
||||
continue;
|
||||
}
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_id) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(manifest) = parse_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&plugin.manifest.path,
|
||||
&plugin.manifest.contents,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
// Only inline hooks are supported for now, so skip any other source types.
|
||||
let Some(PluginManifestHooks::Inline(hook_files)) = manifest.paths.hooks else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for (hook_index, hook_file) in hook_files.into_iter().enumerate() {
|
||||
let manifest_relative_path = plugin
|
||||
.manifest
|
||||
.path
|
||||
.relative_path_from(plugin_root)
|
||||
.unwrap_or_else(|| plugin.manifest.path.to_string());
|
||||
|
||||
sources.push(ExecutorPluginHookSource {
|
||||
plugin_id: plugin_id.clone(),
|
||||
environment_id: environment_id.to_string(),
|
||||
mcp_environment_id: None,
|
||||
mcp_metadata: None,
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: plugin.manifest.path.clone(),
|
||||
source_relative_path: format!("{manifest_relative_path}#hooks[{hook_index}]"),
|
||||
hooks: hook_file.hooks,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Remove this temporary filter once executor plugin hooks can be trusted.
|
||||
sources
|
||||
.into_iter()
|
||||
.filter_map(|mut source| {
|
||||
let plugin_id = source.plugin_id.as_key();
|
||||
for (event, groups) in source.hooks.matcher_groups_mut() {
|
||||
groups.retain_mut(|group| {
|
||||
group.hooks.retain(|handler| {
|
||||
let app_connector_id = match handler {
|
||||
HookHandlerConfig::McpTool { server, tool, .. }
|
||||
if server == CODEX_APPS_MCP_SERVER_NAME =>
|
||||
{
|
||||
lookup_enabled_tool(server, tool)
|
||||
.and_then(|info| info.connector_id.as_deref())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
is_allowlisted_bundled_cleanup_hook(
|
||||
&plugin_id,
|
||||
event,
|
||||
group.matcher.as_deref(),
|
||||
handler,
|
||||
app_connector_id,
|
||||
)
|
||||
});
|
||||
!group.hooks.is_empty()
|
||||
});
|
||||
}
|
||||
(!source.hooks.is_empty()).then_some(source)
|
||||
})
|
||||
.filter_map(|source| resolve_mcp_routing(source, &lookup_enabled_tool))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolves routing for an admitted MCP hook source.
|
||||
fn resolve_mcp_routing<'a>(
|
||||
mut source: ExecutorPluginHookSource,
|
||||
lookup_enabled_tool: &impl Fn(&str, &str) -> Option<&'a ToolInfo>,
|
||||
) -> Option<ExecutorPluginHookSource> {
|
||||
let HookHandlerConfig::McpTool { server, tool, .. } = source
|
||||
.hooks
|
||||
.matcher_groups_mut()
|
||||
.into_iter()
|
||||
.find_map(|(_, groups)| groups.first())?
|
||||
.hooks
|
||||
.first()?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if server != CODEX_APPS_MCP_SERVER_NAME {
|
||||
return Some(source);
|
||||
}
|
||||
|
||||
let tool_info = lookup_enabled_tool(server, tool)?;
|
||||
let routing_metadata = tool_info
|
||||
.tool
|
||||
.meta
|
||||
.as_ref()?
|
||||
.get(MCP_TOOL_CODEX_APPS_META_KEY)?
|
||||
.as_object()?;
|
||||
routing_metadata.get("resource_uri")?.as_str()?;
|
||||
source.mcp_environment_id = Some(DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
|
||||
source.mcp_metadata = Some(Map::from_iter([(
|
||||
MCP_TOOL_CODEX_APPS_META_KEY.to_string(),
|
||||
Value::Object(routing_metadata.clone()),
|
||||
)]));
|
||||
Some(source)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_hooks_tests.rs"]
|
||||
mod tests;
|
||||
557
codex-rs/core-plugins/src/executor_hooks_tests.rs
Normal file
557
codex-rs/core-plugins/src/executor_hooks_tests.rs
Normal file
@@ -0,0 +1,557 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_config::HookEventsToml;
|
||||
use codex_config::MatcherGroup;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoverySnapshot;
|
||||
use codex_plugin::ExecutorPluginHookSource;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn snapshot_for_manifest(
|
||||
plugin_id: &str,
|
||||
environment_id: &str,
|
||||
manifest_path: &str,
|
||||
manifest: serde_json::Value,
|
||||
) -> ExecutorCapabilityDiscoverySnapshot {
|
||||
let plugin_root = PathUri::parse("file:///plugins/computer-use").expect("plugin root");
|
||||
let manifest_path = PathUri::parse(manifest_path).expect("manifest path");
|
||||
let selected_root = SelectedCapabilityRoot {
|
||||
id: plugin_id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path: plugin_root.clone(),
|
||||
},
|
||||
};
|
||||
let discovery = CapabilityRootDiscovery {
|
||||
id: plugin_id.to_string(),
|
||||
path: plugin_root,
|
||||
plugin: Some(DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: manifest_path,
|
||||
contents: manifest.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
}),
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
ExecutorCapabilityDiscoverySnapshot::new(
|
||||
&[selected_root],
|
||||
vec![Ok(Arc::new(discovery))],
|
||||
HashMap::new(),
|
||||
)
|
||||
}
|
||||
|
||||
fn cleanup_hook_manifest() -> serde_json::Value {
|
||||
json!({
|
||||
"name": "computer-use",
|
||||
"hooks": {
|
||||
"hooks": {
|
||||
"Stop": [{
|
||||
"hooks": [{
|
||||
"type": "mcp_tool",
|
||||
"server": "node_repl",
|
||||
"tool": "turn_ended",
|
||||
"input": {
|
||||
"hook_event_name": "${hook_event_name}",
|
||||
"session_id": "${session_id}",
|
||||
"turn_id": "${turn_id}"
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_source(index: usize) -> ExecutorPluginHookSource {
|
||||
ExecutorPluginHookSource {
|
||||
plugin_id: PluginId::parse("computer-use@openai-bundled").expect("plugin id"),
|
||||
environment_id: "executor-a".to_string(),
|
||||
mcp_environment_id: None,
|
||||
mcp_metadata: None,
|
||||
plugin_root: PathUri::parse("file:///plugins/computer-use").expect("plugin root"),
|
||||
manifest_path: PathUri::parse("file:///plugins/computer-use/.codex-plugin/plugin.json")
|
||||
.expect("manifest path"),
|
||||
source_relative_path: format!(".codex-plugin/plugin.json#hooks[{index}]"),
|
||||
hooks: HookEventsToml {
|
||||
stop: vec![MatcherGroup {
|
||||
matcher: None,
|
||||
hooks: vec![HookHandlerConfig::McpTool {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "turn_ended".to_string(),
|
||||
input: serde_json::from_value(json!({
|
||||
"hook_event_name": "${hook_event_name}",
|
||||
"session_id": "${session_id}",
|
||||
"turn_id": "${turn_id}",
|
||||
}))
|
||||
.expect("executor hook input"),
|
||||
timeout_sec: None,
|
||||
status_message: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_allowlisted_executor_plugin_hook_sources() {
|
||||
let cleanup_hooks = cleanup_hook_manifest()["hooks"]["hooks"]["Stop"].clone();
|
||||
let manifest = json!({
|
||||
"name": "computer-use",
|
||||
"hooks": [
|
||||
{ "hooks": { "Stop": cleanup_hooks } },
|
||||
{ "hooks": { "Interrupt": cleanup_hooks } },
|
||||
{ "hooks": {
|
||||
"Stop": cleanup_hooks,
|
||||
"Interrupt": cleanup_hooks,
|
||||
"UserPromptSubmit": cleanup_hooks
|
||||
} },
|
||||
{ "hooks": { "UserPromptSubmit": cleanup_hooks } }
|
||||
]
|
||||
});
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
let sources =
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None);
|
||||
let mut interrupt_source = expected_source(/*index*/ 1);
|
||||
interrupt_source.hooks.interrupt = std::mem::take(&mut interrupt_source.hooks.stop);
|
||||
let mut stop_and_interrupt_source = expected_source(/*index*/ 2);
|
||||
stop_and_interrupt_source.hooks.interrupt = stop_and_interrupt_source.hooks.stop.clone();
|
||||
|
||||
assert_eq!(
|
||||
sources,
|
||||
vec![
|
||||
expected_source(/*index*/ 0),
|
||||
interrupt_source,
|
||||
stop_and_interrupt_source,
|
||||
]
|
||||
);
|
||||
for (config, expected) in [
|
||||
(
|
||||
"[_default]\nenabled = false\n[\"computer-use@other-marketplace\"]\nenabled = true",
|
||||
Vec::new(),
|
||||
),
|
||||
(
|
||||
"[_default]\nenabled = false\n[\"computer-use@openai-bundled\"]\nenabled = true",
|
||||
sources,
|
||||
),
|
||||
] {
|
||||
let config = toml::from_str(config).expect("plugin policy");
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &config, |_, _| None),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_unified_computer_use_cleanup_hooks() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["name"] = json!("unified-computer-use");
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0]["server"] = json!("cua_repl");
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"unified-computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.plugin_id = PluginId::parse("unified-computer-use@openai-bundled").expect("plugin id");
|
||||
let HookHandlerConfig::McpTool { server, .. } = &mut expected.hooks.stop[0].hooks[0] else {
|
||||
panic!("expected an MCP tool hook");
|
||||
};
|
||||
*server = "cua_repl".to_string();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_mixed_handlers_without_rewriting_allowed_groups() {
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
let mut second_handler = expected.hooks.stop[0].hooks[0].clone();
|
||||
let HookHandlerConfig::McpTool { input, .. } = &mut second_handler else {
|
||||
panic!("expected an MCP tool hook");
|
||||
};
|
||||
input.insert("order".to_string(), json!(2));
|
||||
expected.hooks.stop[0].hooks.push(second_handler.clone());
|
||||
expected.hooks.stop.push(MatcherGroup {
|
||||
matcher: None,
|
||||
hooks: vec![second_handler],
|
||||
});
|
||||
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["hooks"]["hooks"]["Stop"] =
|
||||
serde_json::to_value(&expected.hooks.stop).expect("serialize stop hooks");
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"]
|
||||
.as_array_mut()
|
||||
.expect("stop handlers")
|
||||
.insert(
|
||||
/*index*/ 0,
|
||||
json!({ "type": "mcp_tool", "server": "node_repl", "tool": "other" }),
|
||||
);
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_allowlisted_executor_plugin_hook_options() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
let handler = &mut manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0];
|
||||
handler["input"] = json!({ "untrusted": "manifest-provided input" });
|
||||
handler["timeout"] = json!(30);
|
||||
handler["statusMessage"] = json!("Cleaning up Computer Use");
|
||||
manifest["hooks"]["hooks"]["Interrupt"] = manifest["hooks"]["hooks"]["Stop"].clone();
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.hooks.stop[0].hooks[0] = HookHandlerConfig::McpTool {
|
||||
server: "node_repl".to_string(),
|
||||
tool: "turn_ended".to_string(),
|
||||
input: serde_json::from_value(json!({ "untrusted": "manifest-provided input" }))
|
||||
.expect("manifest-provided executor hook input"),
|
||||
timeout_sec: Some(30),
|
||||
status_message: Some("Cleaning up Computer Use".to_string()),
|
||||
};
|
||||
expected.hooks.interrupt = expected.hooks.stop.clone();
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
vec![expected]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_apps_hook_metadata_from_the_registered_connector() {
|
||||
let mut manifest = cleanup_hook_manifest();
|
||||
manifest["name"] = json!("browser");
|
||||
let handler = &mut manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0];
|
||||
handler["server"] = json!("codex_apps");
|
||||
handler["tool"] = json!("browser.turn_ended");
|
||||
handler["input"] = json!({});
|
||||
let mut expected = expected_source(/*index*/ 0);
|
||||
expected.plugin_id = PluginId::parse("browser@openai-curated-remote").expect("plugin id");
|
||||
expected.mcp_environment_id = Some(DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
|
||||
let routing = json!({
|
||||
"resource_uri": "/connector_openai_browser/browser-link/turn_ended",
|
||||
"contains_mcp_source": true,
|
||||
});
|
||||
expected.mcp_metadata = Some(Map::from_iter([(
|
||||
MCP_TOOL_CODEX_APPS_META_KEY.to_string(),
|
||||
routing.clone(),
|
||||
)]));
|
||||
|
||||
for (name, event, connector_id, input, routing_metadata, admitted) in [
|
||||
(
|
||||
"registered app",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"colliding tool name",
|
||||
"Stop",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"unavailable tool",
|
||||
"Stop",
|
||||
None,
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"registered subagent app",
|
||||
"SubagentStop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"registered interrupted app",
|
||||
"Interrupt",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"colliding interrupt tool name",
|
||||
"Interrupt",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"interrupt manifest arguments",
|
||||
"Interrupt",
|
||||
Some("connector_openai_browser"),
|
||||
json!({ "untrusted": "manifest-provided input" }),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"colliding subagent tool name",
|
||||
"SubagentStop",
|
||||
Some("connector_other_browser"),
|
||||
json!({}),
|
||||
routing.clone(),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"manifest arguments",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({ "untrusted": "manifest-provided input" }),
|
||||
routing,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"missing routing metadata",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
json!(null),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"invalid resource URI",
|
||||
"Stop",
|
||||
Some("connector_openai_browser"),
|
||||
json!({}),
|
||||
json!({ "resource_uri": 42 }),
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let mut manifest = manifest.clone();
|
||||
manifest["hooks"]["hooks"]["Stop"][0]["hooks"][0]["input"] = input;
|
||||
let events = manifest["hooks"]["hooks"]
|
||||
.as_object_mut()
|
||||
.expect("hook events");
|
||||
let groups = events.remove("Stop").expect("stop groups");
|
||||
events.insert(event.to_string(), groups);
|
||||
let mut expected = expected.clone();
|
||||
expected.hooks = serde_json::from_value(manifest["hooks"]["hooks"].clone()).expect("hooks");
|
||||
let snapshot = snapshot_for_manifest(
|
||||
"browser@openai-curated-remote",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
let tool_info = connector_id.map(|connector_id| {
|
||||
serde_json::from_value::<ToolInfo>(json!({
|
||||
"server_name": "codex_apps",
|
||||
"tool_name": "turn_ended",
|
||||
"tool_namespace": "browser",
|
||||
"connector_id": connector_id,
|
||||
"tool": {
|
||||
"name": "browser.turn_ended",
|
||||
"inputSchema": { "type": "object" },
|
||||
"_meta": { "_codex_apps": routing_metadata },
|
||||
},
|
||||
}))
|
||||
.expect("listed tool")
|
||||
});
|
||||
let actual = executor_plugin_hook_sources(
|
||||
&snapshot,
|
||||
&PluginsConfigToml::default(),
|
||||
|server, tool| {
|
||||
tool_info
|
||||
.as_ref()
|
||||
.filter(|info| info.server_name == server && info.tool.name == tool)
|
||||
},
|
||||
);
|
||||
let expected = if admitted {
|
||||
vec![expected.clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_unallowlisted_executor_plugin_hooks() {
|
||||
let mut wrong_event = cleanup_hook_manifest();
|
||||
let hook_events = wrong_event["hooks"]["hooks"]
|
||||
.as_object_mut()
|
||||
.expect("hook events");
|
||||
let stop_groups = hook_events.remove("Stop").expect("stop groups");
|
||||
hook_events.insert("SessionStart".to_string(), stop_groups);
|
||||
let mut wrong_handler = cleanup_hook_manifest();
|
||||
wrong_handler["hooks"]["hooks"]["Stop"][0]["hooks"][0] = json!({
|
||||
"type": "command",
|
||||
"command": "echo cleanup"
|
||||
});
|
||||
let mut wrong_server = cleanup_hook_manifest();
|
||||
wrong_server["hooks"]["hooks"]["Stop"][0]["hooks"][0]["server"] = json!("other");
|
||||
let mut wrong_tool = cleanup_hook_manifest();
|
||||
wrong_tool["hooks"]["hooks"]["Stop"][0]["hooks"][0]["tool"] = json!("other");
|
||||
let mut wrong_matcher = cleanup_hook_manifest();
|
||||
wrong_matcher["hooks"]["hooks"]["Stop"][0]["matcher"] = json!("unexpected");
|
||||
for (name, plugin_id, manifest) in [
|
||||
(
|
||||
"unallowlisted bundled plugin",
|
||||
"another-plugin@openai-bundled",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"wrong marketplace",
|
||||
"computer-use@other",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"bundled alpha marketplace",
|
||||
"computer-use@openai-bundled-alpha",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
(
|
||||
"bundled marketplace suffix",
|
||||
"computer-use@fake-openai-bundled",
|
||||
cleanup_hook_manifest(),
|
||||
),
|
||||
("wrong event", "computer-use@openai-bundled", wrong_event),
|
||||
(
|
||||
"wrong handler",
|
||||
"computer-use@openai-bundled",
|
||||
wrong_handler,
|
||||
),
|
||||
("wrong server", "computer-use@openai-bundled", wrong_server),
|
||||
("wrong tool", "computer-use@openai-bundled", wrong_tool),
|
||||
(
|
||||
"wrong matcher",
|
||||
"computer-use@openai-bundled",
|
||||
wrong_matcher,
|
||||
),
|
||||
] {
|
||||
let snapshot = snapshot_for_manifest(
|
||||
plugin_id,
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
manifest,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&snapshot, &PluginsConfigToml::default(), |_, _| None),
|
||||
Vec::<ExecutorPluginHookSource>::new(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_file_backed_executor_plugin_hooks() {
|
||||
let file_backed = snapshot_for_manifest(
|
||||
"computer-use@openai-bundled",
|
||||
"executor-a",
|
||||
"file:///plugins/computer-use/.codex-plugin/plugin.json",
|
||||
json!({
|
||||
"name": "computer-use",
|
||||
"hooks": "./hooks/hooks.json"
|
||||
}),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources(&file_backed, &PluginsConfigToml::default(), |_, _| None),
|
||||
Vec::<ExecutorPluginHookSource>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_hooks_preserve_admission_policy_and_environment_routing() {
|
||||
let manifest = cleanup_hook_manifest();
|
||||
let files = DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
path: PathUri::parse("file:///plugins/computer-use/.codex-plugin/plugin.json").unwrap(),
|
||||
contents: manifest.to_string(),
|
||||
},
|
||||
mcp_config: None,
|
||||
apps_config: None,
|
||||
};
|
||||
let plugin = codex_exec_server::ExecutorPlugin {
|
||||
id: "computer-use@openai-bundled".to_string(),
|
||||
display_name: "Computer use".to_string(),
|
||||
remote_plugin_id: None,
|
||||
version: "local".to_string(),
|
||||
root: PathUri::parse("file:///plugins/computer-use").unwrap(),
|
||||
files,
|
||||
skills: Vec::new(),
|
||||
};
|
||||
let mut untrusted = plugin.clone();
|
||||
untrusted.id = "computer-use@untrusted".to_string();
|
||||
let inventory = Arc::new(codex_exec_server::DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![plugin, untrusted],
|
||||
..Default::default()
|
||||
});
|
||||
let snapshots = [
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::clone(&inventory)),
|
||||
},
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-b".to_string(),
|
||||
result: Ok(inventory),
|
||||
},
|
||||
ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "failed".to_string(),
|
||||
result: Err("discovery failed".to_string()),
|
||||
},
|
||||
];
|
||||
let mut second = expected_source(/*index*/ 0);
|
||||
second.environment_id = "executor-b".to_string();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &PluginsConfigToml::default(), |_, _| None),
|
||||
vec![expected_source(/*index*/ 0), second]
|
||||
);
|
||||
let disabled = toml::from_str(
|
||||
"[_default]\nenabled = true\n[\"computer-use@openai-bundled\"]\nenabled = false",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
executor_plugin_hook_sources_v2(&snapshots, &disabled, |_, _| None),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
342
codex-rs/core-plugins/src/executor_provider.rs
Normal file
342
codex-rs/core-plugins/src/executor_provider.rs
Normal file
@@ -0,0 +1,342 @@
|
||||
//! Resolves selected plugin roots through their owning executor's filesystem.
|
||||
//! Resource locations retain that environment's authority.
|
||||
|
||||
use crate::PluginProvider;
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_plugin::ResolvedPlugin;
|
||||
use codex_plugin::ResolvedPluginError;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_path_uri::PathUriParseError;
|
||||
use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
use futures::StreamExt;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
const MAX_CONCURRENT_MANIFEST_PROBES: usize = 256;
|
||||
|
||||
/// Failure to resolve an environment-owned capability root as a plugin package.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ExecutorPluginProviderError {
|
||||
#[error("discovery failed for selected capability root `{root_id}`")]
|
||||
DiscoveryFailed { root_id: String },
|
||||
#[error(
|
||||
"selected capability root `{root_id}` references unavailable environment `{environment_id}`"
|
||||
)]
|
||||
UnavailableEnvironment {
|
||||
root_id: String,
|
||||
environment_id: String,
|
||||
},
|
||||
#[error("failed to inspect selected capability root `{root_id}` at {path}: {source}")]
|
||||
InspectRoot {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("selected capability root `{root_id}` path {path} is not a directory")]
|
||||
RootNotDirectory { root_id: String, path: PathUri },
|
||||
#[error(
|
||||
"failed to resolve plugin manifest path `{relative_path}` below selected capability root `{root_id}` at {root}: {source}"
|
||||
)]
|
||||
InvalidManifestPath {
|
||||
root_id: String,
|
||||
root: PathUri,
|
||||
relative_path: &'static str,
|
||||
#[source]
|
||||
source: PathUriParseError,
|
||||
},
|
||||
#[error("failed to inspect plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
InspectManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("failed to read plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
ReadManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
#[error("failed to parse plugin manifest for `{root_id}` at {path}: {source}")]
|
||||
ParseManifest {
|
||||
root_id: String,
|
||||
path: PathUri,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
#[error("failed to construct plugin descriptor for `{root_id}`: {source}")]
|
||||
ConstructDescriptor {
|
||||
root_id: String,
|
||||
#[source]
|
||||
source: ResolvedPluginError,
|
||||
},
|
||||
}
|
||||
|
||||
/// Resolves plugin packages through the filesystem owned by an execution environment.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExecutorPluginProvider {
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
}
|
||||
|
||||
/// Ownership of a selected root, independently of whether its manifest can be parsed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PluginRootOwnership {
|
||||
Plugin,
|
||||
Standalone,
|
||||
}
|
||||
|
||||
/// A resolved plugin paired with the concrete filesystem used to read it.
|
||||
#[derive(Clone)]
|
||||
pub struct ResolvedExecutorPlugin {
|
||||
plugin: ResolvedPlugin,
|
||||
file_system: Arc<dyn ExecutorFileSystem>,
|
||||
}
|
||||
|
||||
impl ResolvedExecutorPlugin {
|
||||
/// Returns the source-neutral plugin descriptor.
|
||||
pub fn plugin(&self) -> &ResolvedPlugin {
|
||||
&self.plugin
|
||||
}
|
||||
|
||||
/// Returns the concrete filesystem that resolved the descriptor.
|
||||
pub fn file_system(&self) -> &dyn ExecutorFileSystem {
|
||||
self.file_system.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorPluginProvider {
|
||||
/// Creates a provider backed by the active execution environments.
|
||||
pub fn new(environment_manager: Arc<EnvironmentManager>) -> Self {
|
||||
Self {
|
||||
environment_manager,
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies ownership before capability parsing. Failed discovery or metadata
|
||||
/// access returns an error, not evidence that a root is standalone.
|
||||
pub async fn root_ownership(
|
||||
&self,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
discovery: Option<&CapabilityRootDiscovery>,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> Result<PluginRootOwnership, ExecutorPluginProviderError> {
|
||||
let CapabilityRootLocation::Environment {
|
||||
environment_id,
|
||||
path,
|
||||
} = &selected_root.location;
|
||||
if let Some(discovery) = discovery {
|
||||
if discovery.error.is_some() {
|
||||
return Err(ExecutorPluginProviderError::DiscoveryFailed {
|
||||
root_id: selected_root.id.clone(),
|
||||
});
|
||||
}
|
||||
if discovery.plugin.is_some()
|
||||
|| discovery.namespace_manifests.iter().any(|manifest| {
|
||||
manifest
|
||||
.path
|
||||
.parent()
|
||||
.and_then(|directory| directory.parent())
|
||||
.is_some_and(|plugin_root| path.starts_with(&plugin_root))
|
||||
})
|
||||
{
|
||||
return Ok(PluginRootOwnership::Plugin);
|
||||
}
|
||||
if discovery.warnings.is_empty() {
|
||||
return Ok(PluginRootOwnership::Standalone);
|
||||
}
|
||||
}
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(environment_id)
|
||||
.ok_or_else(|| ExecutorPluginProviderError::UnavailableEnvironment {
|
||||
root_id: selected_root.id.clone(),
|
||||
environment_id: environment_id.clone(),
|
||||
})?;
|
||||
let file_system = environment.get_filesystem();
|
||||
let manifest = find_manifest(
|
||||
selected_root,
|
||||
std::iter::successors(Some(path.clone()), PathUri::parent),
|
||||
file_system.as_ref(),
|
||||
sandbox,
|
||||
)
|
||||
.await?;
|
||||
Ok(if manifest.is_some() {
|
||||
PluginRootOwnership::Plugin
|
||||
} else {
|
||||
PluginRootOwnership::Standalone
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves a plugin and retains the exact filesystem used for package access.
|
||||
#[tracing::instrument(name = "plugins.executor.package.resolve", skip_all)]
|
||||
pub async fn resolve_bound(
|
||||
&self,
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
) -> Result<Option<ResolvedExecutorPlugin>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let plugin_root = selected_plugin_root(selected_root);
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let environment = self
|
||||
.environment_manager
|
||||
.get_environment(environment_id)
|
||||
.ok_or_else(|| ExecutorPluginProviderError::UnavailableEnvironment {
|
||||
root_id: root_id.clone(),
|
||||
environment_id: environment_id.clone(),
|
||||
})?;
|
||||
let file_system = environment.get_filesystem();
|
||||
let plugin = resolve_plugin_root(selected_root, plugin_root, file_system.as_ref()).await?;
|
||||
|
||||
Ok(plugin.map(|plugin| ResolvedExecutorPlugin {
|
||||
plugin,
|
||||
file_system,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginProvider for ExecutorPluginProvider {}
|
||||
|
||||
fn selected_plugin_root(selected_root: &SelectedCapabilityRoot) -> PathUri {
|
||||
let CapabilityRootLocation::Environment { path, .. } = &selected_root.location;
|
||||
path.clone()
|
||||
}
|
||||
|
||||
async fn resolve_plugin_root(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
plugin_root: PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Result<Option<ResolvedPlugin>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
|
||||
let root_metadata = file_system
|
||||
.get_metadata(
|
||||
&plugin_root,
|
||||
GetMetadataOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| ExecutorPluginProviderError::InspectRoot {
|
||||
root_id: root_id.clone(),
|
||||
path: plugin_root.clone(),
|
||||
source,
|
||||
})?;
|
||||
if !root_metadata.is_directory {
|
||||
return Err(ExecutorPluginProviderError::RootNotDirectory {
|
||||
root_id: root_id.clone(),
|
||||
path: plugin_root,
|
||||
});
|
||||
}
|
||||
|
||||
let Some(manifest_uri) = find_manifest(
|
||||
selected_root,
|
||||
std::iter::once(plugin_root.clone()),
|
||||
file_system,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let contents = file_system
|
||||
.read_file_text(
|
||||
&manifest_uri,
|
||||
ReadFileOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| ExecutorPluginProviderError::ReadManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: manifest_uri.clone(),
|
||||
source,
|
||||
})?;
|
||||
let manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_uri, &contents).map_err(|source| {
|
||||
ExecutorPluginProviderError::ParseManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: manifest_uri.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
let plugin = ResolvedPlugin::from_environment(
|
||||
root_id.clone(),
|
||||
environment_id.clone(),
|
||||
plugin_root,
|
||||
manifest_uri,
|
||||
manifest,
|
||||
)
|
||||
.map_err(|source| ExecutorPluginProviderError::ConstructDescriptor {
|
||||
root_id: root_id.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
Ok(Some(plugin))
|
||||
}
|
||||
|
||||
async fn find_manifest(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
mut plugin_roots: impl Iterator<Item = PathUri> + Send,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
sandbox: Option<&FileSystemSandboxContext>,
|
||||
) -> Result<Option<PathUri>, ExecutorPluginProviderError> {
|
||||
let root_id = &selected_root.id;
|
||||
let mut plugin_root = plugin_roots.next();
|
||||
let mut marker_index = 0;
|
||||
let probes = std::iter::from_fn(move || {
|
||||
let root = plugin_root.clone()?;
|
||||
let relative_path = *DISCOVERABLE_PLUGIN_MANIFEST_PATHS.get(marker_index)?;
|
||||
let candidate_uri = root.join(relative_path).map_err(|source| {
|
||||
ExecutorPluginProviderError::InvalidManifestPath {
|
||||
root_id: root_id.clone(),
|
||||
root,
|
||||
relative_path,
|
||||
source,
|
||||
}
|
||||
});
|
||||
marker_index += 1;
|
||||
if marker_index == DISCOVERABLE_PLUGIN_MANIFEST_PATHS.len() {
|
||||
marker_index = 0;
|
||||
plugin_root = plugin_roots.next();
|
||||
}
|
||||
Some(candidate_uri)
|
||||
});
|
||||
// Pipeline remote metadata calls while consuming results in ancestor/manifest priority order.
|
||||
let mut results = futures::stream::iter(probes)
|
||||
.map(|candidate_uri| async move {
|
||||
let candidate_uri = candidate_uri?;
|
||||
match file_system
|
||||
.get_metadata(&candidate_uri, GetMetadataOptions::default(), sandbox)
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_file => Ok(Some(candidate_uri)),
|
||||
Ok(_) => Ok(None),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Err(source) => Err(ExecutorPluginProviderError::InspectManifest {
|
||||
root_id: root_id.clone(),
|
||||
path: candidate_uri,
|
||||
source,
|
||||
}),
|
||||
}
|
||||
})
|
||||
.buffered(MAX_CONCURRENT_MANIFEST_PROBES);
|
||||
while let Some(result) = results.next().await {
|
||||
if let Some(manifest) = result? {
|
||||
return Ok(Some(manifest));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "executor_provider_tests.rs"]
|
||||
mod tests;
|
||||
657
codex-rs/core-plugins/src/executor_provider_tests.rs
Normal file
657
codex-rs/core-plugins/src/executor_provider_tests.rs
Normal file
@@ -0,0 +1,657 @@
|
||||
use super::ExecutorPluginProvider;
|
||||
use super::ExecutorPluginProviderError;
|
||||
use super::PluginRootOwnership;
|
||||
use super::find_manifest;
|
||||
use super::resolve_plugin_root;
|
||||
use crate::manifest::parse_plugin_manifest_uri;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::CopyOptions;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::ExecutorFileSystemFuture;
|
||||
use codex_exec_server::FileMetadata;
|
||||
use codex_exec_server::FileSystemReadStream;
|
||||
use codex_exec_server::FileSystemResult;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_exec_server::ReadDirectoryEntry;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_exec_server::WalkOptions;
|
||||
use codex_exec_server::WalkOutcome;
|
||||
use codex_exec_server::WriteFileOptions;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_plugin::ResolvedPlugin;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const MANIFEST_CONTENTS: &str = r#"{
|
||||
"name": "demo-plugin",
|
||||
"version": " 1.2.3 ",
|
||||
"description": "Demo plugin",
|
||||
"skills": "./skills",
|
||||
"mcpServers": "./.mcp.json",
|
||||
"apps": "./.app.json",
|
||||
"interface": {
|
||||
"displayName": "Demo Plugin",
|
||||
"composerIcon": "./assets/icon.svg"
|
||||
}
|
||||
}"#;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum FileSystemCall {
|
||||
Metadata(PathUri),
|
||||
SandboxedMetadata {
|
||||
path: PathUri,
|
||||
sandbox: Box<FileSystemSandboxContext>,
|
||||
},
|
||||
Read(PathUri),
|
||||
}
|
||||
|
||||
struct SyntheticPluginFileSystem {
|
||||
plugin_root: PathUri,
|
||||
manifest_path: PathUri,
|
||||
calls: Mutex<Vec<FileSystemCall>>,
|
||||
metadata_gate: Option<Arc<Semaphore>>,
|
||||
metadata_delay: Option<(PathUri, Arc<Semaphore>)>,
|
||||
metadata_error: Option<PathUri>,
|
||||
}
|
||||
|
||||
impl SyntheticPluginFileSystem {
|
||||
fn unsupported<T>() -> FileSystemResult<T> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"operation is not used by plugin resolution",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorFileSystem for SyntheticPluginFileSystem {
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
_options: ReadFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
Box::pin(async move {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(FileSystemCall::Read(path.clone()));
|
||||
if path == &self.manifest_path {
|
||||
Ok(MANIFEST_CONTENTS.as_bytes().to_vec())
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn read_file_stream<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_contents: Vec<u8>,
|
||||
_options: WriteFileOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: CreateDirectoryOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
_options: GetMetadataOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
Box::pin(async move {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(match sandbox {
|
||||
Some(sandbox) => FileSystemCall::SandboxedMetadata {
|
||||
path: path.clone(),
|
||||
sandbox: Box::new(sandbox.clone()),
|
||||
},
|
||||
None => FileSystemCall::Metadata(path.clone()),
|
||||
});
|
||||
if let Some(gate) = &self.metadata_gate {
|
||||
gate.acquire().await.expect("open metadata gate").forget();
|
||||
}
|
||||
if let Some((delayed_path, gate)) = &self.metadata_delay
|
||||
&& delayed_path == path
|
||||
{
|
||||
gate.acquire().await.expect("open delayed gate").forget();
|
||||
}
|
||||
if self.metadata_error.as_ref() == Some(path) {
|
||||
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
|
||||
}
|
||||
let (is_directory, is_file) = if path == &self.plugin_root {
|
||||
(true, false)
|
||||
} else if path == &self.manifest_path {
|
||||
(false, true)
|
||||
} else {
|
||||
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"));
|
||||
};
|
||||
Ok(FileMetadata {
|
||||
is_directory,
|
||||
is_file,
|
||||
is_symlink: false,
|
||||
size: 0,
|
||||
created_at_ms: 0,
|
||||
modified_at_ms: 0,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn walk<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: WalkOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, WalkOutcome> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
_path: &'a PathUri,
|
||||
_options: RemoveOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
_source_path: &'a PathUri,
|
||||
_destination_path: &'a PathUri,
|
||||
_options: CopyOptions,
|
||||
_sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(async { Self::unsupported() })
|
||||
}
|
||||
}
|
||||
|
||||
fn write_manifest(plugin_root: &Path, relative_path: &str, contents: &str) {
|
||||
let manifest_path = plugin_root.join(relative_path);
|
||||
fs::create_dir_all(manifest_path.parent().expect("manifest parent"))
|
||||
.expect("create manifest parent");
|
||||
fs::write(manifest_path, contents).expect("write manifest");
|
||||
}
|
||||
|
||||
fn selected_root(id: &str, environment_id: &str, path: &Path) -> SelectedCapabilityRoot {
|
||||
SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path: PathUri::from_host_native_path(path).expect("path URI"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_root_uri(id: &str, environment_id: &str, path: PathUri) -> SelectedCapabilityRoot {
|
||||
SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_ownership_survives_malformed_ancestor_manifests() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let root = directory.path().join("package/skills");
|
||||
fs::create_dir_all(&root).expect("create skills root");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
let selected = selected_root("example@marketplace", LOCAL_ENVIRONMENT_ID, &root);
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Standalone
|
||||
);
|
||||
write_manifest(
|
||||
root.parent().unwrap(),
|
||||
".codex-plugin/plugin.json",
|
||||
"{broken",
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
let mut discovery = CapabilityRootDiscovery {
|
||||
id: selected.id.clone(),
|
||||
path: PathUri::from_host_native_path(&root).unwrap(),
|
||||
plugin: None,
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: Vec::new(),
|
||||
warnings: vec!["unreadable manifest".into()],
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
discovery.error = Some("discovery failed".into());
|
||||
assert!(matches!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await,
|
||||
Err(ExecutorPluginProviderError::DiscoveryFailed { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovery_ownership_uses_ancestors_not_nested_plugins() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let path = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let selected = selected_root_uri("example@marketplace", "executor", path.clone());
|
||||
let provider =
|
||||
ExecutorPluginProvider::new(Arc::new(environment_manager_without_environments()));
|
||||
let mut discovery = CapabilityRootDiscovery {
|
||||
id: selected.id.clone(),
|
||||
path: path.clone(),
|
||||
plugin: None,
|
||||
skills: Vec::new(),
|
||||
namespace_manifests: vec![CapabilityTextFile {
|
||||
path: path.join("nested/.codex-plugin/plugin.json").unwrap(),
|
||||
contents: "{broken".into(),
|
||||
}],
|
||||
warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Standalone
|
||||
);
|
||||
discovery.namespace_manifests[0].path = path.join(".codex-plugin/plugin.json").unwrap();
|
||||
assert_eq!(
|
||||
provider
|
||||
.root_ownership(&selected, Some(&discovery), /*sandbox*/ None)
|
||||
.await
|
||||
.unwrap(),
|
||||
PluginRootOwnership::Plugin
|
||||
);
|
||||
assert!(matches!(
|
||||
provider
|
||||
.root_ownership(&selected, /*discovery*/ None, /*sandbox*/ None)
|
||||
.await,
|
||||
Err(ExecutorPluginProviderError::UnavailableEnvironment { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ancestor_manifest_probes_pipeline_and_preserve_error_order() {
|
||||
let root = PathUri::parse("file:///a/b/c/d/e/f").expect("selected root URI");
|
||||
let owner = PathUri::parse("file:///a/b/c").expect("owner URI");
|
||||
let manifest = owner.join(".codex-plugin/plugin.json").unwrap();
|
||||
let earlier_error = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let later_error = owner.join(".claude-plugin/plugin.json").unwrap();
|
||||
let expected_probes = std::iter::successors(Some(root.clone()), PathUri::parent)
|
||||
.flat_map(|ancestor| {
|
||||
DISCOVERABLE_PLUGIN_MANIFEST_PATHS
|
||||
.iter()
|
||||
.map(move |marker| ancestor.join(marker).unwrap())
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for (metadata_error, expected) in [
|
||||
(None, Ok(Some(manifest.clone()))),
|
||||
(
|
||||
Some(earlier_error.clone()),
|
||||
Err((earlier_error.clone(), io::ErrorKind::PermissionDenied)),
|
||||
),
|
||||
(Some(later_error), Ok(Some(manifest.clone()))),
|
||||
] {
|
||||
let gate = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let earliest_gate = Arc::new(Semaphore::new(/*permits*/ 0));
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
// A directory named like a manifest must not count as plugin ownership.
|
||||
plugin_root: earlier_error.clone(),
|
||||
manifest_path: manifest.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: Some(Arc::clone(&gate)),
|
||||
metadata_delay: Some((earlier_error.clone(), Arc::clone(&earliest_gate))),
|
||||
metadata_error,
|
||||
};
|
||||
let selected = selected_root_uri("example@marketplace", "executor", root.clone());
|
||||
let mut resolution = Box::pin(find_manifest(
|
||||
&selected,
|
||||
std::iter::successors(Some(root.clone()), PathUri::parent),
|
||||
&file_system,
|
||||
/*sandbox*/ None,
|
||||
));
|
||||
assert!(futures::poll!(resolution.as_mut()).is_pending());
|
||||
let probes = file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.iter()
|
||||
.map(|call| match call {
|
||||
FileSystemCall::Metadata(path) => path.clone(),
|
||||
call => panic!("unexpected filesystem call: {call:?}"),
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
assert_eq!(probes, expected_probes);
|
||||
gate.add_permits(probes.len());
|
||||
// Later successes/errors cannot outrank the earliest still-pending candidate.
|
||||
assert!(futures::poll!(resolution.as_mut()).is_pending());
|
||||
earliest_gate.add_permits(/*n*/ 1);
|
||||
let result = resolution.await.map_err(|error| {
|
||||
let ExecutorPluginProviderError::InspectManifest { path, source, .. } = error else {
|
||||
panic!("unexpected manifest resolution error: {error}");
|
||||
};
|
||||
(path, source.kind())
|
||||
});
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manifest_presence_uses_sandboxed_metadata_without_reading_contents() {
|
||||
let directory = tempdir().expect("tempdir");
|
||||
let plugin_root = PathUri::from_host_native_path(directory.path()).expect("root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let sandbox =
|
||||
FileSystemSandboxContext::from_permission_profile(Default::default(), plugin_root.clone());
|
||||
assert_eq!(
|
||||
find_manifest(
|
||||
&selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
|
||||
std::iter::once(plugin_root.clone()),
|
||||
&file_system,
|
||||
Some(&sandbox),
|
||||
)
|
||||
.await
|
||||
.expect("probe manifest"),
|
||||
Some(manifest_path.clone()),
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![FileSystemCall::SandboxedMetadata {
|
||||
path: manifest_path,
|
||||
sandbox: Box::new(sandbox)
|
||||
}],
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_resolution_uses_supplied_executor_file_system() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("executor-only-plugin");
|
||||
assert!(!plugin_root.exists());
|
||||
let plugin_root = PathUri::from_host_native_path(&plugin_root).expect("plugin root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let parsed_manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
|
||||
.expect("parse manifest");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let resolved = resolve_plugin_root(
|
||||
&selected_root_uri("selected-demo", "executor-test", plugin_root.clone()),
|
||||
plugin_root.clone(),
|
||||
&file_system,
|
||||
)
|
||||
.await
|
||||
.expect("resolve executor plugin");
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
Some(
|
||||
ResolvedPlugin::from_environment(
|
||||
"selected-demo".to_string(),
|
||||
"executor-test".to_string(),
|
||||
plugin_root.clone(),
|
||||
manifest_path.clone(),
|
||||
parsed_manifest,
|
||||
)
|
||||
.expect("valid expected descriptor")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
FileSystemCall::Metadata(plugin_root),
|
||||
FileSystemCall::Metadata(manifest_path.clone()),
|
||||
FileSystemCall::Read(manifest_path),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_root_resolution_accepts_foreign_executor_file_uri() {
|
||||
let plugin_root = PathUri::parse("file:///C:/plugins/foo").expect("Windows plugin root URI");
|
||||
let manifest_path = plugin_root
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.expect("manifest URI");
|
||||
let parsed_manifest =
|
||||
parse_plugin_manifest_uri(&plugin_root, &manifest_path, MANIFEST_CONTENTS)
|
||||
.expect("parse manifest");
|
||||
let file_system = SyntheticPluginFileSystem {
|
||||
plugin_root: plugin_root.clone(),
|
||||
manifest_path: manifest_path.clone(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
metadata_gate: None,
|
||||
metadata_delay: None,
|
||||
metadata_error: None,
|
||||
};
|
||||
let selected_root = selected_root_uri("selected-demo", "executor-test", plugin_root.clone());
|
||||
let resolved = resolve_plugin_root(&selected_root, plugin_root.clone(), &file_system)
|
||||
.await
|
||||
.expect("resolve executor plugin");
|
||||
|
||||
assert_eq!(
|
||||
resolved,
|
||||
Some(
|
||||
ResolvedPlugin::from_environment(
|
||||
"selected-demo".to_string(),
|
||||
"executor-test".to_string(),
|
||||
plugin_root.clone(),
|
||||
manifest_path.clone(),
|
||||
parsed_manifest,
|
||||
)
|
||||
.expect("valid expected descriptor")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
*file_system
|
||||
.calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
FileSystemCall::Metadata(plugin_root),
|
||||
FileSystemCall::Metadata(manifest_path.clone()),
|
||||
FileSystemCall::Read(manifest_path),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn standalone_capability_root_is_not_a_plugin() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let standalone_root = temp_dir.path().join("standalone-skill");
|
||||
fs::create_dir_all(&standalone_root).expect("create standalone root");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let resolved = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"standalone",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&standalone_root,
|
||||
))
|
||||
.await
|
||||
.expect("resolve standalone root");
|
||||
|
||||
assert!(resolved.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn root_agent_plugin_manifest_is_not_an_executor_plugin() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("agent-plugin");
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
"plugin.json",
|
||||
r#"{
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
||||
"name": "agent-plugin",
|
||||
"version": "1.0.0"
|
||||
}"#,
|
||||
);
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let resolved = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"agent-plugin",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&plugin_root,
|
||||
))
|
||||
.await
|
||||
.expect("resolve selected root");
|
||||
|
||||
assert!(resolved.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_environment_does_not_fall_back_to_host_filesystem() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("host-plugin");
|
||||
write_manifest(&plugin_root, ".codex-plugin/plugin.json", MANIFEST_CONTENTS);
|
||||
let provider =
|
||||
ExecutorPluginProvider::new(Arc::new(environment_manager_without_environments()));
|
||||
|
||||
let err = provider
|
||||
.resolve_bound(&selected_root("host-plugin", "missing", &plugin_root))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.expect_err("missing environment should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"selected capability root `host-plugin` references unavailable environment `missing`"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_preferred_manifest_does_not_fall_through_to_alternate() {
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let plugin_root = temp_dir.path().join("demo-plugin");
|
||||
write_manifest(&plugin_root, ".codex-plugin/plugin.json", "{not-json");
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
".claude-plugin/plugin.json",
|
||||
MANIFEST_CONTENTS,
|
||||
);
|
||||
let expected_path =
|
||||
PathUri::from_host_native_path(plugin_root.join(".codex-plugin/plugin.json"))
|
||||
.expect("manifest URI");
|
||||
let provider = ExecutorPluginProvider::new(Arc::new(EnvironmentManager::default_for_tests()));
|
||||
|
||||
let err = provider
|
||||
.resolve_bound(&selected_root(
|
||||
"selected-demo",
|
||||
LOCAL_ENVIRONMENT_ID,
|
||||
&plugin_root,
|
||||
))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.expect_err("malformed preferred manifest should fail");
|
||||
|
||||
assert!(
|
||||
std::error::Error::source(&err)
|
||||
.is_some_and(<dyn std::error::Error>::is::<serde_json::Error>)
|
||||
);
|
||||
let ExecutorPluginProviderError::ParseManifest {
|
||||
root_id,
|
||||
path,
|
||||
source: _,
|
||||
} = err
|
||||
else {
|
||||
panic!("expected parse error");
|
||||
};
|
||||
assert_eq!(
|
||||
(root_id, path),
|
||||
("selected-demo".to_string(), expected_path)
|
||||
);
|
||||
}
|
||||
85
codex-rs/core-plugins/src/git_policy.rs
Normal file
85
codex-rs/core-plugins/src/git_policy.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
// These variables can redirect Git to an untrusted repository or inject command-scoped settings.
|
||||
pub(crate) const REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES: &[&str] = &[
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_CEILING_DIRECTORIES",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_CONFIG",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_CONFIG_PARAMETERS",
|
||||
"GIT_DIR",
|
||||
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
|
||||
"GIT_GRAFT_FILE",
|
||||
"GIT_IMPLICIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_NAMESPACE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_PREFIX",
|
||||
"GIT_REPLACE_REF_BASE",
|
||||
"GIT_SHALLOW_FILE",
|
||||
"GIT_WORK_TREE",
|
||||
];
|
||||
|
||||
/// Distinguishes isolated background Git operations from explicitly requested user operations.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum PluginGitMode {
|
||||
/// Ignores repository-scoped Git configuration inherited from the launch project.
|
||||
Automatic,
|
||||
/// Preserves the configuration explicitly available to user-requested Git commands.
|
||||
Manual,
|
||||
}
|
||||
|
||||
impl PluginGitMode {
|
||||
/// Creates a Git command with the repository-environment policy for this operation.
|
||||
/// Automatic remote lookups and initial clones must also select a trusted repository.
|
||||
pub(crate) fn command(self, git_binary: &Path) -> Command {
|
||||
let mut command = codex_utils_process::background_command(git_binary);
|
||||
command.args(["-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG]);
|
||||
if matches!(self, Self::Automatic) {
|
||||
command.env("GIT_OPTIONAL_LOCKS", "0");
|
||||
for name in REPOSITORY_LOCAL_GIT_ENVIRONMENT_VARIABLES {
|
||||
command.env_remove(name);
|
||||
}
|
||||
}
|
||||
command
|
||||
}
|
||||
}
|
||||
|
||||
/// Isolates an automatic Git command from repository discovery in the launch project.
|
||||
///
|
||||
/// The command must already have repository-scoped environment variables removed. Keep the
|
||||
/// returned guard alive until the Git process exits because it owns the selected repository.
|
||||
pub(crate) fn configure_trusted_git_repository(
|
||||
command: &mut Command,
|
||||
codex_home: &Path,
|
||||
) -> Result<TempDir, String> {
|
||||
let canonical_home = AbsolutePathBuf::from_absolute_path(codex_home)
|
||||
.and_then(|path| path.canonicalize())
|
||||
.map_err(|err| format!("failed to resolve trusted Codex home: {err}"))?;
|
||||
let staging_root = canonical_home.join(".tmp");
|
||||
std::fs::create_dir_all(staging_root.as_path())
|
||||
.map_err(|err| format!("failed to create trusted Git repository root: {err}"))?;
|
||||
let staging_root = staging_root
|
||||
.canonicalize()
|
||||
.map_err(|err| format!("failed to resolve trusted Git repository root: {err}"))?;
|
||||
if !staging_root.as_path().starts_with(canonical_home.as_path()) {
|
||||
return Err("trusted Git repository root escapes Codex home".to_string());
|
||||
}
|
||||
|
||||
let repository = tempfile::Builder::new()
|
||||
.prefix("git-")
|
||||
.tempdir_in(staging_root.as_path())
|
||||
.map_err(|err| format!("failed to create trusted Git repository: {err}"))?;
|
||||
for directory in ["objects", "refs"] {
|
||||
std::fs::create_dir(repository.path().join(directory))
|
||||
.map_err(|err| format!("failed to initialize trusted Git repository: {err}"))?;
|
||||
}
|
||||
std::fs::write(repository.path().join("HEAD"), "ref: refs/heads/main\n")
|
||||
.map_err(|err| format!("failed to initialize trusted Git repository HEAD: {err}"))?;
|
||||
command.env("GIT_DIR", repository.path());
|
||||
Ok(repository)
|
||||
}
|
||||
46
codex-rs/core-plugins/src/http_client_selector.rs
Normal file
46
codex-rs/core-plugins/src/http_client_selector.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use codex_http_client::NetworkPolicy;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RequestBuilder;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use http::Method;
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Builds requests whose URL is also used to resolve their outbound route.
|
||||
///
|
||||
/// Implementations must keep route selection coupled to the request URL. Returning a transport
|
||||
/// client would let callers send a different URL than the one used for route selection.
|
||||
pub(crate) trait HttpClientSelector: Debug + Send + Sync {
|
||||
fn for_current_account(&self) -> Arc<dyn HttpClientSelector>;
|
||||
fn request(&self, method: Method, url: &str) -> RequestBuilder;
|
||||
fn request_for_account(
|
||||
&self,
|
||||
method: Method,
|
||||
url: &str,
|
||||
binding: &NetworkPolicy,
|
||||
) -> Option<RequestBuilder>;
|
||||
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy;
|
||||
}
|
||||
|
||||
impl HttpClientSelector for RouteAwareClientPool {
|
||||
fn for_current_account(&self) -> Arc<dyn HttpClientSelector> {
|
||||
Arc::new(RouteAwareClientPool::for_current_account(self))
|
||||
}
|
||||
|
||||
fn request(&self, method: Method, url: &str) -> RequestBuilder {
|
||||
RouteAwareClientPool::request(self, method, url)
|
||||
}
|
||||
|
||||
fn request_for_account(
|
||||
&self,
|
||||
method: Method,
|
||||
url: &str,
|
||||
binding: &NetworkPolicy,
|
||||
) -> Option<RequestBuilder> {
|
||||
Some(self.with_account_binding(binding)?.request(method, url))
|
||||
}
|
||||
|
||||
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
|
||||
RouteAwareClientPool::outbound_proxy_policy(self)
|
||||
}
|
||||
}
|
||||
78
codex-rs/core-plugins/src/installed_marketplaces.rs
Normal file
78
codex-rs/core-plugins/src/installed_marketplaces.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::marketplace::find_marketplace_manifest_path;
|
||||
use crate::marketplace_policy::policy_filtered_plugin_config;
|
||||
|
||||
pub const INSTALLED_MARKETPLACES_DIR: &str = ".tmp/marketplaces";
|
||||
|
||||
pub fn marketplace_install_root(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(INSTALLED_MARKETPLACES_DIR)
|
||||
}
|
||||
|
||||
pub fn installed_marketplace_roots_from_layer_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> Vec<AbsolutePathBuf> {
|
||||
let Some(effective_config) = policy_filtered_plugin_config(config_layer_stack, codex_home)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(marketplaces_value) = effective_config.get("marketplaces") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(marketplaces) = marketplaces_value.as_table() else {
|
||||
warn!("invalid marketplaces config: expected table");
|
||||
return Vec::new();
|
||||
};
|
||||
let default_install_root = marketplace_install_root(codex_home);
|
||||
let mut roots = marketplaces
|
||||
.iter()
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
if !marketplace.is_table() {
|
||||
warn!(
|
||||
marketplace_name,
|
||||
"ignoring invalid configured marketplace entry"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
if let Err(err) = validate_plugin_segment(marketplace_name, "marketplace name") {
|
||||
warn!(
|
||||
marketplace_name,
|
||||
error = %err,
|
||||
"ignoring invalid configured marketplace name"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let path = resolve_configured_marketplace_root(
|
||||
marketplace_name,
|
||||
marketplace,
|
||||
&default_install_root,
|
||||
)?;
|
||||
find_marketplace_manifest_path(&path).map(|_| path)
|
||||
})
|
||||
.filter_map(|path| AbsolutePathBuf::try_from(path).ok())
|
||||
.collect::<Vec<_>>();
|
||||
roots.sort_unstable_by(|left, right| left.as_path().cmp(right.as_path()));
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn resolve_configured_marketplace_root(
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
default_install_root: &Path,
|
||||
) -> Option<PathBuf> {
|
||||
match marketplace.get("source_type").and_then(toml::Value::as_str) {
|
||||
Some("local") => marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.filter(|source| !source.is_empty())
|
||||
.map(PathBuf::from),
|
||||
_ => Some(default_install_root.join(marketplace_name)),
|
||||
}
|
||||
}
|
||||
135
codex-rs/core-plugins/src/lib.rs
Normal file
135
codex-rs/core-plugins/src/lib.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
mod app_mcp_routing;
|
||||
mod artifact_operation;
|
||||
mod catalog;
|
||||
mod command_migration;
|
||||
mod discoverable;
|
||||
mod error_subtype;
|
||||
mod executor_catalog;
|
||||
mod executor_hooks;
|
||||
mod executor_provider;
|
||||
mod git_policy;
|
||||
mod http_client_selector;
|
||||
pub mod installed_marketplaces;
|
||||
mod loaded_cache_metrics;
|
||||
pub mod loader;
|
||||
mod manager;
|
||||
pub mod manifest;
|
||||
pub mod marketplace;
|
||||
pub mod marketplace_add;
|
||||
mod marketplace_policy;
|
||||
pub mod marketplace_remove;
|
||||
mod marketplace_staging;
|
||||
pub mod marketplace_upgrade;
|
||||
mod npm_source;
|
||||
mod plugin_bundle_archive;
|
||||
mod plugin_measurement_references;
|
||||
mod plugin_metrics;
|
||||
mod plugin_metrics_sidecar;
|
||||
mod provider;
|
||||
mod recommended_plugin_install;
|
||||
pub mod remote;
|
||||
pub mod remote_bundle;
|
||||
pub mod remote_legacy;
|
||||
mod remote_metadata;
|
||||
mod remote_plugin_id_resolver;
|
||||
mod script_attribution;
|
||||
mod skill_snapshots;
|
||||
pub mod startup_sync;
|
||||
pub mod store;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
pub mod toggles;
|
||||
mod tool_suggest_metadata;
|
||||
|
||||
pub(crate) use git_policy::PluginGitMode;
|
||||
pub(crate) use git_policy::configure_trusted_git_repository;
|
||||
|
||||
pub const OPENAI_CURATED_MARKETPLACE_NAME: &str = "openai-curated";
|
||||
pub const OPENAI_API_CURATED_MARKETPLACE_NAME: &str = "openai-api-curated";
|
||||
pub const OPENAI_BUNDLED_MARKETPLACE_NAME: &str = "openai-bundled";
|
||||
pub(crate) const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha";
|
||||
pub(crate) const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
|
||||
|
||||
pub fn is_openai_curated_marketplace_name(marketplace_name: &str) -> bool {
|
||||
marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME
|
||||
|| marketplace_name == OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
}
|
||||
|
||||
pub type LoadedPlugin = codex_plugin::LoadedPlugin<codex_config::McpServerConfig>;
|
||||
pub type PluginLoadOutcome = codex_plugin::PluginLoadOutcome<codex_config::McpServerConfig>;
|
||||
|
||||
pub use app_mcp_routing::apps_route_available;
|
||||
pub use artifact_operation::ArtifactOperation;
|
||||
pub use artifact_operation::recognize_artifact_operation;
|
||||
pub use catalog::PluginCatalog;
|
||||
pub use catalog::PluginCatalogEntry;
|
||||
pub use catalog::PluginSourceLocation;
|
||||
pub use catalog::merge_catalogs;
|
||||
pub use codex_core_plugin_common::PluginIdentity;
|
||||
pub use command_migration::CommandDescriptionMode;
|
||||
pub use command_migration::CommandMigrationProfile;
|
||||
pub use command_migration::RewriteProfile as CommandRewriteProfile;
|
||||
pub use command_migration::count_missing_commands_with_profile;
|
||||
pub use command_migration::import_commands_with_profile;
|
||||
pub use command_migration::missing_command_names_with_profile;
|
||||
pub use discoverable::ToolSuggestDiscoverablePlugin;
|
||||
pub use discoverable::ToolSuggestPluginDiscoveryInput;
|
||||
pub use executor_catalog::catalog_from_snapshots;
|
||||
pub use executor_hooks::executor_plugin_hook_sources;
|
||||
pub use executor_hooks::executor_plugin_hook_sources_v2;
|
||||
pub use executor_provider::ExecutorPluginProvider;
|
||||
pub use executor_provider::ExecutorPluginProviderError;
|
||||
pub use executor_provider::PluginRootOwnership;
|
||||
pub use executor_provider::ResolvedExecutorPlugin;
|
||||
pub use loader::PluginHookLoadOutcome;
|
||||
pub use manager::ConfiguredMarketplace;
|
||||
pub use manager::ConfiguredMarketplaceListOutcome;
|
||||
pub use manager::ConfiguredMarketplacePlugin;
|
||||
pub use manager::EffectivePluginsChange;
|
||||
pub use manager::PluginDetail;
|
||||
pub use manager::PluginDetailsUnavailableReason;
|
||||
pub use manager::PluginInstallError;
|
||||
pub use manager::PluginInstallOutcome;
|
||||
pub use manager::PluginInstallRequest;
|
||||
pub use manager::PluginListBackgroundTaskOptions;
|
||||
pub use manager::PluginMarketplaceContext;
|
||||
pub use manager::PluginMarketplaceScope;
|
||||
pub use manager::PluginReadOutcome;
|
||||
pub use manager::PluginReadRequest;
|
||||
pub use manager::PluginUninstallError;
|
||||
pub use manager::PluginsConfigInput;
|
||||
pub use manager::PluginsManager;
|
||||
pub use manager::RecommendedPluginCandidatesInput;
|
||||
pub use manager::RemotePluginInstallOutcome;
|
||||
pub use manager::RemotePluginInstallRequest;
|
||||
pub use manager::RemotePluginOperationError;
|
||||
pub use manager::RemotePluginOperationErrorKind;
|
||||
pub use manager::RemotePluginUninstallOutcome;
|
||||
pub use marketplace_policy::allowed_configured_marketplace_names;
|
||||
pub use marketplace_upgrade::ConfigLayerReload;
|
||||
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeError as PluginMarketplaceUpgradeError;
|
||||
pub use marketplace_upgrade::ConfiguredMarketplaceUpgradeOutcome as PluginMarketplaceUpgradeOutcome;
|
||||
pub use plugin_measurement_references::PluginMeasurementReference;
|
||||
pub use plugin_measurement_references::RemotePluginMeasurementCache;
|
||||
pub use plugin_metrics::PluginMeasurementDefinition;
|
||||
pub use plugin_metrics::PluginMetricsOperation;
|
||||
pub use plugin_metrics::ResolvedPluginMetricsOperation;
|
||||
pub use plugin_metrics_sidecar::PLUGIN_METRICS_OUTPUT_ENV_VAR;
|
||||
pub use plugin_metrics_sidecar::PluginMeasurementBatch;
|
||||
pub use plugin_metrics_sidecar::PluginMetricsSidecar;
|
||||
pub use plugin_metrics_sidecar::strip_output_env;
|
||||
pub use provider::PluginListQuery;
|
||||
pub use provider::PluginProvider;
|
||||
pub use provider::PluginProviderError;
|
||||
pub use provider::PluginProviderFuture;
|
||||
pub use provider::PluginProviderResult;
|
||||
pub use recommended_plugin_install::hydrate_selected_recommended_plugin_install_metadata;
|
||||
pub use remote::RecommendedPlugin;
|
||||
pub use remote::RecommendedPluginsMode;
|
||||
pub use remote_metadata::remote_catalog_metadata_eq;
|
||||
pub use script_attribution::PluginCommandAttribution;
|
||||
pub use script_attribution::PluginMeasurementTarget;
|
||||
pub use script_attribution::TrustedPluginRoots;
|
||||
pub use script_attribution::command_script_arguments;
|
||||
|
||||
pub use marketplace_policy::configured_plugins_from_stack;
|
||||
49
codex-rs/core-plugins/src/loaded_cache_metrics.rs
Normal file
49
codex-rs/core-plugins/src/loaded_cache_metrics.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Request counts exclude disabled plugins, account-switch discards, and cancellations.
|
||||
//! Auth retries keep the furthest request outcome reached; each completed wait/load is timed.
|
||||
//! Skill-snapshot lookups are not requests. Clear events include already-empty caches.
|
||||
//! Tags never contain configuration data.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) const LOAD_DURATION: &str = "codex.plugins.loaded_cache.load.duration_ms";
|
||||
pub(crate) const WAIT_DURATION: &str = "codex.plugins.loaded_cache.wait.duration_ms";
|
||||
|
||||
pub(crate) enum RequestOutcome {
|
||||
Hit,
|
||||
HitAfterWait,
|
||||
Load,
|
||||
}
|
||||
|
||||
impl RequestOutcome {
|
||||
pub(crate) fn record(self) {
|
||||
let Some(metrics) = codex_otel::global() else {
|
||||
return;
|
||||
};
|
||||
let outcome = match self {
|
||||
Self::Hit => "hit",
|
||||
Self::HitAfterWait => "hit_after_wait",
|
||||
Self::Load => "load",
|
||||
};
|
||||
let _ = metrics.counter(
|
||||
"codex.plugins.loaded_cache.request",
|
||||
/*inc*/ 1,
|
||||
&[("outcome", outcome)],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_duration(name: &'static str, duration: Duration) {
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(name, duration, &[]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_event(event: &'static str) {
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.counter(
|
||||
"codex.plugins.loaded_cache.event",
|
||||
/*inc*/ 1,
|
||||
&[("event", event)],
|
||||
);
|
||||
}
|
||||
}
|
||||
1955
codex-rs/core-plugins/src/loader.rs
Normal file
1955
codex-rs/core-plugins/src/loader.rs
Normal file
File diff suppressed because it is too large
Load Diff
1196
codex-rs/core-plugins/src/loader_tests.rs
Normal file
1196
codex-rs/core-plugins/src/loader_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
3804
codex-rs/core-plugins/src/manager.rs
Normal file
3804
codex-rs/core-plugins/src/manager.rs
Normal file
File diff suppressed because it is too large
Load Diff
142
codex-rs/core-plugins/src/manager_errors.rs
Normal file
142
codex-rs/core-plugins/src/manager_errors.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
//! Plugin mutation errors and their stable telemetry classifications.
|
||||
|
||||
use crate::marketplace::MarketplaceError;
|
||||
use crate::remote_legacy::RemotePluginMutationError;
|
||||
use crate::store::PluginStoreError;
|
||||
use crate::store::error_context_sub_error_type;
|
||||
use codex_plugin::PluginIdError;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginInstallError {
|
||||
#[error("{0}")]
|
||||
Marketplace(#[from] MarketplaceError),
|
||||
|
||||
#[error("{0}")]
|
||||
Remote(#[from] RemotePluginMutationError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("{0}")]
|
||||
Config(#[from] anyhow::Error),
|
||||
|
||||
#[error("failed to join plugin install task: {0}")]
|
||||
Join(#[from] tokio::task::JoinError),
|
||||
}
|
||||
|
||||
impl PluginInstallError {
|
||||
pub(super) fn join(source: tokio::task::JoinError) -> Self {
|
||||
Self::Join(source)
|
||||
}
|
||||
|
||||
pub fn is_invalid_request(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Marketplace(
|
||||
MarketplaceError::MarketplaceNotFound { .. }
|
||||
| MarketplaceError::InvalidMarketplaceFile { .. }
|
||||
| MarketplaceError::PluginNotFound { .. }
|
||||
| MarketplaceError::PluginNotAvailable { .. }
|
||||
| MarketplaceError::InvalidPlugin(_)
|
||||
) | Self::Store(PluginStoreError::Invalid(_))
|
||||
)
|
||||
}
|
||||
|
||||
pub fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Marketplace(err) => marketplace_error_sub_error_type(err),
|
||||
Self::Remote(err) => err.sub_error_type(),
|
||||
Self::Store(err) => err.sub_error_type(),
|
||||
Self::Config(_) => Some("failed_to_enable_plugin".to_string()),
|
||||
Self::Join(_) => Some("plugin_install_task_failed".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plugin_install_error_type(err: &PluginInstallError) -> &'static str {
|
||||
match err {
|
||||
PluginInstallError::Marketplace(err) => marketplace_error_type(err),
|
||||
PluginInstallError::Remote(err) => remote_plugin_mutation_error_type(err),
|
||||
PluginInstallError::Store(err) => plugin_store_error_type(err),
|
||||
PluginInstallError::Config(_) => "config",
|
||||
PluginInstallError::Join(_) => "join",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn marketplace_error_type(err: &MarketplaceError) -> &'static str {
|
||||
match err {
|
||||
MarketplaceError::Io { .. } => "marketplace_io",
|
||||
MarketplaceError::MarketplaceNotFound { .. } => "marketplace_not_found",
|
||||
MarketplaceError::InvalidMarketplaceFile { .. } => "invalid_marketplace_file",
|
||||
MarketplaceError::PluginNotFound { .. } => "plugin_not_found",
|
||||
MarketplaceError::PluginNotAvailable { .. } => "plugin_not_available",
|
||||
MarketplaceError::PluginsDisabled => "plugins_disabled",
|
||||
MarketplaceError::InvalidPlugin(_) => "invalid_plugin",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn marketplace_error_sub_error_type(err: &MarketplaceError) -> Option<String> {
|
||||
match err {
|
||||
MarketplaceError::Io { context, .. } => Some(error_context_sub_error_type(context)),
|
||||
MarketplaceError::MarketplaceNotFound { .. }
|
||||
| MarketplaceError::InvalidMarketplaceFile { .. }
|
||||
| MarketplaceError::PluginNotFound { .. }
|
||||
| MarketplaceError::PluginNotAvailable { .. }
|
||||
| MarketplaceError::PluginsDisabled
|
||||
| MarketplaceError::InvalidPlugin(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_mutation_error_type(err: &RemotePluginMutationError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginMutationError::AuthRequired => "remote_mutation_auth_required",
|
||||
RemotePluginMutationError::UnsupportedAuthMode => "remote_mutation_unsupported_auth_mode",
|
||||
RemotePluginMutationError::AuthToken(_) => "remote_mutation_auth_token",
|
||||
RemotePluginMutationError::InvalidBaseUrl(_) => "remote_mutation_invalid_base_url",
|
||||
RemotePluginMutationError::InvalidBaseUrlPath => "remote_mutation_invalid_base_url_path",
|
||||
RemotePluginMutationError::Request { .. } => "remote_mutation_request",
|
||||
RemotePluginMutationError::UnexpectedStatus { .. } => "remote_mutation_unexpected_status",
|
||||
RemotePluginMutationError::Decode { .. } => "remote_mutation_decode",
|
||||
RemotePluginMutationError::UnexpectedPluginId { .. } => {
|
||||
"remote_mutation_unexpected_plugin_id"
|
||||
}
|
||||
RemotePluginMutationError::UnexpectedEnabledState { .. } => {
|
||||
"remote_mutation_unexpected_enabled_state"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_store_error_type(err: &PluginStoreError) -> &'static str {
|
||||
match err {
|
||||
PluginStoreError::Io { .. } => "store_io",
|
||||
PluginStoreError::Invalid(_) => "store_invalid",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginUninstallError {
|
||||
#[error("{0}")]
|
||||
InvalidPluginId(#[from] PluginIdError),
|
||||
|
||||
#[error("{0}")]
|
||||
Remote(#[from] RemotePluginMutationError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("{0}")]
|
||||
Config(#[from] anyhow::Error),
|
||||
|
||||
#[error("failed to join plugin uninstall task: {0}")]
|
||||
Join(#[from] tokio::task::JoinError),
|
||||
}
|
||||
|
||||
impl PluginUninstallError {
|
||||
pub(super) fn join(source: tokio::task::JoinError) -> Self {
|
||||
Self::Join(source)
|
||||
}
|
||||
|
||||
pub fn is_invalid_request(&self) -> bool {
|
||||
matches!(self, Self::InvalidPluginId(_))
|
||||
}
|
||||
}
|
||||
7973
codex-rs/core-plugins/src/manager_tests.rs
Normal file
7973
codex-rs/core-plugins/src/manager_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
1031
codex-rs/core-plugins/src/manifest.rs
Normal file
1031
codex-rs/core-plugins/src/manifest.rs
Normal file
File diff suppressed because it is too large
Load Diff
181
codex-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
181
codex-rs/core-plugins/src/manifest/manifest_cache.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
//! Reuse parsed manifest revisions within an explicitly owned plugin store.
|
||||
//! Store clones share the cache; independently created stores do not share entries or warnings.
|
||||
|
||||
use super::LoadedPluginManifest;
|
||||
use super::PluginManifestFormat;
|
||||
use super::UriPluginManifest;
|
||||
use super::parse_resolved_plugin_manifest;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_MANIFEST_RELATIVE_PATH;
|
||||
use codex_utils_plugins::find_plugin_manifest_path;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const CAPACITY: usize = 128;
|
||||
const MAX_CACHABLE_INPUT_LEN: usize = 64 * 1024;
|
||||
|
||||
pub(crate) struct ManifestCache {
|
||||
state: Option<Mutex<ManifestCacheState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ManifestCacheState {
|
||||
entries: HashMap<(PathUri, PathUri), Entry>,
|
||||
recency: VecDeque<(PathUri, PathUri)>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
contents_digest: [u8; 32],
|
||||
overlay: Option<(PathUri, [u8; 32])>,
|
||||
manifest: UriPluginManifest,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ManifestCache {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ManifestCache")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ManifestCache {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Some(Mutex::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCache {
|
||||
pub(crate) fn disabled() -> Self {
|
||||
Self { state: None }
|
||||
}
|
||||
|
||||
pub(crate) fn load(&self, plugin_root: &Path) -> Option<LoadedPluginManifest> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root)?;
|
||||
let contents = fs::read_to_string(&manifest_path).ok()?;
|
||||
let is_agent_plugin =
|
||||
manifest_path == plugin_root.join(AGENT_PLUGIN_MANIFEST_RELATIVE_PATH);
|
||||
let overlay = if is_agent_plugin {
|
||||
let overlay_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
fs::read_to_string(&overlay_path)
|
||||
.ok()
|
||||
.map(|contents| (overlay_path, contents))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match parse_resolved_plugin_manifest(
|
||||
self,
|
||||
plugin_root,
|
||||
&manifest_path,
|
||||
&contents,
|
||||
overlay
|
||||
.as_ref()
|
||||
.map(|(path, contents)| (path.as_path(), contents.as_str())),
|
||||
) {
|
||||
Ok(manifest) => Some(LoadedPluginManifest {
|
||||
manifest,
|
||||
format: if is_agent_plugin {
|
||||
PluginManifestFormat::AgentPlugin
|
||||
} else {
|
||||
PluginManifestFormat::Legacy
|
||||
},
|
||||
}),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
path = %manifest_path.display(),
|
||||
"failed to parse plugin manifest: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse(
|
||||
&self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let Some(state) = &self.state else {
|
||||
return parse();
|
||||
};
|
||||
if contents
|
||||
.len()
|
||||
.saturating_add(overlay.map_or(0, |(_, value)| value.len()))
|
||||
> MAX_CACHABLE_INPUT_LEN
|
||||
{
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(&(root.clone(), path.clone()));
|
||||
// Unbounded inputs must not serialize unrelated parses behind the cache lock.
|
||||
return parse();
|
||||
}
|
||||
// Parsing is synchronous and does no filesystem I/O. Serializing cache misses also
|
||||
// prevents concurrent capability loaders from validating the same revision twice.
|
||||
state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.parse(root, path, contents, overlay, parse)
|
||||
}
|
||||
}
|
||||
|
||||
impl ManifestCacheState {
|
||||
fn remove(&mut self, key: &(PathUri, PathUri)) -> Option<Entry> {
|
||||
let entry = self.entries.remove(key)?;
|
||||
self.recency.retain(|existing| existing != key);
|
||||
Some(entry)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
&mut self,
|
||||
root: &PathUri,
|
||||
path: &PathUri,
|
||||
contents: &str,
|
||||
overlay: Option<(&PathUri, &str)>,
|
||||
parse: impl FnOnce() -> Result<UriPluginManifest, serde_json::Error>,
|
||||
) -> Result<UriPluginManifest, serde_json::Error> {
|
||||
let key = (root.clone(), path.clone());
|
||||
let previous = self.remove(&key);
|
||||
let contents_digest = Sha256::digest(contents.as_bytes()).into();
|
||||
let overlay = overlay
|
||||
.map(|(path, contents)| (path.clone(), Sha256::digest(contents.as_bytes()).into()));
|
||||
if let Some(entry) = previous
|
||||
&& entry.contents_digest == contents_digest
|
||||
&& entry.overlay == overlay
|
||||
{
|
||||
let manifest = entry.manifest.clone();
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(key, entry);
|
||||
return Ok(manifest);
|
||||
}
|
||||
let manifest = parse()?;
|
||||
if self.entries.len() == CAPACITY
|
||||
&& let Some(oldest) = self.recency.pop_back()
|
||||
{
|
||||
self.entries.remove(&oldest);
|
||||
}
|
||||
self.recency.push_front(key.clone());
|
||||
self.entries.insert(
|
||||
key,
|
||||
Entry {
|
||||
contents_digest,
|
||||
overlay,
|
||||
manifest: manifest.clone(),
|
||||
},
|
||||
);
|
||||
Ok(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "manifest_cache_tests.rs"]
|
||||
mod tests;
|
||||
303
codex-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
303
codex-rs/core-plugins/src/manifest/manifest_cache_tests.rs
Normal file
@@ -0,0 +1,303 @@
|
||||
//! Verify parse reuse, revision invalidation, and diagnostic preservation.
|
||||
|
||||
use super::super::parse_legacy_plugin_manifest_uri;
|
||||
use super::super::parse_resolved_plugin_manifest;
|
||||
use super::ManifestCache;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use std::sync::Mutex;
|
||||
use tracing_test::internal::MockWriter;
|
||||
|
||||
#[test]
|
||||
fn repeated_revision_runs_parser_once_and_changes_run_it_again() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let first = r#"{"name":"demo","description":"first"}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed"}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
let mut results = Vec::new();
|
||||
for contents in std::iter::repeat_n(first, 220).chain([changed, first]) {
|
||||
results.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let original = results[0].clone();
|
||||
let mut revised = original.clone();
|
||||
revised.description = Some("changed".to_string());
|
||||
assert_eq!(
|
||||
results,
|
||||
std::iter::repeat_n(original.clone(), 220)
|
||||
.chain([revised, original])
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_fields_warn_once_until_the_manifest_changes() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join(".codex-plugin/plugin.json");
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let original =
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let changed = r#"{"name":"demo","description":"changed","interface":{"defaultPrompt":" ","composerIcon":"../outside.svg"}}"#;
|
||||
let cache = ManifestCache::default();
|
||||
let parse = |contents| {
|
||||
parse_resolved_plugin_manifest(
|
||||
&cache,
|
||||
directory.path(),
|
||||
&path,
|
||||
contents,
|
||||
/*overlay*/ None,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let first = parse(original);
|
||||
for _ in 0..220 {
|
||||
assert_eq!(parse(original), first);
|
||||
}
|
||||
let mut expected = first.clone();
|
||||
expected.description = Some("changed".to_string());
|
||||
assert_eq!(parse(changed), expected);
|
||||
assert_eq!(parse(original), first);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(logs.matches("ignoring interface.defaultPrompt").count(), 3);
|
||||
assert_eq!(logs.matches("ignoring interface.composerIcon").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_revision_and_resource_root_are_part_of_cached_parse() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let other_root = root.join("other").unwrap();
|
||||
let path = root.join("plugin.json").unwrap();
|
||||
let overlay_path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = serde_json::json!({
|
||||
"$schema": codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "demo"
|
||||
})
|
||||
.to_string();
|
||||
let first = r#"{"interface":{"defaultPrompt":"first"}}"#;
|
||||
let changed = r#"{"interface":{"defaultPrompt":"changed"}}"#;
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for (plugin_root, overlay) in [
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, first))),
|
||||
(&root, Some((&overlay_path, changed))),
|
||||
(&root, None),
|
||||
(&other_root, None),
|
||||
] {
|
||||
let manifest = cache
|
||||
.parse(plugin_root, &path, &contents, overlay, || {
|
||||
parses.set(parses.get() + 1);
|
||||
super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let expected = super::super::agent_plugin_manifest::parse_agent_plugin_manifest_uri(
|
||||
plugin_root,
|
||||
&path,
|
||||
&contents,
|
||||
overlay,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(manifest, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_revision_is_retried_and_repair_is_visible() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let cache = ManifestCache::default();
|
||||
for contents in ["{", "{"] {
|
||||
assert!(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let repaired = r#"{"name":"repaired"}"#;
|
||||
assert_eq!(
|
||||
cache
|
||||
.parse(&root, &path, repaired, /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired)
|
||||
})
|
||||
.unwrap(),
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, repaired).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_windows_paths_share_a_cached_revision() {
|
||||
let cache = ManifestCache::default();
|
||||
let parses = Cell::new(0);
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let mut manifests = Vec::new();
|
||||
for value in ["file:///C:/plugins/Demo", "file:///C:/plugins/demo"] {
|
||||
let root = PathUri::parse(value).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
manifests.push(
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert_eq!(manifests[0], manifests[1]);
|
||||
assert_eq!(parses.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_revision_invalidates_previous_result_without_being_cached() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let small = r#"{"name":"demo"}"#;
|
||||
let large = format!("{}{small}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let parses = Cell::new(0);
|
||||
let cache = ManifestCache::default();
|
||||
for contents in [small, small, &large, &large, small] {
|
||||
cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(parses.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_parse_does_not_block_unrelated_manifest() {
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let large_path = root.join("large.json").unwrap();
|
||||
let small_path = root.join("small.json").unwrap();
|
||||
let large = format!("{}{{}}", " ".repeat(super::MAX_CACHABLE_INPUT_LEN));
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
let (completed_tx, completed_rx) = mpsc::channel();
|
||||
let root = &root;
|
||||
let large_path = &large_path;
|
||||
let small_path = &small_path;
|
||||
let large = &large;
|
||||
let cache = &ManifestCache::default();
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, large_path, large, /*overlay*/ None, || {
|
||||
started_tx.send(()).unwrap();
|
||||
release_rx.recv().unwrap();
|
||||
parse_legacy_plugin_manifest_uri(root, large_path, large)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
started_rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
scope.spawn(move || {
|
||||
cache
|
||||
.parse(root, small_path, "{}", /*overlay*/ None, || {
|
||||
parse_legacy_plugin_manifest_uri(root, small_path, "{}")
|
||||
})
|
||||
.unwrap();
|
||||
completed_tx.send(()).unwrap();
|
||||
});
|
||||
let completed = completed_rx.recv_timeout(Duration::from_secs(10));
|
||||
release_tx.send(()).unwrap();
|
||||
assert_eq!(completed, Ok(()));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_clones_reuse_validation_but_independent_stores_warn_again() {
|
||||
use crate::store::PluginStore;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = directory.path().join("plugin");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin")).unwrap();
|
||||
std::fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"demo","interface":{"defaultPrompt":" "}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let buffer: &'static Mutex<Vec<u8>> = Box::leak(Box::new(Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(/*ansi*/ false)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let store = PluginStore::new(directory.path().to_path_buf());
|
||||
let cloned_store = store.clone();
|
||||
let first = store.manifest_cache.load(&root).unwrap().manifest;
|
||||
for _ in 0..220 {
|
||||
assert_eq!(
|
||||
cloned_store.manifest_cache.load(&root).unwrap().manifest,
|
||||
first
|
||||
);
|
||||
}
|
||||
let independent_store = PluginStore::new(directory.path().to_path_buf());
|
||||
assert_eq!(
|
||||
independent_store
|
||||
.manifest_cache
|
||||
.load(&root)
|
||||
.unwrap()
|
||||
.manifest,
|
||||
first
|
||||
);
|
||||
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
|
||||
assert_eq!(
|
||||
logs.matches("ignoring interface.defaultPrompt: prompt must not be empty")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_cache_parses_each_load() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = PathUri::from_host_native_path(directory.path()).unwrap();
|
||||
let path = root.join(".codex-plugin/plugin.json").unwrap();
|
||||
let contents = r#"{"name":"demo"}"#;
|
||||
let expected = parse_legacy_plugin_manifest_uri(&root, &path, contents).unwrap();
|
||||
let cache = ManifestCache::disabled();
|
||||
let parses = Cell::new(0);
|
||||
for _ in 0..3 {
|
||||
let result = cache
|
||||
.parse(&root, &path, contents, /*overlay*/ None, || {
|
||||
parses.set(parses.get() + 1);
|
||||
parse_legacy_plugin_manifest_uri(&root, &path, contents)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
assert_eq!(parses.get(), 3);
|
||||
}
|
||||
1175
codex-rs/core-plugins/src/marketplace.rs
Normal file
1175
codex-rs/core-plugins/src/marketplace.rs
Normal file
File diff suppressed because it is too large
Load Diff
482
codex-rs/core-plugins/src/marketplace_add.rs
Normal file
482
codex-rs/core-plugins/src/marketplace_add.rs
Normal file
@@ -0,0 +1,482 @@
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::marketplace_policy::validate_marketplace_name_for_add;
|
||||
use crate::marketplace_policy::validate_marketplace_source_for_add;
|
||||
use crate::marketplace_staging::MarketplaceStagingDir;
|
||||
use crate::marketplace_staging::cleanup_marketplace_staging;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod install;
|
||||
mod metadata;
|
||||
mod source;
|
||||
|
||||
use install::clone_git_source;
|
||||
use install::ensure_marketplace_destination_is_inside_install_root;
|
||||
use install::replace_marketplace_root;
|
||||
use install::safe_marketplace_dir_name;
|
||||
use metadata::MarketplaceInstallMetadata;
|
||||
use metadata::find_marketplace_root_by_name;
|
||||
use metadata::installed_marketplace_root_for_source;
|
||||
use metadata::record_added_marketplace_entry;
|
||||
pub(crate) use source::MarketplaceSource;
|
||||
pub(crate) use source::parse_marketplace_source;
|
||||
use source::stage_marketplace_source;
|
||||
use source::validate_marketplace_source_root;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceAddRequest {
|
||||
pub source: String,
|
||||
pub ref_name: Option<String>,
|
||||
pub sparse_paths: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceAddOutcome {
|
||||
pub marketplace_name: String,
|
||||
pub source_display: String,
|
||||
pub installed_root: AbsolutePathBuf,
|
||||
pub already_added: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MarketplaceAddError {
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
pub async fn add_marketplace(
|
||||
codex_home: PathBuf,
|
||||
requirements: ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
add_marketplace_sync(codex_home.as_path(), &requirements, request)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| MarketplaceAddError::Internal(format!("failed to add marketplace: {err}")))?
|
||||
}
|
||||
|
||||
pub fn is_local_marketplace_source(
|
||||
source: &str,
|
||||
explicit_ref: Option<String>,
|
||||
) -> Result<bool, MarketplaceAddError> {
|
||||
Ok(matches!(
|
||||
parse_marketplace_source(source, explicit_ref)?,
|
||||
source::MarketplaceSource::Local { .. }
|
||||
))
|
||||
}
|
||||
|
||||
fn add_marketplace_sync(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError> {
|
||||
add_marketplace_sync_with_cloner(codex_home, requirements, request, clone_git_source)
|
||||
}
|
||||
|
||||
fn add_marketplace_sync_with_cloner<F>(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
request: MarketplaceAddRequest,
|
||||
clone_source: F,
|
||||
) -> Result<MarketplaceAddOutcome, MarketplaceAddError>
|
||||
where
|
||||
F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>,
|
||||
{
|
||||
let MarketplaceAddRequest {
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
} = request;
|
||||
let source = parse_marketplace_source(&source, ref_name)?;
|
||||
let managed_marketplace_name =
|
||||
validate_marketplace_source_for_add(codex_home, requirements, &source)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--sparse is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let install_root = marketplace_install_root(codex_home);
|
||||
fs::create_dir_all(&install_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to create marketplace install directory {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
|
||||
// Remove abandoned staging directories from earlier operations.
|
||||
// This is generally fast and rare operation so it doesn't deserve a separate cleanup task
|
||||
cleanup_marketplace_staging(&install_root);
|
||||
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &sparse_paths);
|
||||
if let Some(existing_root) =
|
||||
installed_marketplace_root_for_source(codex_home, &install_root, &install_metadata)?
|
||||
{
|
||||
let marketplace_name = validate_marketplace_source_root(&existing_root)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
|
||||
return Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(existing_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: true,
|
||||
});
|
||||
}
|
||||
|
||||
if let MarketplaceSource::Local { path } = &source {
|
||||
let marketplace_name = validate_marketplace_source_root(path)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
|
||||
return Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(path.clone()).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: false,
|
||||
});
|
||||
}
|
||||
|
||||
let staged_dir = MarketplaceStagingDir::new(&install_root).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to create temporary marketplace directory in {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
// Retain the cleanup guard through validation, installation, and config-write rollback.
|
||||
let staged_root = staged_dir.path();
|
||||
|
||||
stage_marketplace_source(&source, &sparse_paths, staged_root, clone_source)?;
|
||||
|
||||
let marketplace_name = validate_marketplace_source_root(staged_root)?;
|
||||
validate_marketplace_name_for_add(managed_marketplace_name, &marketplace_name)
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
|
||||
let destination = install_root.join(safe_marketplace_dir_name(&marketplace_name)?);
|
||||
ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?;
|
||||
if destination.exists() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
replace_marketplace_root(staged_root, &destination).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to install marketplace at {}: {err}",
|
||||
destination.display()
|
||||
))
|
||||
})?;
|
||||
if let Err(err) =
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)
|
||||
{
|
||||
if let Err(rollback_err) = fs::rename(&destination, staged_root) {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"{err}; additionally failed to roll back installed marketplace at {}: {rollback_err}",
|
||||
destination.display()
|
||||
)));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
Ok(MarketplaceAddOutcome {
|
||||
marketplace_name,
|
||||
source_display: source.display(),
|
||||
installed_root: AbsolutePathBuf::try_from(destination).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve installed marketplace root: {err}"
|
||||
))
|
||||
})?,
|
||||
already_added: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::RequirementsLayerEntry;
|
||||
use codex_config::compose_requirements;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn requirements(requirements_toml: &str) -> ConfigRequirements {
|
||||
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
requirements_toml,
|
||||
)])
|
||||
.expect("compose requirements")
|
||||
.expect("requirements should be present");
|
||||
ConfigRequirements::try_from(with_sources).expect("normalize requirements")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_installs_marketplace_and_updates_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "remote copy")?;
|
||||
|
||||
let result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, destination| {
|
||||
copy_dir_all(source_root.path(), destination)
|
||||
.map_err(|err| MarketplaceAddError::Internal(err.to_string()))
|
||||
},
|
||||
)?;
|
||||
|
||||
assert_eq!(result.marketplace_name, "debug");
|
||||
assert_eq!(result.source_display, "https://github.com/owner/repo.git");
|
||||
assert!(!result.already_added);
|
||||
assert!(
|
||||
result
|
||||
.installed_root
|
||||
.as_path()
|
||||
.join(".agents/plugins/marketplace.json")
|
||||
.is_file()
|
||||
);
|
||||
|
||||
let config = fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE))?;
|
||||
assert!(config.contains("[marketplaces.debug]"));
|
||||
assert!(config.contains("source_type = \"git\""));
|
||||
assert!(config.contains("source = \"https://github.com/owner/repo.git\""));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_git_marketplace_does_not_clone_or_create_install_root() {
|
||||
let requirements = requirements(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
|
||||
[marketplaces.allowed_sources.internal]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^allowed\.test$'
|
||||
"#,
|
||||
);
|
||||
for source in [
|
||||
"https://github.com/example/blocked.git",
|
||||
"https://127.0.0.1:18767/r.git",
|
||||
"https://allowed.test@127.0.0.1:18767/r.git",
|
||||
r"http://allowed.test\@127.0.0.1:18767/r.git",
|
||||
r"https://allowed.test\@127.0.0.1:18767/r.git",
|
||||
r"http://allowed.test\anything@127.0.0.1:18767/r.git",
|
||||
r"https://allowed.test\name:password@127.0.0.1:18767/r.git",
|
||||
r"https:///allowed.test\anything@127.0.0.1:18767/r.git",
|
||||
] {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let cloner_called = Cell::new(false);
|
||||
|
||||
let err = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
MarketplaceAddRequest {
|
||||
source: source.to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
cloner_called.set(true);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.expect_err("blocked marketplace should fail");
|
||||
|
||||
assert!(err.to_string().contains("is not allowed by requirements"));
|
||||
assert!(!cloner_called.get(), "cloned denied source: {source}");
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(codex_config::CONFIG_TOML_FILE)
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_installs_local_directory_source_and_updates_config() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
|
||||
let expected_source = source_root.path().canonicalize()?.display().to_string();
|
||||
assert_eq!(result.marketplace_name, "debug");
|
||||
assert_eq!(result.source_display, expected_source);
|
||||
let expected_installed_root =
|
||||
AbsolutePathBuf::from_absolute_path(source_root.path().canonicalize()?)?;
|
||||
assert_eq!(result.installed_root, expected_installed_root);
|
||||
assert!(!result.already_added);
|
||||
assert!(
|
||||
!marketplace_install_root(codex_home.path())
|
||||
.join("debug")
|
||||
.exists()
|
||||
);
|
||||
|
||||
let config = fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE))?;
|
||||
let config: toml::Value = toml::from_str(&config)?;
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source_type"].as_str(),
|
||||
Some("local")
|
||||
);
|
||||
assert_eq!(
|
||||
config["marketplaces"]["debug"]["source"].as_str(),
|
||||
Some(expected_source.as_str())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_rejects_sparse_checkout_for_local_directory_source() -> Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let err = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&ConfigRequirements::default(),
|
||||
MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: vec![".agents".to_string()],
|
||||
},
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"--sparse is only supported for git marketplace sources"
|
||||
);
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(codex_config::CONFIG_TOML_FILE)
|
||||
.exists()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_marketplace_sync_treats_existing_local_directory_source_as_already_added() -> Result<()>
|
||||
{
|
||||
let codex_home = TempDir::new()?;
|
||||
let source_root = TempDir::new()?;
|
||||
write_marketplace_source(source_root.path(), "local copy")?;
|
||||
|
||||
let request = MarketplaceAddRequest {
|
||||
source: source_root.path().display().to_string(),
|
||||
ref_name: None,
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
let requirements = ConfigRequirements::default();
|
||||
let first_result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
request.clone(),
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
let second_result = add_marketplace_sync_with_cloner(
|
||||
codex_home.path(),
|
||||
&requirements,
|
||||
request,
|
||||
|_url, _ref_name, _sparse_paths, _destination| {
|
||||
panic!("git cloner should not be called for local marketplace sources")
|
||||
},
|
||||
)?;
|
||||
|
||||
assert!(!first_result.already_added);
|
||||
assert!(second_result.already_added);
|
||||
assert_eq!(second_result.installed_root, first_result.installed_root);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_marketplace_source(source: &Path, marker: &str) -> std::io::Result<()> {
|
||||
fs::create_dir_all(source.join(".agents/plugins"))?;
|
||||
fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?;
|
||||
fs::write(
|
||||
source.join(".agents/plugins/marketplace.json"),
|
||||
r#"{
|
||||
"name": "debug",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "sample",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/sample"
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
)?;
|
||||
fs::write(
|
||||
source.join("plugins/sample/.codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample"}"#,
|
||||
)?;
|
||||
fs::write(source.join("plugins/sample/marker.txt"), marker)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
fs::create_dir_all(destination)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
let source_path = entry.path();
|
||||
let destination_path = destination.join(entry.file_name());
|
||||
if source_path.is_dir() {
|
||||
copy_dir_all(&source_path, &destination_path)?;
|
||||
} else {
|
||||
fs::copy(&source_path, &destination_path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
133
codex-rs/core-plugins/src/marketplace_add/install.rs
Normal file
133
codex-rs/core-plugins/src/marketplace_add/install.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use super::MarketplaceAddError;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn clone_git_source(
|
||||
url: &str,
|
||||
ref_name: Option<&str>,
|
||||
sparse_paths: &[String],
|
||||
destination: &Path,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let destination_string = destination.to_string_lossy().to_string();
|
||||
if sparse_paths.is_empty() {
|
||||
run_git(
|
||||
&["clone", url, destination_string.as_str()],
|
||||
/*cwd*/ None,
|
||||
)?;
|
||||
if let Some(ref_name) = ref_name {
|
||||
run_git(
|
||||
&["checkout", ref_name],
|
||||
Some(Path::new(&destination_string)),
|
||||
)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
run_git(
|
||||
&[
|
||||
"clone",
|
||||
"--filter=blob:none",
|
||||
"--no-checkout",
|
||||
url,
|
||||
destination_string.as_str(),
|
||||
],
|
||||
/*cwd*/ None,
|
||||
)?;
|
||||
let mut sparse_args = vec!["sparse-checkout", "set"];
|
||||
sparse_args.extend(sparse_paths.iter().map(String::as_str));
|
||||
run_git(&sparse_args, Some(destination))?;
|
||||
run_git(&["checkout", ref_name.unwrap_or("HEAD")], Some(destination))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn safe_marketplace_dir_name(
|
||||
marketplace_name: &str,
|
||||
) -> Result<String, MarketplaceAddError> {
|
||||
let safe = marketplace_name
|
||||
.chars()
|
||||
.map(|ch| {
|
||||
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {
|
||||
ch
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
let safe = safe.trim_matches('.').to_string();
|
||||
if safe.is_empty() || safe == ".." {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace name '{marketplace_name}' cannot be used as an install directory"
|
||||
)));
|
||||
}
|
||||
Ok(safe)
|
||||
}
|
||||
|
||||
pub(super) fn ensure_marketplace_destination_is_inside_install_root(
|
||||
install_root: &Path,
|
||||
destination: &Path,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let install_root = install_root.canonicalize().map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve marketplace install root {}: {err}",
|
||||
install_root.display()
|
||||
))
|
||||
})?;
|
||||
let destination_parent = destination
|
||||
.parent()
|
||||
.ok_or_else(|| {
|
||||
MarketplaceAddError::Internal("marketplace destination has no parent".to_string())
|
||||
})?
|
||||
.canonicalize()
|
||||
.map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to resolve marketplace destination parent {}: {err}",
|
||||
destination.display()
|
||||
))
|
||||
})?;
|
||||
if !destination_parent.starts_with(&install_root) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace destination {} is outside install root {}",
|
||||
destination.display(),
|
||||
install_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn replace_marketplace_root(
|
||||
staged_root: &Path,
|
||||
destination: &Path,
|
||||
) -> std::io::Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::rename(staged_root, destination)
|
||||
}
|
||||
|
||||
fn run_git(args: &[&str], cwd: Option<&Path>) -> Result<(), MarketplaceAddError> {
|
||||
let mut command = codex_utils_process::background_command("git");
|
||||
command
|
||||
.args(["-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG])
|
||||
.args(args);
|
||||
command.env("GIT_TERMINAL_PROMPT", "0");
|
||||
if let Some(cwd) = cwd {
|
||||
command.current_dir(cwd);
|
||||
}
|
||||
|
||||
let output = command.output().map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!("failed to run git {}: {err}", args.join(" ")))
|
||||
})?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
Err(MarketplaceAddError::Internal(format!(
|
||||
"git {} failed with status {}\nstdout:\n{}\nstderr:\n{}",
|
||||
args.join(" "),
|
||||
output.status,
|
||||
stdout.trim(),
|
||||
stderr.trim()
|
||||
)))
|
||||
}
|
||||
348
codex-rs/core-plugins/src/marketplace_add/metadata.rs
Normal file
348
codex-rs/core-plugins/src/marketplace_add/metadata.rs
Normal file
@@ -0,0 +1,348 @@
|
||||
use super::MarketplaceAddError;
|
||||
use super::source::MarketplaceSource;
|
||||
use crate::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::MarketplaceConfigUpdate;
|
||||
use codex_config::record_user_marketplace;
|
||||
use codex_utils_path::paths_match_after_normalization;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct MarketplaceInstallMetadata {
|
||||
source: InstalledMarketplaceSource,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum InstalledMarketplaceSource {
|
||||
Git {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
},
|
||||
Local {
|
||||
path: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) fn record_added_marketplace_entry(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
install_metadata: &MarketplaceInstallMetadata,
|
||||
) -> Result<(), MarketplaceAddError> {
|
||||
let source = install_metadata.config_source();
|
||||
let update = MarketplaceConfigUpdate {
|
||||
source_type: install_metadata.config_source_type(),
|
||||
source: &source,
|
||||
ref_name: install_metadata.ref_name(),
|
||||
sparse_paths: install_metadata.sparse_paths(),
|
||||
};
|
||||
|
||||
record_user_marketplace(codex_home, marketplace_name, &update).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to add marketplace '{marketplace_name}' to user config.toml: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn installed_marketplace_root_for_source(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
install_metadata: &MarketplaceInstallMetadata,
|
||||
) -> Result<Option<PathBuf>, MarketplaceAddError> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let config = match fs::read_to_string(&config_path) {
|
||||
Ok(config) => config,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"failed to read user config {}: {err}",
|
||||
config_path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let config: toml::Value = toml::from_str(&config).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to parse user config {}: {err}",
|
||||
config_path.display()
|
||||
))
|
||||
})?;
|
||||
let Some(marketplaces) = config.get("marketplaces").and_then(toml::Value::as_table) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
for (marketplace_name, marketplace) in marketplaces {
|
||||
if !install_metadata.matches_config(marketplace) {
|
||||
continue;
|
||||
}
|
||||
let root = match &install_metadata.source {
|
||||
// Keep using the resolved request path if the configured alias is retargeted.
|
||||
InstalledMarketplaceSource::Local { path } => PathBuf::from(path),
|
||||
InstalledMarketplaceSource::Git { .. } => install_root.join(marketplace_name),
|
||||
};
|
||||
if validate_marketplace_root(&root).is_ok() {
|
||||
return Ok(Some(root));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn find_marketplace_root_by_name(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
marketplace_name: &str,
|
||||
) -> Result<Option<PathBuf>, MarketplaceAddError> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let config = match fs::read_to_string(&config_path) {
|
||||
Ok(config) => config,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(MarketplaceAddError::Internal(format!(
|
||||
"failed to read user config {}: {err}",
|
||||
config_path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let config: toml::Value = toml::from_str(&config).map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to parse user config {}: {err}",
|
||||
config_path.display()
|
||||
))
|
||||
})?;
|
||||
let Some(marketplace) = config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let Some(root) =
|
||||
resolve_configured_marketplace_root(marketplace_name, marketplace, install_root)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if validate_marketplace_root(&root).is_ok() {
|
||||
Ok(Some(root))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl MarketplaceInstallMetadata {
|
||||
pub(super) fn from_source(source: &MarketplaceSource, sparse_paths: &[String]) -> Self {
|
||||
let source = match source {
|
||||
MarketplaceSource::Git { url, ref_name } => InstalledMarketplaceSource::Git {
|
||||
url: url.clone(),
|
||||
ref_name: ref_name.clone(),
|
||||
sparse_paths: sparse_paths.to_vec(),
|
||||
},
|
||||
MarketplaceSource::Local { path } => InstalledMarketplaceSource::Local {
|
||||
path: path.display().to_string(),
|
||||
},
|
||||
};
|
||||
Self { source }
|
||||
}
|
||||
|
||||
fn config_source_type(&self) -> &'static str {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { .. } => "git",
|
||||
InstalledMarketplaceSource::Local { .. } => "local",
|
||||
}
|
||||
}
|
||||
|
||||
fn config_source(&self) -> String {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { url, .. } => url.clone(),
|
||||
InstalledMarketplaceSource::Local { path } => path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn ref_name(&self) -> Option<&str> {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { ref_name, .. } => ref_name.as_deref(),
|
||||
InstalledMarketplaceSource::Local { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sparse_paths(&self) -> &[String] {
|
||||
match &self.source {
|
||||
InstalledMarketplaceSource::Git { sparse_paths, .. } => sparse_paths,
|
||||
InstalledMarketplaceSource::Local { .. } => &[],
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_config(&self, marketplace: &toml::Value) -> bool {
|
||||
marketplace.get("source_type").and_then(toml::Value::as_str)
|
||||
== Some(self.config_source_type())
|
||||
&& marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.is_some_and(|source| match &self.source {
|
||||
InstalledMarketplaceSource::Local { path } => {
|
||||
paths_match_after_normalization(source, path)
|
||||
}
|
||||
InstalledMarketplaceSource::Git { url, .. } => source == url,
|
||||
})
|
||||
&& marketplace.get("ref").and_then(toml::Value::as_str) == self.ref_name()
|
||||
&& config_sparse_paths(marketplace) == self.sparse_paths()
|
||||
}
|
||||
}
|
||||
|
||||
fn config_sparse_paths(marketplace: &toml::Value) -> Vec<String> {
|
||||
marketplace
|
||||
.get("sparse_paths")
|
||||
.and_then(toml::Value::as_array)
|
||||
.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(toml::Value::as_str)
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn installed_marketplace_root_for_source_propagates_config_read_errors() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
|
||||
fs::create_dir(&config_path).unwrap();
|
||||
|
||||
let install_root = codex_home.path().join("marketplaces");
|
||||
let source = MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
};
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]);
|
||||
|
||||
let err = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&install_metadata,
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string().contains(&format!(
|
||||
"failed to read user config {}:",
|
||||
config_path.display()
|
||||
)),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_marketplace_root_for_source_uses_local_source_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let install_root = codex_home.path().join("marketplaces");
|
||||
let source_root = codex_home.path().join("source");
|
||||
fs::create_dir_all(source_root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
source_root.join(".agents/plugins/marketplace.json"),
|
||||
r#"{"name":"debug","plugins":[]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let source = MarketplaceSource::Local {
|
||||
path: source_root.clone(),
|
||||
};
|
||||
let install_metadata = MarketplaceInstallMetadata::from_source(&source, &[]);
|
||||
record_added_marketplace_entry(codex_home.path(), "debug", &install_metadata).unwrap();
|
||||
|
||||
let root = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&install_metadata,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(root, Some(source_root));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn local_marketplace_matches_canonical_and_legacy_windows_sources() {
|
||||
let source = TempDir::new().unwrap();
|
||||
let other = TempDir::new().unwrap();
|
||||
let metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: source.path().canonicalize().unwrap(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let canonical = source.path().canonicalize().unwrap();
|
||||
let legacy =
|
||||
codex_utils_absolute_path::normalize_windows_device_path(&canonical.to_string_lossy())
|
||||
.unwrap();
|
||||
for spelling in [
|
||||
canonical.to_string_lossy().into_owned(),
|
||||
legacy.replace('\\', "/"),
|
||||
] {
|
||||
let config: toml::Value =
|
||||
toml::from_str(&format!("source_type = \"local\"\nsource = {spelling:?}\n"))
|
||||
.unwrap();
|
||||
assert!(metadata.matches_config(&config));
|
||||
}
|
||||
let different = other.path().to_string_lossy();
|
||||
let config: toml::Value = toml::from_str(&format!(
|
||||
"source_type = \"local\"\nsource = {different:?}\n"
|
||||
))
|
||||
.unwrap();
|
||||
assert!(!metadata.matches_config(&config));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn installed_local_root_does_not_follow_retargeted_configured_junction() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let source_root = codex_home.path().join("source");
|
||||
let other_root = codex_home.path().join("other");
|
||||
for (root, name) in [(&source_root, "source"), (&other_root, "other")] {
|
||||
fs::create_dir_all(root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
root.join(".agents/plugins/marketplace.json"),
|
||||
format!(r#"{{"name":"{name}","plugins":[]}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let alias = codex_home.path().join("configured-source");
|
||||
crate::test_support::create_directory_junction(&source_root, &alias);
|
||||
let configured_metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: alias.clone(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
record_added_marketplace_entry(codex_home.path(), "source", &configured_metadata).unwrap();
|
||||
let canonical_source = source_root.canonicalize().unwrap();
|
||||
let request_metadata = MarketplaceInstallMetadata::from_source(
|
||||
&MarketplaceSource::Local {
|
||||
path: canonical_source.clone(),
|
||||
},
|
||||
&[],
|
||||
);
|
||||
let root = installed_marketplace_root_for_source(
|
||||
codex_home.path(),
|
||||
&codex_home.path().join("marketplaces"),
|
||||
&request_metadata,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// Model an updater switching the alias before the caller validates the returned root.
|
||||
fs::remove_dir(&alias).unwrap();
|
||||
crate::test_support::create_directory_junction(&other_root, &alias);
|
||||
assert_eq!(root, canonical_source);
|
||||
assert_eq!(validate_marketplace_root(&root).unwrap(), "source");
|
||||
}
|
||||
}
|
||||
393
codex-rs/core-plugins/src/marketplace_add/source.rs
Normal file
393
codex-rs/core-plugins/src/marketplace_add/source.rs
Normal file
@@ -0,0 +1,393 @@
|
||||
use super::MarketplaceAddError;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum MarketplaceSource {
|
||||
Git {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
},
|
||||
Local {
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) fn parse_marketplace_source(
|
||||
source: &str,
|
||||
explicit_ref: Option<String>,
|
||||
) -> Result<MarketplaceSource, MarketplaceAddError> {
|
||||
let source = source.trim();
|
||||
if source.is_empty() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"marketplace source must not be empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let (base_source, parsed_ref) = split_source_ref(source);
|
||||
let ref_name = explicit_ref.or(parsed_ref);
|
||||
|
||||
if looks_like_local_path(&base_source) {
|
||||
if ref_name.is_some() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--ref is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
let path = resolve_local_source_path(&base_source)?;
|
||||
if path.is_file() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"local marketplace source must be a directory, not a file".to_string(),
|
||||
));
|
||||
}
|
||||
return Ok(MarketplaceSource::Local { path });
|
||||
}
|
||||
|
||||
if is_ssh_git_url(&base_source) || is_git_url(&base_source) {
|
||||
return Ok(MarketplaceSource::Git {
|
||||
url: normalize_git_url(&base_source),
|
||||
ref_name,
|
||||
});
|
||||
}
|
||||
|
||||
if looks_like_github_shorthand(&base_source) {
|
||||
return Ok(MarketplaceSource::Git {
|
||||
url: format!("https://github.com/{base_source}.git"),
|
||||
ref_name,
|
||||
});
|
||||
}
|
||||
|
||||
Err(MarketplaceAddError::InvalidRequest(
|
||||
"invalid marketplace source format; expected owner/repo, a git URL, or a local marketplace path"
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn stage_marketplace_source<F>(
|
||||
source: &MarketplaceSource,
|
||||
sparse_paths: &[String],
|
||||
staged_root: &Path,
|
||||
clone_source: F,
|
||||
) -> Result<(), MarketplaceAddError>
|
||||
where
|
||||
F: Fn(&str, Option<&str>, &[String], &Path) -> Result<(), MarketplaceAddError>,
|
||||
{
|
||||
if !sparse_paths.is_empty() && !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err(MarketplaceAddError::InvalidRequest(
|
||||
"--sparse is only supported for git marketplace sources".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
match source {
|
||||
MarketplaceSource::Git { url, ref_name } => {
|
||||
clone_source(url, ref_name.as_deref(), sparse_paths, staged_root)
|
||||
}
|
||||
MarketplaceSource::Local { .. } => unreachable!(
|
||||
"local marketplace sources are added without staging a copied install root"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_marketplace_source_root(root: &Path) -> Result<String, MarketplaceAddError> {
|
||||
let marketplace_name = validate_marketplace_root(root)
|
||||
.map_err(|err| MarketplaceAddError::InvalidRequest(err.to_string()))?;
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name")
|
||||
.map_err(MarketplaceAddError::InvalidRequest)?;
|
||||
Ok(marketplace_name)
|
||||
}
|
||||
|
||||
fn split_source_ref(source: &str) -> (String, Option<String>) {
|
||||
if let Some((base, ref_name)) = source.rsplit_once('#') {
|
||||
return (base.to_string(), non_empty_ref(ref_name));
|
||||
}
|
||||
if !looks_like_local_path(source)
|
||||
&& !source.contains("://")
|
||||
&& !is_ssh_git_url(source)
|
||||
&& let Some((base, ref_name)) = source.rsplit_once('@')
|
||||
{
|
||||
return (base.to_string(), non_empty_ref(ref_name));
|
||||
}
|
||||
(source.to_string(), None)
|
||||
}
|
||||
|
||||
fn non_empty_ref(ref_name: &str) -> Option<String> {
|
||||
let ref_name = ref_name.trim();
|
||||
(!ref_name.is_empty()).then(|| ref_name.to_string())
|
||||
}
|
||||
|
||||
fn normalize_git_url(url: &str) -> String {
|
||||
let url = url.trim_end_matches('/');
|
||||
if url.starts_with("https://github.com/") && !url.ends_with(".git") {
|
||||
format!("{url}.git")
|
||||
} else {
|
||||
url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_local_path(source: &str) -> bool {
|
||||
Path::new(source).is_absolute()
|
||||
|| looks_like_windows_absolute_path(source)
|
||||
|| source.starts_with("./")
|
||||
|| source.starts_with(".\\")
|
||||
|| source.starts_with("../")
|
||||
|| source.starts_with("..\\")
|
||||
|| source.starts_with("~/")
|
||||
|| source == "."
|
||||
|| source == ".."
|
||||
}
|
||||
|
||||
fn looks_like_windows_absolute_path(source: &str) -> bool {
|
||||
let bytes = source.as_bytes();
|
||||
bytes.len() >= 3
|
||||
&& bytes[0].is_ascii_alphabetic()
|
||||
&& bytes[1] == b':'
|
||||
&& matches!(bytes[2], b'\\' | b'/')
|
||||
|| source.starts_with(r"\\")
|
||||
}
|
||||
|
||||
fn resolve_local_source_path(source: &str) -> Result<PathBuf, MarketplaceAddError> {
|
||||
let path = expand_tilde_path(source);
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|err| {
|
||||
MarketplaceAddError::Internal(format!(
|
||||
"failed to read current working directory for local marketplace source: {err}"
|
||||
))
|
||||
})?
|
||||
.join(path)
|
||||
};
|
||||
|
||||
path.canonicalize().map_err(|err| {
|
||||
MarketplaceAddError::InvalidRequest(format!(
|
||||
"failed to resolve local marketplace source path: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn expand_tilde_path(source: &str) -> PathBuf {
|
||||
let Some(rest) = source.strip_prefix("~/") else {
|
||||
return PathBuf::from(source);
|
||||
};
|
||||
let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
|
||||
return PathBuf::from(source);
|
||||
};
|
||||
PathBuf::from(home).join(rest)
|
||||
}
|
||||
|
||||
fn is_ssh_git_url(source: &str) -> bool {
|
||||
source.starts_with("ssh://") || source.starts_with("git@") && source.contains(':')
|
||||
}
|
||||
|
||||
fn is_git_url(source: &str) -> bool {
|
||||
source.starts_with("http://") || source.starts_with("https://")
|
||||
}
|
||||
|
||||
fn looks_like_github_shorthand(source: &str) -> bool {
|
||||
let mut segments = source.split('/');
|
||||
let owner = segments.next();
|
||||
let repo = segments.next();
|
||||
let extra = segments.next();
|
||||
owner.is_some_and(is_github_shorthand_segment)
|
||||
&& repo.is_some_and(is_github_shorthand_segment)
|
||||
&& extra.is_none()
|
||||
}
|
||||
|
||||
fn is_github_shorthand_segment(segment: &str) -> bool {
|
||||
!segment.is_empty()
|
||||
&& segment
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
|
||||
}
|
||||
|
||||
impl MarketplaceSource {
|
||||
pub(crate) fn display(&self) -> String {
|
||||
match self {
|
||||
Self::Git { url, ref_name } => match ref_name {
|
||||
Some(ref_name) => format!("{url}#{ref_name}"),
|
||||
None => url.clone(),
|
||||
},
|
||||
Self::Local { path } => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn github_shorthand_parses_ref_suffix() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("owner/repo@main", /*explicit_ref*/ None).unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_url_parses_fragment_ref() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source(
|
||||
"https://example.com/team/repo.git#v1",
|
||||
/*explicit_ref*/ None
|
||||
)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://example.com/team/repo.git".to_string(),
|
||||
ref_name: Some("v1".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_ref_overrides_source_ref() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("owner/repo@main", Some("release".to_string())).unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("release".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_shorthand_and_git_url_normalize_to_same_source() {
|
||||
let shorthand = parse_marketplace_source("owner/repo", /*explicit_ref*/ None).unwrap();
|
||||
let git_url = parse_marketplace_source(
|
||||
"https://github.com/owner/repo.git",
|
||||
/*explicit_ref*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(shorthand, git_url);
|
||||
assert_eq!(
|
||||
shorthand,
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_url_with_trailing_slash_normalizes_without_extra_path_segment() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("https://github.com/owner/repo/", /*explicit_ref*/ None)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/owner/repo.git".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_github_https_source_parses_as_git_url() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source("https://gitlab.com/owner/repo", /*explicit_ref*/ None)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "https://gitlab.com/owner/repo".to_string(),
|
||||
ref_name: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_url_source_is_rejected() {
|
||||
let err =
|
||||
parse_marketplace_source("file:///tmp/marketplace.git", /*explicit_ref*/ None)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("invalid marketplace source format"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_path_source_parses() {
|
||||
let source = parse_marketplace_source(".", /*explicit_ref*/ None).unwrap();
|
||||
|
||||
let MarketplaceSource::Local { path } = source else {
|
||||
panic!("expected local path source");
|
||||
};
|
||||
assert!(path.is_absolute());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_absolute_paths_look_like_local_paths_on_every_host() {
|
||||
assert!(looks_like_local_path(r"C:\Users\alice\marketplace"));
|
||||
assert!(looks_like_local_path("C:/Users/alice/marketplace"));
|
||||
assert!(looks_like_local_path(r"\\server\share\marketplace"));
|
||||
assert!(!looks_like_local_path(r"C:relative\path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_file_source_is_rejected() {
|
||||
let tempdir = TempDir::new().unwrap();
|
||||
let file = tempdir.path().join("marketplace.json");
|
||||
std::fs::write(&file, "{}").unwrap();
|
||||
|
||||
let err =
|
||||
parse_marketplace_source(file.to_str().unwrap(), /*explicit_ref*/ None).unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("local marketplace source must be a directory, not a file"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_git_sources_reject_ref_override() {
|
||||
let err = parse_marketplace_source("./marketplace", Some("main".to_string())).unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("--ref is only supported for git marketplace sources"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_git_sources_reject_sparse_checkout() {
|
||||
let path = std::env::current_dir().unwrap();
|
||||
let err = stage_marketplace_source(
|
||||
&MarketplaceSource::Local { path },
|
||||
&["plugins/foo".to_string()],
|
||||
Path::new("/tmp"),
|
||||
|_url, _ref_name, _sparse_paths, _staged_root| Ok(()),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("--sparse is only supported for git marketplace sources"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_url_parses_as_git_url() {
|
||||
assert_eq!(
|
||||
parse_marketplace_source(
|
||||
"ssh://git@github.com/owner/repo.git#main",
|
||||
/*explicit_ref*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
MarketplaceSource::Git {
|
||||
url: "ssh://git@github.com/owner/repo.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
167
codex-rs/core-plugins/src/marketplace_context.rs
Normal file
167
codex-rs/core-plugins/src/marketplace_context.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
//! Aggregates request-wide plugin settings and repository-scoped marketplaces.
|
||||
//!
|
||||
//! Marketplace paths and plugin sources use first-scope precedence, while plugin state is
|
||||
//! merged across scopes. Cache refresh reuses listed marketplaces and configured plugin identities.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Request-wide plugin settings and the ordered repository configurations for one marketplace request.
|
||||
#[derive(Clone)]
|
||||
pub struct PluginMarketplaceContext {
|
||||
pub global_config: PluginsConfigInput,
|
||||
pub scopes: Vec<PluginMarketplaceScope>,
|
||||
pub load_errors: Vec<MarketplaceListError>,
|
||||
}
|
||||
|
||||
/// A repository's effective configuration, or non-project configuration when no cwd was supplied.
|
||||
#[derive(Clone)]
|
||||
pub struct PluginMarketplaceScope {
|
||||
pub cwd: Option<AbsolutePathBuf>,
|
||||
pub config: PluginsConfigInput,
|
||||
}
|
||||
|
||||
impl PluginMarketplaceContext {
|
||||
pub fn plugins_enabled(&self) -> bool {
|
||||
self.global_config.plugins_enabled
|
||||
|| self.scopes.iter().any(|scope| scope.config.plugins_enabled)
|
||||
}
|
||||
|
||||
pub fn remote_plugins_enabled(&self) -> bool {
|
||||
self.global_config.plugins_enabled && self.global_config.remote_plugin_enabled
|
||||
}
|
||||
|
||||
pub(super) fn list_marketplaces(
|
||||
&self,
|
||||
manager: &PluginsManager,
|
||||
include_openai_curated: bool,
|
||||
) -> Result<ConfiguredMarketplaceListOutcome, MarketplaceError> {
|
||||
let mut plugin_states = ConfiguredPluginStates::default();
|
||||
for scope in self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
{
|
||||
let state = manager.configured_plugin_states(&scope.config);
|
||||
plugin_states.installed.extend(state.installed);
|
||||
plugin_states.enabled.extend(state.enabled);
|
||||
}
|
||||
|
||||
let mut combined = ConfiguredMarketplaceListOutcome {
|
||||
errors: self.load_errors.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut seen_marketplace_paths = HashSet::new();
|
||||
let mut seen_plugin_ids = HashSet::new();
|
||||
let mut seen_error_paths = combined
|
||||
.errors
|
||||
.iter()
|
||||
.map(|error| error.path.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
for scope in self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
{
|
||||
let outcome = manager.list_marketplaces_for_config_with_states(
|
||||
&scope.config,
|
||||
scope.cwd.as_slice(),
|
||||
include_openai_curated,
|
||||
&plugin_states,
|
||||
)?;
|
||||
for mut marketplace in outcome.marketplaces {
|
||||
if !seen_marketplace_paths.insert(marketplace.path.clone()) {
|
||||
continue;
|
||||
}
|
||||
marketplace
|
||||
.plugins
|
||||
.retain(|plugin| seen_plugin_ids.insert(plugin.id.clone()));
|
||||
if !marketplace.plugins.is_empty() {
|
||||
combined.marketplaces.push(marketplace);
|
||||
}
|
||||
}
|
||||
combined.errors.extend(
|
||||
outcome
|
||||
.errors
|
||||
.into_iter()
|
||||
.filter(|error| seen_error_paths.insert(error.path.clone())),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(combined)
|
||||
}
|
||||
|
||||
pub(super) fn non_curated_cache_refresh_request(
|
||||
&self,
|
||||
manager: &PluginsManager,
|
||||
marketplaces: &[ConfiguredMarketplace],
|
||||
mode: NonCuratedCacheRefreshMode,
|
||||
git_mode: PluginGitMode,
|
||||
) -> Option<NonCuratedCacheRefreshRequest> {
|
||||
let configured_plugin_key_set = self
|
||||
.scopes
|
||||
.iter()
|
||||
.filter(|scope| scope.config.plugins_enabled)
|
||||
.flat_map(|scope| {
|
||||
configured_plugins_from_stack(
|
||||
&scope.config.config_layer_stack,
|
||||
manager.codex_home.as_path(),
|
||||
)
|
||||
.into_keys()
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
let mut roots = Vec::new();
|
||||
let mut configured_plugin_keys = Vec::new();
|
||||
let mut configured_plugin_sources = Vec::new();
|
||||
|
||||
for marketplace in marketplaces {
|
||||
if is_openai_curated_marketplace_name(&marketplace.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for plugin in &marketplace.plugins {
|
||||
if !configured_plugin_key_set.contains(&plugin.id) {
|
||||
continue;
|
||||
}
|
||||
let local_version = if plugin.source.is_install_materialized() {
|
||||
plugin
|
||||
.manifest_fallback
|
||||
.as_ref()
|
||||
.and_then(MarketplacePluginManifestFallback::parse_for_listing)
|
||||
.and_then(|manifest| manifest.version)
|
||||
} else {
|
||||
plugin.local_version.clone()
|
||||
};
|
||||
configured_plugin_keys.push(plugin.id.clone());
|
||||
configured_plugin_sources.push(NonCuratedPluginSource {
|
||||
marketplace_path: marketplace.path.clone(),
|
||||
plugin_key: plugin.id.clone(),
|
||||
source: plugin.source.clone(),
|
||||
local_version,
|
||||
});
|
||||
}
|
||||
roots.push(marketplace.path.clone());
|
||||
}
|
||||
|
||||
if roots.is_empty() || configured_plugin_keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Refresh rediscovers sources in root order; retain listing's precedence.
|
||||
configured_plugin_keys.sort_unstable();
|
||||
configured_plugin_sources.sort_by(|left, right| {
|
||||
left.marketplace_path
|
||||
.cmp(&right.marketplace_path)
|
||||
.then_with(|| left.plugin_key.cmp(&right.plugin_key))
|
||||
});
|
||||
|
||||
Some(NonCuratedCacheRefreshRequest {
|
||||
roots,
|
||||
configured_plugin_keys,
|
||||
configured_plugin_sources,
|
||||
mode,
|
||||
git_mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
612
codex-rs/core-plugins/src/marketplace_policy.rs
Normal file
612
codex-rs/core-plugins/src/marketplace_policy.rs
Normal file
@@ -0,0 +1,612 @@
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME;
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use crate::is_openai_curated_marketplace_name;
|
||||
use crate::marketplace::marketplace_root_dir;
|
||||
use crate::marketplace_add::MarketplaceSource;
|
||||
use crate::marketplace_add::parse_marketplace_source;
|
||||
use crate::remote::RemotePluginScope;
|
||||
use crate::startup_sync::OPENAI_PLUGINS_GIT_URL;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::MarketplaceAllowedSourceKind;
|
||||
use codex_config::MarketplaceAllowedSourceToml;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::types::MarketplaceConfig;
|
||||
use codex_config::types::MarketplaceSourceType;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_config::types::PluginsConfigToml;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path::paths_match_after_normalization;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use url::Url;
|
||||
|
||||
enum AllowedMarketplaceSource {
|
||||
GitUrl {
|
||||
url: String,
|
||||
ref_name: Option<String>,
|
||||
},
|
||||
GitHostPattern(Regex),
|
||||
Local(AbsolutePathBuf),
|
||||
}
|
||||
|
||||
pub(crate) struct MarketplacePolicy {
|
||||
restricted: Option<RestrictedMarketplacePolicy>,
|
||||
}
|
||||
|
||||
struct RestrictedMarketplacePolicy {
|
||||
allowed_sources: Result<Vec<AllowedMarketplaceSource>, String>,
|
||||
source: RequirementSource,
|
||||
}
|
||||
|
||||
impl MarketplacePolicy {
|
||||
pub(crate) fn from_requirements(requirements: &ConfigRequirements) -> Self {
|
||||
let Some(requirements) = requirements.marketplaces.as_ref().filter(|requirements| {
|
||||
requirements
|
||||
.value
|
||||
.restrict_to_allowed_sources
|
||||
.unwrap_or(false)
|
||||
}) else {
|
||||
return Self { restricted: None };
|
||||
};
|
||||
|
||||
let allowed_sources = requirements
|
||||
.value
|
||||
.allowed_sources
|
||||
.iter()
|
||||
.map(|(key, allowed_source)| {
|
||||
compile_allowed_source(key, allowed_source, &requirements.source)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
restricted: Some(RestrictedMarketplacePolicy {
|
||||
allowed_sources,
|
||||
source: requirements.source.clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_restricted(&self) -> bool {
|
||||
self.restricted.is_some()
|
||||
}
|
||||
|
||||
fn validate_source(&self, source: &MarketplaceSource) -> Result<(), String> {
|
||||
let Some(RestrictedMarketplacePolicy {
|
||||
allowed_sources,
|
||||
source: requirement_source,
|
||||
}) = &self.restricted
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let allowed_sources = allowed_sources.as_ref().map_err(Clone::clone)?;
|
||||
if allowed_sources
|
||||
.iter()
|
||||
.any(|allowed_source| allowed_source.matches(source))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"marketplace source `{}` is not allowed by requirements from {requirement_source}",
|
||||
source.display()
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_install(
|
||||
&self,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
let root = marketplace_root_dir(marketplace_path).map_err(|err| err.to_string())?;
|
||||
if let Some(expected_name) = managed_marketplace_name(codex_home, marketplace_path, &root) {
|
||||
if is_openai_curated_marketplace_name(expected_name) {
|
||||
self.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)?;
|
||||
}
|
||||
return validate_expected_marketplace_name(expected_name, marketplace_name);
|
||||
}
|
||||
if is_reserved_marketplace_name(marketplace_name) {
|
||||
return Err(format!(
|
||||
"marketplace `{marketplace_name}` is reserved and cannot be loaded from this source"
|
||||
));
|
||||
}
|
||||
if !self.is_restricted() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let marketplace = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"marketplace `{marketplace_name}` must be added to config before plugins can be installed while marketplace source restrictions are enabled"
|
||||
)
|
||||
})?;
|
||||
self.validate_configured_marketplace(marketplace_name, marketplace)?;
|
||||
|
||||
let configured_root = resolve_configured_marketplace_root(
|
||||
marketplace_name,
|
||||
marketplace,
|
||||
&marketplace_install_root(codex_home),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
format!("configured marketplace `{marketplace_name}` does not have a usable root")
|
||||
})?;
|
||||
if !paths_match_after_normalization(&configured_root, root.as_path()) {
|
||||
return Err(format!(
|
||||
"marketplace path `{}` does not match configured marketplace `{marketplace_name}`",
|
||||
root.as_path().display()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn validate_git_source(
|
||||
&self,
|
||||
source: &str,
|
||||
ref_name: Option<String>,
|
||||
) -> Result<Option<MarketplaceSource>, String> {
|
||||
if !self.is_restricted() {
|
||||
return Ok(None);
|
||||
}
|
||||
let source = parse_marketplace_source(source, ref_name).map_err(|err| err.to_string())?;
|
||||
if !matches!(source, MarketplaceSource::Git { .. }) {
|
||||
return Err("configured Git marketplace source is not a Git URL".to_string());
|
||||
}
|
||||
self.validate_source(&source)?;
|
||||
Ok(Some(source))
|
||||
}
|
||||
|
||||
fn validate_configured_marketplace(
|
||||
&self,
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<(), String> {
|
||||
let source = configured_marketplace_source(marketplace_name, marketplace)?;
|
||||
self.validate_source(&source)
|
||||
}
|
||||
}
|
||||
|
||||
impl AllowedMarketplaceSource {
|
||||
fn matches(&self, source: &MarketplaceSource) -> bool {
|
||||
match (self, source) {
|
||||
(
|
||||
Self::GitUrl {
|
||||
url: allowed_url,
|
||||
ref_name: allowed_ref,
|
||||
},
|
||||
MarketplaceSource::Git { url, ref_name },
|
||||
) => {
|
||||
allowed_url == url
|
||||
&& allowed_ref
|
||||
.as_ref()
|
||||
.is_none_or(|allowed_ref| Some(allowed_ref) == ref_name.as_ref())
|
||||
}
|
||||
(Self::GitHostPattern(pattern), MarketplaceSource::Git { url, .. }) => {
|
||||
git_hostname(url).is_some_and(|hostname| pattern.is_match(&hostname))
|
||||
}
|
||||
(Self::Local(allowed), MarketplaceSource::Local { path }) => {
|
||||
paths_match_after_normalization(allowed.as_path(), path)
|
||||
}
|
||||
(Self::GitUrl { .. } | Self::GitHostPattern(_), MarketplaceSource::Local { .. })
|
||||
| (Self::Local(_), MarketplaceSource::Git { .. }) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn policy_filtered_plugin_config(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> Option<toml::Value> {
|
||||
let mut effective_config = config_layer_stack.effective_config();
|
||||
if effective_config.get("plugins").is_none() && effective_config.get("marketplaces").is_none() {
|
||||
return None;
|
||||
}
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
let allowed_marketplace_names =
|
||||
allowed_configured_marketplace_names_with_policy(&effective_config, &policy, codex_home);
|
||||
let configured_marketplace_names = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.map(|marketplaces| marketplaces.keys().cloned().collect::<HashSet<_>>())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(marketplaces) = effective_config
|
||||
.get_mut("marketplaces")
|
||||
.and_then(toml::Value::as_table_mut)
|
||||
{
|
||||
marketplaces
|
||||
.retain(|marketplace_name, _| allowed_marketplace_names.contains(marketplace_name));
|
||||
}
|
||||
if let Some(plugins) = effective_config
|
||||
.get_mut("plugins")
|
||||
.and_then(toml::Value::as_table_mut)
|
||||
{
|
||||
plugins.retain(|plugin_key, _| {
|
||||
if plugin_key == "_default" {
|
||||
return true;
|
||||
}
|
||||
let Ok(plugin_id) = PluginId::parse(plugin_key) else {
|
||||
return !policy.is_restricted();
|
||||
};
|
||||
let marketplace_name = &plugin_id.marketplace_name;
|
||||
if configured_marketplace_names.contains(marketplace_name) {
|
||||
return allowed_marketplace_names.contains(marketplace_name);
|
||||
}
|
||||
if is_openai_curated_marketplace_name(marketplace_name) {
|
||||
return policy
|
||||
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
|
||||
.is_ok();
|
||||
}
|
||||
!policy.is_restricted()
|
||||
});
|
||||
}
|
||||
Some(effective_config)
|
||||
}
|
||||
|
||||
pub fn allowed_configured_marketplace_names(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> HashSet<String> {
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
allowed_configured_marketplace_names_with_policy(&effective_config, &policy, codex_home)
|
||||
}
|
||||
|
||||
fn allowed_configured_marketplace_names_with_policy(
|
||||
effective_config: &toml::Value,
|
||||
policy: &MarketplacePolicy,
|
||||
codex_home: &Path,
|
||||
) -> HashSet<String> {
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return HashSet::new();
|
||||
};
|
||||
marketplaces
|
||||
.iter()
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
let allowed = match managed_marketplace_config_name(codex_home, marketplace) {
|
||||
Some(expected_name) => expected_name == marketplace_name,
|
||||
None if is_reserved_marketplace_name(marketplace_name) => false,
|
||||
None if !policy.is_restricted() => true,
|
||||
None => policy
|
||||
.validate_configured_marketplace(marketplace_name, marketplace)
|
||||
.is_ok(),
|
||||
};
|
||||
allowed.then(|| marketplace_name.clone())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn configured_plugins_from_stack(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &Path,
|
||||
) -> HashMap<String, PluginConfig> {
|
||||
let Some(effective_config) = policy_filtered_plugin_config(config_layer_stack, codex_home)
|
||||
else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(plugins_value) = effective_config.get("plugins") else {
|
||||
return HashMap::new();
|
||||
};
|
||||
match PluginsConfigToml::deserialize(plugins_value.clone()) {
|
||||
Ok(plugins) => plugins.plugins,
|
||||
Err(err) => {
|
||||
tracing::warn!("invalid plugins config: {err}");
|
||||
HashMap::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_marketplace_source_for_add(
|
||||
codex_home: &Path,
|
||||
requirements: &ConfigRequirements,
|
||||
source: &MarketplaceSource,
|
||||
) -> Result<Option<&'static str>, String> {
|
||||
let policy = MarketplacePolicy::from_requirements(requirements);
|
||||
if let MarketplaceSource::Local { path } = source
|
||||
&& let Some(expected_name) = managed_local_marketplace_name(codex_home, path)
|
||||
{
|
||||
return Ok(Some(expected_name));
|
||||
}
|
||||
if !policy.is_restricted() {
|
||||
return Ok(None);
|
||||
}
|
||||
policy.validate_source(source)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_marketplace_name_for_add(
|
||||
expected_name: Option<&'static str>,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
if let Some(expected_name) = expected_name {
|
||||
return validate_expected_marketplace_name(expected_name, marketplace_name);
|
||||
}
|
||||
if is_reserved_marketplace_name(marketplace_name) {
|
||||
return Err(format!(
|
||||
"marketplace `{marketplace_name}` is reserved and cannot be added from this source"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_allowed_source(
|
||||
key: &str,
|
||||
allowed_source: &MarketplaceAllowedSourceToml,
|
||||
requirement_source: &RequirementSource,
|
||||
) -> Result<AllowedMarketplaceSource, String> {
|
||||
let invalid = |reason: &str| {
|
||||
format!("invalid marketplace allowed source `{key}` in {requirement_source}: {reason}")
|
||||
};
|
||||
let source = allowed_source
|
||||
.source
|
||||
.ok_or_else(|| invalid("missing source"))?;
|
||||
match source {
|
||||
MarketplaceAllowedSourceKind::Git => {
|
||||
let url = allowed_source
|
||||
.url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|url| !url.is_empty())
|
||||
.ok_or_else(|| invalid("missing url"))?;
|
||||
let ref_name = match allowed_source.ref_name.as_deref() {
|
||||
Some(ref_name) if ref_name.trim().is_empty() => {
|
||||
return Err(invalid("ref must not be empty"));
|
||||
}
|
||||
Some(ref_name) => Some(ref_name.trim().to_string()),
|
||||
None => None,
|
||||
};
|
||||
let source =
|
||||
parse_marketplace_source(url, ref_name).map_err(|err| invalid(&err.to_string()))?;
|
||||
let MarketplaceSource::Git { url, ref_name } = source else {
|
||||
return Err(invalid("expected a Git URL"));
|
||||
};
|
||||
Ok(AllowedMarketplaceSource::GitUrl { url, ref_name })
|
||||
}
|
||||
MarketplaceAllowedSourceKind::HostPattern => {
|
||||
let host_pattern = allowed_source
|
||||
.host_pattern
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|host_pattern| !host_pattern.is_empty())
|
||||
.ok_or_else(|| invalid("missing host_pattern"))?;
|
||||
Regex::new(host_pattern)
|
||||
.map(AllowedMarketplaceSource::GitHostPattern)
|
||||
.map_err(|err| invalid(&err.to_string()))
|
||||
}
|
||||
MarketplaceAllowedSourceKind::Local => {
|
||||
let path = allowed_source
|
||||
.path
|
||||
.as_ref()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.ok_or_else(|| invalid("missing path"))?;
|
||||
if !path.is_absolute() {
|
||||
return Err(invalid("local path must be absolute"));
|
||||
}
|
||||
let path = AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
.map_err(|_| invalid("local path must be absolute"))?;
|
||||
Ok(AllowedMarketplaceSource::Local(path))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn configured_marketplace_source(
|
||||
marketplace_name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<MarketplaceSource, String> {
|
||||
let MarketplaceConfig {
|
||||
source_type,
|
||||
source,
|
||||
ref_name,
|
||||
..
|
||||
} = marketplace
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|err| format!("invalid config for marketplace `{marketplace_name}`: {err}"))?;
|
||||
let source_type = source_type.ok_or_else(|| {
|
||||
format!("configured marketplace `{marketplace_name}` is missing source_type")
|
||||
})?;
|
||||
let source = source
|
||||
.ok_or_else(|| format!("configured marketplace `{marketplace_name}` is missing source"))?;
|
||||
match source_type {
|
||||
MarketplaceSourceType::Local => Ok(MarketplaceSource::Local {
|
||||
path: PathBuf::from(source),
|
||||
}),
|
||||
MarketplaceSourceType::Git => {
|
||||
let parsed = parse_marketplace_source(&source, ref_name).map_err(|err| {
|
||||
format!("invalid source for marketplace `{marketplace_name}`: {err}")
|
||||
})?;
|
||||
if matches!(parsed, MarketplaceSource::Git { .. }) {
|
||||
Ok(parsed)
|
||||
} else {
|
||||
Err(format!(
|
||||
"configured marketplace `{marketplace_name}` source does not match source_type `git`"
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_expected_marketplace_name(
|
||||
expected_name: &str,
|
||||
marketplace_name: &str,
|
||||
) -> Result<(), String> {
|
||||
(marketplace_name == expected_name)
|
||||
.then_some(())
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"marketplace manifest name `{marketplace_name}` does not match managed marketplace `{expected_name}`"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn is_reserved_marketplace_name(marketplace_name: &str) -> bool {
|
||||
matches!(
|
||||
marketplace_name,
|
||||
OPENAI_CURATED_MARKETPLACE_NAME
|
||||
| OPENAI_API_CURATED_MARKETPLACE_NAME
|
||||
| OPENAI_BUNDLED_MARKETPLACE_NAME
|
||||
| OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME
|
||||
| OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME
|
||||
) || RemotePluginScope::from_marketplace_name(marketplace_name).is_some()
|
||||
}
|
||||
|
||||
fn managed_marketplace_name(
|
||||
codex_home: &Path,
|
||||
marketplace_path: &AbsolutePathBuf,
|
||||
root: &AbsolutePathBuf,
|
||||
) -> Option<&'static str> {
|
||||
if is_expected_managed_path(
|
||||
marketplace_path.as_path(),
|
||||
&curated_plugins_api_marketplace_path(codex_home),
|
||||
) && is_expected_managed_path(root.as_path(), &curated_plugins_repo_path(codex_home))
|
||||
{
|
||||
return Some(OPENAI_API_CURATED_MARKETPLACE_NAME);
|
||||
}
|
||||
if is_expected_managed_path(root.as_path(), &curated_plugins_repo_path(codex_home)) {
|
||||
return Some(OPENAI_CURATED_MARKETPLACE_NAME);
|
||||
}
|
||||
managed_local_marketplace_name(codex_home, root.as_path())
|
||||
}
|
||||
|
||||
fn managed_marketplace_config_name(
|
||||
codex_home: &Path,
|
||||
marketplace: &toml::Value,
|
||||
) -> Option<&'static str> {
|
||||
if marketplace.get("source_type").and_then(toml::Value::as_str) != Some("local") {
|
||||
return None;
|
||||
}
|
||||
let path = marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.map(Path::new)
|
||||
.filter(|path| path.is_absolute())?;
|
||||
managed_local_marketplace_name(codex_home, path)
|
||||
}
|
||||
|
||||
fn managed_local_marketplace_name(codex_home: &Path, root: &Path) -> Option<&'static str> {
|
||||
for marketplace_name in [
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
] {
|
||||
let expected_root = codex_home
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(marketplace_name);
|
||||
if is_expected_managed_path(root, &expected_root) {
|
||||
return Some(marketplace_name);
|
||||
}
|
||||
}
|
||||
|
||||
let runtime_root = primary_runtime_marketplace_root()?;
|
||||
is_expected_managed_path(root, &runtime_root).then_some(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME)
|
||||
}
|
||||
|
||||
fn is_expected_managed_path(path: &Path, expected: &Path) -> bool {
|
||||
if path == expected {
|
||||
return true;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
path.strip_prefix("/private/var")
|
||||
.is_ok_and(|suffix| Path::new("/var").join(suffix) == expected)
|
||||
|| expected
|
||||
.strip_prefix("/private/var")
|
||||
.is_ok_and(|suffix| Path::new("/var").join(suffix) == path)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let path = path.to_string_lossy();
|
||||
let path = codex_utils_absolute_path::normalize_windows_device_path(&path)
|
||||
.unwrap_or_else(|| path.into_owned())
|
||||
.replace('/', "\\");
|
||||
// Resolve only the owned root; arbitrary aliases must not borrow managed provenance.
|
||||
let canonical_expected = expected.canonicalize().ok();
|
||||
std::iter::once(expected)
|
||||
.chain(canonical_expected.as_deref())
|
||||
.any(|expected| {
|
||||
let expected = expected.to_string_lossy();
|
||||
let expected = codex_utils_absolute_path::normalize_windows_device_path(&expected)
|
||||
.unwrap_or_else(|| expected.into_owned());
|
||||
path.eq_ignore_ascii_case(&expected.replace('/', "\\"))
|
||||
})
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn primary_runtime_marketplace_root() -> Option<PathBuf> {
|
||||
Some(
|
||||
primary_runtime_cache_dir()?
|
||||
.join("codex-runtimes/codex-primary-runtime/plugins")
|
||||
.join(OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
primary_runtime_cache_dir_from_user_profile(std::env::var_os("USERPROFILE").map(PathBuf::from))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn primary_runtime_cache_dir_from_user_profile(user_profile: Option<PathBuf>) -> Option<PathBuf> {
|
||||
user_profile.map(|profile| profile.join(".cache"))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
dirs::home_dir().map(|home| home.join(".cache"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn primary_runtime_cache_dir() -> Option<PathBuf> {
|
||||
dirs::cache_dir()
|
||||
}
|
||||
|
||||
fn git_hostname(url: &str) -> Option<String> {
|
||||
// Url treats backslashes as HTTP(S) path separators, but Git/libcurl does not.
|
||||
// A backslash anywhere in userinfo can therefore hide the host after the final @.
|
||||
if let Some(authority_and_path) = url
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| url.strip_prefix("https://"))
|
||||
{
|
||||
let authority = authority_and_path
|
||||
.trim_start_matches('/')
|
||||
.split(['/', '?', '#'])
|
||||
.next()?;
|
||||
if let Some((userinfo, _)) = authority.rsplit_once('@')
|
||||
&& userinfo.contains('\\')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Ok(url) = Url::parse(url) {
|
||||
return url.host_str().map(str::to_ascii_lowercase);
|
||||
}
|
||||
let (_, host_and_path) = url.split_once('@')?;
|
||||
let (hostname, _) = host_and_path.split_once(':')?;
|
||||
(!hostname.is_empty()).then(|| hostname.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_policy_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Exercises curated Git requirements across discovery, installation, cached loading, and sync.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[path = "curated_skill_tests.rs"]
|
||||
mod skills;
|
||||
|
||||
#[tokio::test]
|
||||
async fn curated_git_policy_controls_catalog_install_and_cached_activation() {
|
||||
for (name, auth) in [
|
||||
(OPENAI_CURATED_MARKETPLACE_NAME, AuthMode::Chatgpt),
|
||||
(OPENAI_API_CURATED_MARKETPLACE_NAME, AuthMode::ApiKey),
|
||||
] {
|
||||
let home = TempDir::new().unwrap();
|
||||
let root = curated_plugins_repo_path(home.path());
|
||||
write_openai_curated_marketplace(&root, &["sample"]);
|
||||
write_openai_api_curated_marketplace(&root, &["sample"]);
|
||||
write_curated_plugin_sha(home.path(), TEST_CURATED_PLUGIN_SHA);
|
||||
write_cached_plugin(home.path(), name, "sample");
|
||||
let user_config = format!("[plugins.\"sample@{name}\"]\nenabled = true\n");
|
||||
let allowed = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.curated]
|
||||
source = "git"
|
||||
url = "https://github.com/openai/plugins.git"
|
||||
"#,
|
||||
);
|
||||
let blocked = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n",
|
||||
);
|
||||
let host_allowed = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
&user_config,
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.github]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^github[.]com$'
|
||||
"#,
|
||||
);
|
||||
let manager = Arc::new(test_plugins_manager_with_options(
|
||||
home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(auth),
|
||||
));
|
||||
let manifest = if name == OPENAI_CURATED_MARKETPLACE_NAME {
|
||||
root.join(".agents/plugins/marketplace.json")
|
||||
} else {
|
||||
curated_plugins_api_marketplace_path(home.path())
|
||||
};
|
||||
for (config, permitted) in [(&allowed, true), (&blocked, false), (&host_allowed, true)] {
|
||||
let expected = if permitted {
|
||||
vec![format!("sample@{name}")]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(loaded_plugin_names(&manager, config).await, expected);
|
||||
let catalogs = manager
|
||||
.list_marketplaces_for_config(config, &[], /*include_openai_curated*/ true)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
catalogs
|
||||
.marketplaces
|
||||
.iter()
|
||||
.map(|catalog| catalog.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
if permitted { vec![name] } else { Vec::new() }
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.install_plugin(
|
||||
&config.config_layer_stack,
|
||||
PluginInstallRequest {
|
||||
plugin_name: "sample".to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from(manifest.clone()).unwrap(),
|
||||
}
|
||||
)
|
||||
.await
|
||||
.is_ok(),
|
||||
permitted
|
||||
);
|
||||
}
|
||||
manager.maybe_start_curated_repo_sync_for_config(
|
||||
&blocked, /*on_effective_plugins_changed*/ None,
|
||||
);
|
||||
assert!(!CURATED_REPO_SYNC_STARTED.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blocking_curated_git_does_not_block_remote_installed_plugins() {
|
||||
let home = TempDir::new().unwrap();
|
||||
write_cached_plugin(home.path(), REMOTE_GLOBAL_MARKETPLACE_NAME, "linear");
|
||||
let manager = test_plugins_manager_with_options(
|
||||
home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::Chatgpt),
|
||||
);
|
||||
manager.write_remote_installed_plugins_cache(vec![remote_installed_plugin("linear")]);
|
||||
let mut config = plugins_config_input_with_requirements(
|
||||
home.path(),
|
||||
"",
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n",
|
||||
);
|
||||
config.remote_plugin_enabled = true;
|
||||
assert_eq!(
|
||||
loaded_plugin_names(&manager, &config).await,
|
||||
vec!["linear@openai-curated-remote".to_string()]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Verifies managed curated Git restrictions through plugin and skill loading.
|
||||
|
||||
use std::fs;
|
||||
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::test_support::test_skill_root_loader;
|
||||
use anyhow::Result;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::test_support::auth_manager_from_optional_auth;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_skills::LoadedSkills;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::SkillRootLoadRequest;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn curated_git_requirements_control_plugin_skills() -> Result<()> {
|
||||
for (name, allow_curated) in [
|
||||
("openai-curated", true),
|
||||
("openai-curated", false),
|
||||
("openai-api-curated", true),
|
||||
("openai-api-curated", false),
|
||||
("openai-bundled", false),
|
||||
] {
|
||||
let home = TempDir::new()?;
|
||||
let plugin_id = format!("sample@{name}");
|
||||
let root = home
|
||||
.path()
|
||||
.join(format!("plugins/cache/{name}/sample/local"));
|
||||
fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
fs::write(
|
||||
root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample","description":"inspect sample data"}"#,
|
||||
)?;
|
||||
let skill_dir = root.join("skills/sample-search");
|
||||
fs::create_dir_all(&skill_dir)?;
|
||||
let skill_path = skill_dir.join("SKILL.md");
|
||||
fs::write(
|
||||
&skill_path,
|
||||
"---\ndescription: inspect sample data\n---\n\n# body\n",
|
||||
)?;
|
||||
let mut user_config = format!("[plugins.\"{plugin_id}\"]\nenabled = true\n");
|
||||
if name == "openai-bundled" {
|
||||
let bundled = home.path().join(".tmp/bundled-marketplaces/openai-bundled");
|
||||
user_config.push_str(&format!(
|
||||
"\n[marketplaces.openai-bundled]\nsource_type = \"local\"\nsource = {bundled:?}\n"
|
||||
));
|
||||
}
|
||||
fs::write(home.path().join("config.toml"), user_config)?;
|
||||
let requirements_path = home.path().join("requirements.toml");
|
||||
let rule = if allow_curated {
|
||||
"[marketplaces.allowed_sources.curated]\nsource = 'git'\nurl = 'https://github.com/openai/plugins.git'\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
fs::write(
|
||||
&requirements_path,
|
||||
format!("[marketplaces]\nrestrict_to_allowed_sources = true\n{rule}"),
|
||||
)?;
|
||||
let home_path = AbsolutePathBuf::try_from(home.path())?;
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
home.path(),
|
||||
Some(home_path),
|
||||
&[],
|
||||
LoaderOverrides {
|
||||
system_requirements_path: Some(requirements_path),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
},
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
let config = PluginsConfigInput::new(
|
||||
config_layer_stack.clone(),
|
||||
config_layer_stack
|
||||
.effective_config()
|
||||
.try_into::<codex_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ false,
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = if name == "openai-curated" {
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing()
|
||||
} else {
|
||||
CodexAuth::from_api_key("test-api-key")
|
||||
};
|
||||
let skills = test_skill_root_loader();
|
||||
let manager = PluginsManager::new(
|
||||
home.path().to_path_buf(),
|
||||
auth_manager_from_optional_auth(Some(auth)),
|
||||
skills.clone(),
|
||||
);
|
||||
let plugins = manager.plugins_for_config(&config).await;
|
||||
let loaded = skills
|
||||
.load_roots(SkillRootLoadRequest {
|
||||
roots: plugins.effective_plugin_skill_roots(),
|
||||
restriction_product: Some(Product::Codex),
|
||||
snapshots: manager.plugin_skill_snapshots_for_config(&config),
|
||||
})
|
||||
.await;
|
||||
let expected = if allow_curated || name == "openai-bundled" {
|
||||
LoadedSkills {
|
||||
skills: vec![SkillMetadata {
|
||||
name: "sample:sample-search".to_string(),
|
||||
description: "inspect sample data".to_string(),
|
||||
short_description: None,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&AbsolutePathBuf::try_from(
|
||||
fs::canonicalize(skill_path)?,
|
||||
)?),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(plugin_id),
|
||||
remote_plugin_id: None,
|
||||
}],
|
||||
errors: Vec::new(),
|
||||
}
|
||||
} else {
|
||||
LoadedSkills::default()
|
||||
};
|
||||
assert_eq!(
|
||||
loaded, expected,
|
||||
"marketplace={name}, allow_curated={allow_curated}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
108
codex-rs/core-plugins/src/marketplace_policy/curated_tests.rs
Normal file
108
codex-rs/core-plugins/src/marketplace_policy/curated_tests.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! Checks the shared curated Git identity while preserving other managed marketplace exemptions.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn curated_catalogs_apply_the_existing_git_source_policy() {
|
||||
let home = TempDir::new().unwrap();
|
||||
for (rule, allowed) in [
|
||||
("", false),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins.git'",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins'",
|
||||
true,
|
||||
),
|
||||
("source = 'git'\nurl = 'openai/plugins'", true),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/other/plugins.git'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'host_pattern'\nhost_pattern = '^github[.]com$'",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"source = 'host_pattern'\nhost_pattern = '^git[.]example[.]com$'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'https://github.com/openai/plugins.git'\nref = 'main'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"source = 'git'\nurl = 'openai/plugins'\n[marketplaces.allowed_sources.invalid]\nsource = 'host_pattern'\nhost_pattern = '('",
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let rule = if rule.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("[marketplaces.allowed_sources.curated]\n{rule}")
|
||||
};
|
||||
let stack = config_layer_stack(&format!(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n{rule}"
|
||||
));
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
for (name, manifest) in [
|
||||
(
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
curated_plugins_repo_path(home.path()).join(".agents/plugins/marketplace.json"),
|
||||
),
|
||||
(
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
curated_plugins_api_marketplace_path(home.path()),
|
||||
),
|
||||
] {
|
||||
let manifest = AbsolutePathBuf::try_from(manifest).unwrap();
|
||||
assert_eq!(
|
||||
policy
|
||||
.validate_install(&stack, home.path(), &manifest, name)
|
||||
.is_ok(),
|
||||
allowed
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_allowlist_cannot_authorize_curated_but_other_managed_sources_remain_allowed() {
|
||||
let home = TempDir::new().unwrap();
|
||||
let root = curated_plugins_repo_path(home.path());
|
||||
let stack = config_layer_stack(&format!(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = true\n[marketplaces.allowed_sources.local]\nsource = 'local'\npath = {root:?}"
|
||||
));
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
assert!(
|
||||
policy
|
||||
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
|
||||
.is_err()
|
||||
);
|
||||
// Windows test sandboxes may omit USERPROFILE, leaving no primary runtime cache root.
|
||||
let primary_runtime = primary_runtime_marketplace_root()
|
||||
.map(|root| (OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME, root));
|
||||
for (name, root) in [
|
||||
(
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
home.path().join(".tmp/bundled-marketplaces/openai-bundled"),
|
||||
),
|
||||
(
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
home.path()
|
||||
.join(".tmp/bundled-marketplaces/openai-bundled-alpha"),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(primary_runtime)
|
||||
{
|
||||
let manifest =
|
||||
AbsolutePathBuf::try_from(root.join(".agents/plugins/marketplace.json")).unwrap();
|
||||
assert_eq!(
|
||||
policy.validate_install(&stack, home.path(), &manifest, name),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
}
|
||||
853
codex-rs/core-plugins/src/marketplace_policy_tests.rs
Normal file
853
codex-rs/core-plugins/src/marketplace_policy_tests.rs
Normal file
@@ -0,0 +1,853 @@
|
||||
use super::*;
|
||||
use crate::marketplace_upgrade::upgrade_configured_git_marketplaces;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::RequirementsLayerEntry;
|
||||
use codex_config::compose_requirements;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[path = "marketplace_policy/curated_tests.rs"]
|
||||
mod curated;
|
||||
|
||||
fn config_layer_stack(requirements_toml: &str) -> ConfigLayerStack {
|
||||
config_layer_stack_with_user_config(requirements_toml, /*user_config*/ None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn primary_runtime_cache_uses_user_profile_on_windows() {
|
||||
assert_eq!(
|
||||
primary_runtime_cache_dir_from_user_profile(Some(PathBuf::from(r"C:\Users\user"))),
|
||||
Some(PathBuf::from(r"C:\Users\user\.cache"))
|
||||
);
|
||||
assert!(is_expected_managed_path(
|
||||
Path::new(r"\\?\c:\users\USER\.cache"),
|
||||
Path::new(r"C:\Users/user\.cache"),
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn managed_windows_root_accepts_redirected_target_but_not_unowned_alias() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let target = temp.path().join("redirected-cache");
|
||||
let owned = temp.path().join(".cache");
|
||||
let alias = temp.path().join("unowned-alias");
|
||||
let other = temp.path().join("different-source");
|
||||
fs::create_dir_all(&target).unwrap();
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
crate::test_support::create_directory_junction(&target, &owned);
|
||||
crate::test_support::create_directory_junction(&target, &alias);
|
||||
let canonical = owned.canonicalize().unwrap();
|
||||
assert!(is_expected_managed_path(&canonical, &owned));
|
||||
assert!(is_expected_managed_path(&owned, &owned));
|
||||
assert!(!is_expected_managed_path(&alias, &owned));
|
||||
assert!(!is_expected_managed_path(&other, &owned));
|
||||
}
|
||||
|
||||
fn config_layer_stack_with_user_config(
|
||||
requirements_toml: &str,
|
||||
user_config: Option<(&str, AbsolutePathBuf)>,
|
||||
) -> ConfigLayerStack {
|
||||
let with_sources = compose_requirements([RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
requirements_toml,
|
||||
)])
|
||||
.expect("compose requirements")
|
||||
.expect("requirements should be present");
|
||||
let requirements_toml = with_sources.clone().into_toml();
|
||||
let requirements =
|
||||
codex_config::ConfigRequirements::try_from(with_sources).expect("normalize requirements");
|
||||
let layers = user_config
|
||||
.map(|(contents, file)| {
|
||||
vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file,
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(contents).expect("parse user config"),
|
||||
)]
|
||||
})
|
||||
.unwrap_or_default();
|
||||
ConfigLayerStack::new(layers, requirements, requirements_toml)
|
||||
.expect("build config layer stack")
|
||||
}
|
||||
|
||||
fn parse_source(source: &str, ref_name: Option<&str>) -> MarketplaceSource {
|
||||
parse_marketplace_source(source, ref_name.map(str::to_string)).expect("parse source")
|
||||
}
|
||||
|
||||
fn validate_source(stack: &ConfigLayerStack, source: &MarketplaceSource) -> Result<(), String> {
|
||||
MarketplacePolicy::from_requirements(stack.requirements()).validate_source(source)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_git_rule_matches_url_and_ref() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins"
|
||||
ref = "main"
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source("https://github.com/example/plugins.git", Some("main")),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
for denied in [
|
||||
parse_source("https://github.com/example/plugins.git", Some("release")),
|
||||
parse_source("https://github.com/other/plugins.git", Some("main")),
|
||||
] {
|
||||
assert!(validate_source(&stack, &denied).is_err());
|
||||
}
|
||||
let normalized = MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_git_source("example/plugins", Some("main".to_string()))
|
||||
.expect("allowlisted shorthand should validate")
|
||||
.expect("restricted policy should normalize the source");
|
||||
assert_eq!(
|
||||
normalized,
|
||||
MarketplaceSource::Git {
|
||||
url: "https://github.com/example/plugins.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_rule_without_ref_allows_any_ref_for_the_same_repository() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins"
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source("https://github.com/example/plugins.git", Some("release")),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_host_pattern_matches_https_and_ssh_sources() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.internal]
|
||||
source = "host_pattern"
|
||||
host_pattern = '^git\.example\.com$'
|
||||
url = "https://github.com/example/ignored.git"
|
||||
ref = "ignored"
|
||||
"#,
|
||||
);
|
||||
|
||||
for source in [
|
||||
"http://git.example.com/team/plugins.git",
|
||||
"https://git.example.com/team/plugins.git",
|
||||
"https://user@git.example.com:8443/team/plugins.git",
|
||||
"https://user%5Cname@git.example.com/team/plugins.git",
|
||||
r"http://git.example.com/team\plugins.git",
|
||||
r"https://git.example.com/team\@plugins.git",
|
||||
r"https://git.example.com?repository=team\@plugins.git",
|
||||
"ssh://git@git.example.com/team/plugins.git",
|
||||
"git@git.example.com:team/plugins.git",
|
||||
] {
|
||||
assert_eq!(
|
||||
validate_source(&stack, &parse_source(source, /*ref_name*/ None)),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_local_rule_rejects_other_directories() {
|
||||
let allowed = TempDir::new().expect("create allowed marketplace directory");
|
||||
let denied = TempDir::new().expect("create denied marketplace directory");
|
||||
let allowed = allowed
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical allowed path");
|
||||
let denied = denied.path().canonicalize().expect("canonical denied path");
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.local]
|
||||
source = "local"
|
||||
path = {allowed:?}
|
||||
"#
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(allowed.to_string_lossy().as_ref(), /*ref_name*/ None),
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
validate_source(
|
||||
&stack,
|
||||
&parse_source(denied.to_string_lossy().as_ref(), /*ref_name*/ None),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restriction_flag_controls_empty_allowlist() {
|
||||
for (restricted, expected_allowed) in [(true, false), (false, true)] {
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = {restricted}
|
||||
"#
|
||||
));
|
||||
let result = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
);
|
||||
assert_eq!(result.is_ok(), expected_allowed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_marketplace_discovery_and_install_validate_source_and_root() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let configured_root = TempDir::new().expect("create configured marketplace");
|
||||
let other_root = TempDir::new().expect("create other marketplace");
|
||||
let configured_root = configured_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical configured root");
|
||||
let other_root = other_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical other root");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "local"
|
||||
path = {configured_root:?}
|
||||
"#
|
||||
),
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.company]
|
||||
source_type = "local"
|
||||
source = {configured_root:?}
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let layer = stack.layers_low_to_high().next().expect("configured layer");
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::System {
|
||||
file: AbsolutePathBuf::try_from(codex_home.path().join("system.toml")).unwrap(),
|
||||
},
|
||||
layer.config.clone(),
|
||||
)],
|
||||
stack.requirements().clone(),
|
||||
stack.requirements_toml().clone(),
|
||||
)
|
||||
.expect("system config stack");
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
let configured_path =
|
||||
AbsolutePathBuf::try_from(configured_root.join(".agents/plugins/marketplace.json"))
|
||||
.expect("configured marketplace path");
|
||||
let other_path = AbsolutePathBuf::try_from(other_root.join(".agents/plugins/marketplace.json"))
|
||||
.expect("other marketplace path");
|
||||
|
||||
fs::create_dir_all(configured_path.as_path().parent().unwrap()).unwrap();
|
||||
fs::write(&configured_path, r#"{"name":"company","plugins":[]}"#).unwrap();
|
||||
assert_eq!(
|
||||
crate::installed_marketplaces::installed_marketplace_roots_from_layer_stack(
|
||||
&stack,
|
||||
codex_home.path()
|
||||
),
|
||||
vec![AbsolutePathBuf::try_from(configured_root).unwrap()],
|
||||
);
|
||||
assert_eq!(
|
||||
policy.validate_install(&stack, codex_home.path(), &configured_path, "company"),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(&stack, codex_home.path(), &configured_path, "other")
|
||||
.expect_err("unconfigured name should fail")
|
||||
.contains("must be added to config")
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(&stack, codex_home.path(), &other_path, "company")
|
||||
.expect_err("mismatched root should fail")
|
||||
.contains("does not match configured marketplace")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_configured_source_is_not_installable() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.debug]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
"#,
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let marketplace_path = AbsolutePathBuf::try_from(
|
||||
marketplace_install_root(codex_home.path()).join("debug/.agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute marketplace path");
|
||||
|
||||
let err = MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_install(&stack, codex_home.path(), &marketplace_path, "debug")
|
||||
.expect_err("blocked marketplace install should fail");
|
||||
assert!(err.contains("is not allowed by requirements"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_relative_local_config_source_is_not_parsed_as_git_shorthand() {
|
||||
let marketplace: toml::Value = toml::from_str(
|
||||
r#"
|
||||
source_type = "local"
|
||||
source = "marketplaces/company"
|
||||
"#,
|
||||
)
|
||||
.expect("parse marketplace config");
|
||||
|
||||
assert_eq!(
|
||||
configured_marketplace_source("company", &marketplace),
|
||||
Ok(MarketplaceSource::Local {
|
||||
path: PathBuf::from("marketplaces/company"),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_marketplace_requires_its_expected_name() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
[marketplaces.allowed_sources.curated]
|
||||
source = "git"
|
||||
url = "https://github.com/openai/plugins.git"
|
||||
"#,
|
||||
);
|
||||
let marketplace_path = AbsolutePathBuf::try_from(
|
||||
curated_plugins_repo_path(codex_home.path()).join(".agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute marketplace path");
|
||||
let policy = MarketplacePolicy::from_requirements(stack.requirements());
|
||||
|
||||
assert_eq!(
|
||||
policy.validate_install(
|
||||
&stack,
|
||||
codex_home.path(),
|
||||
&marketplace_path,
|
||||
crate::OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert!(
|
||||
policy
|
||||
.validate_install(
|
||||
&stack,
|
||||
codex_home.path(),
|
||||
&marketplace_path,
|
||||
crate::OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let repository_manifest = AbsolutePathBuf::try_from(
|
||||
codex_home
|
||||
.path()
|
||||
.join("repository/.agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("absolute repository manifest");
|
||||
let unrestricted = ConfigLayerStack::default();
|
||||
for config in [&stack, &unrestricted] {
|
||||
for marketplace in [
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME,
|
||||
OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME,
|
||||
OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME,
|
||||
] {
|
||||
assert!(
|
||||
MarketplacePolicy::from_requirements(config.requirements())
|
||||
.validate_install(config, codex_home.path(), &repository_manifest, marketplace)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_marketplaces_cannot_borrow_managed_provenance() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let official_root = curated_plugins_repo_path(codex_home.path());
|
||||
let manifest = official_root.join(".agents/plugins/marketplace.json");
|
||||
fs::create_dir_all(manifest.parent().expect("manifest directory"))
|
||||
.expect("create manifest directory");
|
||||
fs::write(&manifest, "{}").expect("write official manifest");
|
||||
|
||||
let root_alias = codex_home.path().join("repository");
|
||||
std::os::unix::fs::symlink(&official_root, &root_alias).expect("symlink official root");
|
||||
let parent_alias = codex_home.path().join("parent-alias");
|
||||
std::os::unix::fs::symlink(
|
||||
official_root.parent().expect("official root parent"),
|
||||
&parent_alias,
|
||||
)
|
||||
.expect("symlink official root parent");
|
||||
let manifest_alias = codex_home
|
||||
.path()
|
||||
.join("manifest-alias/.agents/plugins/api_marketplace.json");
|
||||
fs::create_dir_all(manifest_alias.parent().expect("manifest alias parent"))
|
||||
.expect("create manifest alias directory");
|
||||
std::os::unix::fs::symlink(&manifest, &manifest_alias).expect("symlink official manifest");
|
||||
let stack = ConfigLayerStack::default();
|
||||
|
||||
for (path, marketplace) in [
|
||||
(
|
||||
root_alias.join(".agents/plugins/marketplace.json"),
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
(
|
||||
parent_alias.join("plugins/.agents/plugins/marketplace.json"),
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
),
|
||||
(manifest_alias, OPENAI_API_CURATED_MARKETPLACE_NAME),
|
||||
] {
|
||||
let manifest = AbsolutePathBuf::try_from(path).expect("absolute repository manifest");
|
||||
assert!(
|
||||
MarketplacePolicy::from_requirements(stack.requirements())
|
||||
.validate_install(&stack, codex_home.path(), &manifest, marketplace)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_bundled_source_is_bound_to_its_expected_name() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let bundled_root = codex_home
|
||||
.path()
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(crate::OPENAI_BUNDLED_MARKETPLACE_NAME);
|
||||
fs::create_dir_all(&bundled_root).expect("create bundled marketplace root");
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
);
|
||||
let source = parse_source(
|
||||
bundled_root.to_string_lossy().as_ref(),
|
||||
/*ref_name*/ None,
|
||||
);
|
||||
|
||||
let expected_name =
|
||||
validate_marketplace_source_for_add(codex_home.path(), stack.requirements(), &source)
|
||||
.expect("managed marketplace source should bypass restrictions");
|
||||
assert_eq!(
|
||||
validate_marketplace_name_for_add(expected_name, crate::OPENAI_BUNDLED_MARKETPLACE_NAME,),
|
||||
Ok(())
|
||||
);
|
||||
assert!(validate_marketplace_name_for_add(expected_name, "other").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_user_config_removes_blocked_marketplaces_and_plugins() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.company]
|
||||
source = "git"
|
||||
url = "https://github.com/example/allowed.git"
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.allowed]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/allowed.git"
|
||||
|
||||
[marketplaces.blocked]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
|
||||
[plugins."sample@allowed"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@blocked"]
|
||||
enabled = true
|
||||
"#,
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["allowed".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
configured_plugins_from_stack(&stack, codex_home.path())
|
||||
.into_keys()
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["sample@allowed".to_string()]
|
||||
);
|
||||
|
||||
let raw = stack.effective_user_config().expect("raw user config");
|
||||
assert!(raw["marketplaces"]["blocked"].is_table());
|
||||
assert!(raw["plugins"]["sample@blocked"].is_table());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_bundled_config_is_retained_only_at_its_owned_path() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let bundled_root = codex_home
|
||||
.path()
|
||||
.join(".tmp/bundled-marketplaces")
|
||||
.join(crate::OPENAI_BUNDLED_MARKETPLACE_NAME);
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.openai-bundled]
|
||||
source_type = "local"
|
||||
source = {bundled_root:?}
|
||||
|
||||
[marketplaces.openai-bundled-alpha]
|
||||
source_type = "local"
|
||||
source = "/tmp/not-managed"
|
||||
|
||||
[marketplaces.evil]
|
||||
source_type = "local"
|
||||
source = {bundled_root:?}
|
||||
|
||||
[plugins."sample@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@openai-bundled-alpha"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@evil"]
|
||||
enabled = true
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec![crate::OPENAI_BUNDLED_MARKETPLACE_NAME.to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
projected["plugins"]
|
||||
.as_table()
|
||||
.expect("projected plugins")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
vec![format!("sample@{}", crate::OPENAI_BUNDLED_MARKETPLACE_NAME)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlisted_sources_cannot_claim_reserved_marketplace_names() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let source_root = TempDir::new().expect("create marketplace root");
|
||||
let source_root = source_root
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical marketplace root");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.local]
|
||||
source = "local"
|
||||
path = {source_root:?}
|
||||
"#
|
||||
),
|
||||
Some((
|
||||
&format!(
|
||||
r#"
|
||||
[marketplaces.openai-bundled]
|
||||
source_type = "local"
|
||||
source = {source_root:?}
|
||||
|
||||
[marketplaces.openai-curated]
|
||||
source_type = "local"
|
||||
source = {source_root:?}
|
||||
|
||||
[plugins."sample@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."sample@openai-curated"]
|
||||
enabled = true
|
||||
"#
|
||||
),
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
|
||||
let projected =
|
||||
policy_filtered_plugin_config(&stack, codex_home.path()).expect("project plugin config");
|
||||
assert_eq!(
|
||||
projected["marketplaces"]
|
||||
.as_table()
|
||||
.expect("projected marketplaces")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
assert_eq!(
|
||||
projected["plugins"]
|
||||
.as_table()
|
||||
.expect("projected plugins")
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_or_reserved_upgrade_is_rejected_before_marketplace_installation() {
|
||||
let reload_config: crate::ConfigLayerReload =
|
||||
std::sync::Arc::new(|| panic!("blocked or reserved marketplace must not reload config"));
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let config_file = AbsolutePathBuf::try_from(codex_home.path().join("config.toml"))
|
||||
.expect("absolute config path");
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
"#,
|
||||
Some((
|
||||
r#"
|
||||
[marketplaces.debug]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/blocked.git"
|
||||
"#,
|
||||
config_file.clone(),
|
||||
)),
|
||||
);
|
||||
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("debug"),
|
||||
&reload_config,
|
||||
);
|
||||
|
||||
assert_eq!(outcome.selected_marketplaces, vec!["debug".to_string()]);
|
||||
assert_eq!(outcome.upgraded_roots, Vec::new());
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert!(
|
||||
outcome.errors[0]
|
||||
.message
|
||||
.contains("is not allowed by requirements")
|
||||
);
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
|
||||
let stack = config_layer_stack_with_user_config(
|
||||
"[marketplaces]\nrestrict_to_allowed_sources = false\n",
|
||||
Some((
|
||||
"[marketplaces.openai-bundled]\nsource_type = \"git\"\nsource = \"https://github.com/example/blocked.git\"\n",
|
||||
config_file,
|
||||
)),
|
||||
);
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some(crate::OPENAI_BUNDLED_MARKETPLACE_NAME),
|
||||
&reload_config,
|
||||
);
|
||||
assert!(outcome.errors[0].message.contains("is reserved"));
|
||||
assert!(!marketplace_install_root(codex_home.path()).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_active_rule_fails_closed_even_when_another_rule_matches() {
|
||||
let stack = config_layer_stack(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
|
||||
[marketplaces.allowed_sources.allowed]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins.git"
|
||||
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "host_pattern"
|
||||
host_pattern = "("
|
||||
"#,
|
||||
);
|
||||
|
||||
let err = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.expect_err("invalid active rule should fail closed");
|
||||
assert!(err.contains("invalid marketplace allowed source `invalid`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_allowed_source_shapes_fail_closed() {
|
||||
for (rule, expected_error) in [
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
url = "https://github.com/example/plugins.git"
|
||||
"#,
|
||||
"missing source",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "git"
|
||||
"#,
|
||||
"missing url",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "git"
|
||||
url = "https://github.com/example/plugins.git"
|
||||
ref = " "
|
||||
"#,
|
||||
"ref must not be empty",
|
||||
),
|
||||
(
|
||||
r#"
|
||||
[marketplaces.allowed_sources.invalid]
|
||||
source = "local"
|
||||
path = "../plugins"
|
||||
"#,
|
||||
"local path must be absolute",
|
||||
),
|
||||
] {
|
||||
let stack = config_layer_stack(&format!(
|
||||
r#"
|
||||
[marketplaces]
|
||||
restrict_to_allowed_sources = true
|
||||
{rule}
|
||||
"#
|
||||
));
|
||||
|
||||
let err = validate_source(
|
||||
&stack,
|
||||
&parse_source(
|
||||
"https://github.com/example/plugins.git",
|
||||
/*ref_name*/ None,
|
||||
),
|
||||
)
|
||||
.expect_err("invalid rule should fail closed");
|
||||
assert!(err.contains(expected_error), "{err}");
|
||||
}
|
||||
}
|
||||
403
codex-rs/core-plugins/src/marketplace_remove.rs
Normal file
403
codex-rs/core-plugins/src/marketplace_remove.rs
Normal file
@@ -0,0 +1,403 @@
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::RemoveMarketplaceConfigOutcome;
|
||||
use codex_config::format_config_layer_source;
|
||||
use codex_config::remove_user_marketplace_config;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceRemoveRequest {
|
||||
pub marketplace_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MarketplaceRemoveOutcome {
|
||||
pub marketplace_name: String,
|
||||
pub removed_installed_root: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MarketplaceRemoveError {
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
/// Removes a marketplace's snapshot and any base-user entry only when no other
|
||||
/// enabled layer in the current operation's config stack references its name.
|
||||
pub async fn remove_marketplace(
|
||||
codex_home: PathBuf,
|
||||
config_layer_stack: ConfigLayerStack,
|
||||
request: MarketplaceRemoveRequest,
|
||||
) -> Result<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
remove_marketplace_sync(codex_home.as_path(), &config_layer_stack, request)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!("failed to remove marketplace: {err}"))
|
||||
})?
|
||||
}
|
||||
|
||||
fn remove_marketplace_sync(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
request: MarketplaceRemoveRequest,
|
||||
) -> Result<MarketplaceRemoveOutcome, MarketplaceRemoveError> {
|
||||
let marketplace_name = request.marketplace_name;
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name")
|
||||
.map_err(MarketplaceRemoveError::InvalidRequest)?;
|
||||
|
||||
// Removing a user override must not delete a snapshot still referenced by
|
||||
// another enabled layer, including a lower-precedence layer it shadows.
|
||||
let user_config_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home);
|
||||
if let Some(layer) = config_layer_stack.layers_high_to_low().find(|layer| {
|
||||
!matches!(
|
||||
&layer.name,
|
||||
ConfigLayerSource::User { file, profile: None } if file == &user_config_file
|
||||
) && layer
|
||||
.config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.is_some_and(|marketplaces| {
|
||||
marketplaces
|
||||
.keys()
|
||||
.any(|name| name.eq_ignore_ascii_case(&marketplace_name))
|
||||
})
|
||||
}) {
|
||||
let source = format_config_layer_source(&layer.name, CONFIG_TOML_FILE);
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` is configured in {source}; remove it from that configuration source instead"
|
||||
)));
|
||||
}
|
||||
|
||||
let destination = marketplace_install_root(codex_home).join(&marketplace_name);
|
||||
let config_outcome =
|
||||
remove_user_marketplace_config(codex_home, &marketplace_name).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to remove marketplace '{marketplace_name}' from user config.toml: {err}"
|
||||
))
|
||||
})?;
|
||||
if let RemoveMarketplaceConfigOutcome::NameCaseMismatch { configured_name } = &config_outcome {
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` does not match configured marketplace `{configured_name}` exactly"
|
||||
)));
|
||||
}
|
||||
|
||||
let removed_config = config_outcome == RemoveMarketplaceConfigOutcome::Removed;
|
||||
let removed_installed_root = remove_marketplace_root(&destination)?;
|
||||
|
||||
if removed_installed_root.is_none() && !removed_config {
|
||||
return Err(MarketplaceRemoveError::InvalidRequest(format!(
|
||||
"marketplace `{marketplace_name}` is not configured or installed"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(MarketplaceRemoveOutcome {
|
||||
marketplace_name,
|
||||
removed_installed_root,
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_marketplace_root(root: &Path) -> Result<Option<AbsolutePathBuf>, MarketplaceRemoveError> {
|
||||
if !root.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let removed_root = AbsolutePathBuf::try_from(root.to_path_buf()).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to resolve installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let metadata = fs::symlink_metadata(root).map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to inspect installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
let remove_result = if metadata.is_dir() {
|
||||
fs::remove_dir_all(root)
|
||||
} else {
|
||||
fs::remove_file(root)
|
||||
};
|
||||
remove_result.map_err(|err| {
|
||||
MarketplaceRemoveError::Internal(format!(
|
||||
"failed to remove installed marketplace root {}: {err}",
|
||||
root.display()
|
||||
))
|
||||
})?;
|
||||
Ok(Some(removed_root))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::MarketplaceConfigUpdate;
|
||||
use codex_config::record_user_marketplace;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_config_and_installed_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(installed_root.join(".agents/plugins")).unwrap();
|
||||
fs::write(
|
||||
installed_root.join(".agents/plugins/marketplace.json"),
|
||||
"{}",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outcome.marketplace_name, "debug");
|
||||
assert_eq!(
|
||||
outcome.removed_installed_root,
|
||||
Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap())
|
||||
);
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("[marketplaces.debug]"));
|
||||
assert!(!installed_root.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_rejects_unknown_marketplace() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"marketplace `debug` is not configured or installed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_preserves_shadowed_system_marketplace() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let config = "[marketplaces.debug]\nsource_type = \"git\"\nsource = \"https://github.com/owner/repo.git\"\n";
|
||||
let user_file =
|
||||
AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home.path());
|
||||
let system_file =
|
||||
AbsolutePathBuf::resolve_path_against_base("system.toml", codex_home.path());
|
||||
fs::write(&user_file, config).unwrap();
|
||||
fs::write(&system_file, config).unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
let marker = installed_root.join("marker.txt");
|
||||
fs::write(&marker, "installed").unwrap();
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::System {
|
||||
file: system_file.clone(),
|
||||
},
|
||||
toml::from_str(config).unwrap(),
|
||||
),
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: user_file.clone(),
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(config).unwrap(),
|
||||
),
|
||||
],
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!(
|
||||
"marketplace `debug` is configured in system ({}); remove it from that configuration source instead",
|
||||
system_file.display()
|
||||
),
|
||||
);
|
||||
assert_eq!(fs::read_to_string(user_file).unwrap(), config);
|
||||
assert_eq!(fs::read_to_string(system_file).unwrap(), config);
|
||||
assert_eq!(fs::read_to_string(marker).unwrap(), "installed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_rejects_case_mismatched_configured_name() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "Debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"marketplace `Debug` does not match configured marketplace `debug` exactly"
|
||||
);
|
||||
assert!(installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(config.contains("[marketplaces.debug]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_keeps_installed_root_when_config_removal_fails() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
"[marketplaces.debug\n",
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let err = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("failed to remove marketplace 'debug' from user config.toml")
|
||||
);
|
||||
assert!(installed_root.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_file_installed_root() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
record_user_marketplace(
|
||||
codex_home.path(),
|
||||
"debug",
|
||||
&MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(installed_root.parent().unwrap()).unwrap();
|
||||
fs::write(&installed_root, "corrupt install root").unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
outcome,
|
||||
MarketplaceRemoveOutcome {
|
||||
marketplace_name: "debug".to_string(),
|
||||
removed_installed_root: Some(
|
||||
AbsolutePathBuf::try_from(installed_root.clone()).unwrap()
|
||||
),
|
||||
}
|
||||
);
|
||||
assert!(!installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("[marketplaces.debug]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_marketplace_sync_removes_inline_config_entry() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(codex_config::CONFIG_TOML_FILE),
|
||||
r#"
|
||||
marketplaces = { debug = { source_type = "git", source = "https://github.com/owner/repo.git" } }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
|
||||
fs::create_dir_all(&installed_root).unwrap();
|
||||
|
||||
let outcome = remove_marketplace_sync(
|
||||
codex_home.path(),
|
||||
&ConfigLayerStack::default(),
|
||||
MarketplaceRemoveRequest {
|
||||
marketplace_name: "debug".to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(outcome.marketplace_name, "debug");
|
||||
assert_eq!(
|
||||
outcome.removed_installed_root,
|
||||
Some(AbsolutePathBuf::try_from(installed_root.clone()).unwrap())
|
||||
);
|
||||
assert!(!installed_root.exists());
|
||||
let config =
|
||||
fs::read_to_string(codex_home.path().join(codex_config::CONFIG_TOML_FILE)).unwrap();
|
||||
assert!(!config.contains("debug"));
|
||||
}
|
||||
}
|
||||
185
codex-rs/core-plugins/src/marketplace_staging.rs
Normal file
185
codex-rs/core-plugins/src/marketplace_staging.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! Owns temporary marketplace checkouts and reclaims abandoned ones.
|
||||
//! A coordination lock protects publication of each checkout's lifetime lock. Checkouts
|
||||
//! live below their owner directory so Git and activation cannot replace the lock file.
|
||||
//! Cleanup claims a limited batch under coordination, then deletes it outside that lock.
|
||||
//! Legacy directories use age thresholds because older binaries publish no owner lock.
|
||||
|
||||
use codex_utils_path::symlink_metadata_if_exists;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
use tempfile::TempDir;
|
||||
use tracing::warn;
|
||||
|
||||
const LEGACY_ADD_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
// Upgrades have a 30-second timeout per Git command; leave ample room for all phases.
|
||||
const LEGACY_UPGRADE_MAX_AGE: Duration = Duration::from_secs(10 * 60);
|
||||
const LEGACY_ADD_PREFIX: &str = "marketplace-add-";
|
||||
const LEGACY_UPGRADE_PREFIX: &str = "marketplace-upgrade-";
|
||||
const MAX_CLEANUP_DIRECTORIES: usize = 4;
|
||||
const COORDINATION_LOCK: &str = ".staging.lock";
|
||||
const CLEANUP_LOCK: &str = ".staging-cleanup.lock";
|
||||
const OWNER_LOCK: &str = ".lock";
|
||||
|
||||
pub(crate) struct MarketplaceStagingDir {
|
||||
// Close the lock before TempDir removes its directory, including on Windows.
|
||||
_lock: File,
|
||||
_directory: TempDir,
|
||||
checkout: PathBuf,
|
||||
}
|
||||
|
||||
impl MarketplaceStagingDir {
|
||||
pub(crate) fn new(install_root: &Path) -> io::Result<Self> {
|
||||
let staging_root = Self::staging_root(install_root);
|
||||
fs::create_dir_all(&staging_root)?;
|
||||
let coordination = open_lock(&install_root.join(COORDINATION_LOCK))?;
|
||||
coordination.lock()?;
|
||||
let directory = tempfile::Builder::new()
|
||||
.prefix(&Self::directory_prefix())
|
||||
.tempdir_in(&staging_root)?;
|
||||
let lock = File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(directory.path().join(OWNER_LOCK))?;
|
||||
lock.lock()?;
|
||||
let checkout = directory.path().join("checkout");
|
||||
Ok(Self {
|
||||
_lock: lock,
|
||||
_directory: directory,
|
||||
checkout,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.checkout
|
||||
}
|
||||
|
||||
fn staging_root(install_root: &Path) -> PathBuf {
|
||||
install_root.join(".staging")
|
||||
}
|
||||
|
||||
fn directory_prefix() -> String {
|
||||
// Windows and WSL may share a home without sharing a file-lock namespace.
|
||||
format!("marketplace-{}-", std::env::consts::OS)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cleanup_marketplace_staging(install_root: &Path) {
|
||||
if let Err(err) = remove_stale_staging_dirs(install_root, SystemTime::now()) {
|
||||
warn!("failed to clean up marketplace staging directories: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn open_lock(path: &Path) -> io::Result<File> {
|
||||
File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(path)
|
||||
}
|
||||
|
||||
fn try_lock(lock: File) -> io::Result<Option<File>> {
|
||||
match lock.try_lock() {
|
||||
Ok(()) => Ok(Some(lock)),
|
||||
Err(fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(fs::TryLockError::Error(err)) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_stale_staging_dirs(install_root: &Path, now: SystemTime) -> io::Result<()> {
|
||||
let staging_root = MarketplaceStagingDir::staging_root(install_root);
|
||||
let Some(metadata) = symlink_metadata_if_exists(&staging_root)? else {
|
||||
return Ok(());
|
||||
};
|
||||
if !metadata.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
// Skip this pass if another process creates a checkout or removes a batch.
|
||||
let Some(_cleanup) = try_lock(open_lock(&install_root.join(CLEANUP_LOCK))?)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(coordination) = try_lock(open_lock(&install_root.join(COORDINATION_LOCK))?)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let prefix = MarketplaceStagingDir::directory_prefix();
|
||||
let mut abandoned = Vec::new();
|
||||
for entry in fs::read_dir(&staging_root)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
// Continue past an unreadable entry so one failure cannot prevent reclamation.
|
||||
match is_abandoned_staging_dir(&entry, &prefix, now) {
|
||||
Ok(true) => abandoned.push(path),
|
||||
Ok(false) => {}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
warn!(path = %path.display(), "failed to inspect marketplace staging directory: {err}");
|
||||
}
|
||||
}
|
||||
if abandoned.len() == MAX_CLEANUP_DIRECTORIES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Unique checkout names cannot acquire a new owner after publication.
|
||||
// Keep the cleanup lock, but let new checkouts start while deletion runs.
|
||||
drop(coordination);
|
||||
for path in abandoned {
|
||||
if let Err(err) = fs::remove_dir_all(&path)
|
||||
&& err.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
warn!(path = %path.display(), "failed to remove abandoned marketplace staging directory: {err}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_abandoned_staging_dir(
|
||||
entry: &fs::DirEntry,
|
||||
prefix: &str,
|
||||
now: SystemTime,
|
||||
) -> io::Result<bool> {
|
||||
if !entry.file_type()?.is_dir() {
|
||||
return Ok(false);
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let Some(name) = name.to_str() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !name.starts_with(prefix) {
|
||||
// Older binaries did not publish ownership. Leave recent directories
|
||||
// alone so an upgrade can coexist with their in-flight clones.
|
||||
let max_age = if name.starts_with(LEGACY_ADD_PREFIX) {
|
||||
LEGACY_ADD_MAX_AGE
|
||||
} else if name.starts_with(LEGACY_UPGRADE_PREFIX) {
|
||||
LEGACY_UPGRADE_MAX_AGE
|
||||
} else {
|
||||
return Ok(false);
|
||||
};
|
||||
return Ok(now
|
||||
.duration_since(entry.metadata()?.modified()?)
|
||||
.unwrap_or_default()
|
||||
>= max_age);
|
||||
}
|
||||
let owner_lock = entry.path().join(OWNER_LOCK);
|
||||
let Some(metadata) = symlink_metadata_if_exists(&owner_lock)? else {
|
||||
// A crash before lock publication can leave an empty directory.
|
||||
return Ok(true);
|
||||
};
|
||||
if !metadata.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
// An unlocked checkout has no Codex owner to activate it. A surviving Git
|
||||
// process may still write here; deletion can interrupt that abandoned clone.
|
||||
let lock = File::options().read(true).write(true).open(owner_lock)?;
|
||||
// Close the probe's lock before cleanup removes the directory on Windows.
|
||||
Ok(try_lock(lock)?.is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_staging_tests.rs"]
|
||||
mod tests;
|
||||
197
codex-rs/core-plugins/src/marketplace_staging_tests.rs
Normal file
197
codex-rs/core-plugins/src/marketplace_staging_tests.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! Exercises staging ownership across processes and age-based recovery of legacy checkouts.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::BufRead;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[test]
|
||||
fn cleanup_preserves_live_process_and_reclaims_its_abandoned_checkout() -> Result<()> {
|
||||
const CHILD_HOME: &str = "CODEX_MARKETPLACE_STAGING_CHILD_HOME";
|
||||
if let Some(home) = std::env::var_os(CHILD_HOME) {
|
||||
let staging = MarketplaceStagingDir::new(Path::new(&home))?;
|
||||
fs::create_dir_all(staging.path())?;
|
||||
fs::write(staging.path().join("payload"), "in-flight clone")?;
|
||||
println!("staging-ready");
|
||||
std::io::stdout().flush()?;
|
||||
std::io::stdin().read_exact(&mut [0])?;
|
||||
// Model process exit while a background upgrade still owns a checkout.
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut child = codex_utils_process::background_command(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"marketplace_staging::tests::cleanup_preserves_live_process_and_reclaims_its_abandoned_checkout",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_HOME, home.path())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
|
||||
let mut ready = false;
|
||||
for line in stdout.lines() {
|
||||
if line?.contains("staging-ready") {
|
||||
ready = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(ready, "child should publish its checkout before cleanup");
|
||||
let staging_root = home.path().join(".staging");
|
||||
let active = fs::read_dir(&staging_root)?.next().unwrap()?.path();
|
||||
let payload = active.join("checkout/payload");
|
||||
|
||||
// Age must never override the lifetime lock, even across processes.
|
||||
remove_stale_staging_dirs(home.path(), SystemTime::now() + LEGACY_ADD_MAX_AGE)?;
|
||||
assert_eq!(fs::read_to_string(&payload)?, "in-flight clone");
|
||||
let concurrent = MarketplaceStagingDir::new(home.path())?;
|
||||
fs::create_dir_all(concurrent.path())?;
|
||||
fs::write(concurrent.path().join("payload"), "second clone")?;
|
||||
|
||||
child.stdin.take().unwrap().write_all(b"x")?;
|
||||
assert!(child.wait()?.success());
|
||||
assert!(payload.exists(), "process exit must bypass TempDir cleanup");
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert!(!active.exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(concurrent.path().join("payload"))?,
|
||||
"second clone"
|
||||
);
|
||||
drop(concurrent);
|
||||
assert_eq!(fs::read_dir(staging_root)?.count(), 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_reclaims_unpublished_and_aged_legacy_clones() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
let legacy_add = staging_root.join("marketplace-add-old");
|
||||
let legacy_upgrade = staging_root.join("marketplace-upgrade-old");
|
||||
let unrelated = staging_root.join("unrelated");
|
||||
let foreign = staging_root.join("marketplace-other-os-active");
|
||||
let unpublished = staging_root.join(format!(
|
||||
"{}unpublished",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
));
|
||||
for path in [
|
||||
&legacy_add,
|
||||
&legacy_upgrade,
|
||||
&unrelated,
|
||||
&foreign,
|
||||
&unpublished,
|
||||
] {
|
||||
fs::create_dir_all(path)?;
|
||||
}
|
||||
fs::write(legacy_add.join("payload"), "old add")?;
|
||||
fs::write(legacy_upgrade.join("payload"), "old upgrade")?;
|
||||
let unrelated_file =
|
||||
staging_root.join(format!("{}file", MarketplaceStagingDir::directory_prefix()));
|
||||
fs::write(&unrelated_file, "keep")?;
|
||||
|
||||
// Base synthetic ages on the filesystem clock, which can differ from the wall clock.
|
||||
let now = fs::metadata(&legacy_add)?
|
||||
.modified()?
|
||||
.max(fs::metadata(&legacy_upgrade)?.modified()?);
|
||||
for (age, expected_legacy_dirs) in [
|
||||
(Duration::ZERO, [true, true]),
|
||||
(
|
||||
LEGACY_UPGRADE_MAX_AGE + Duration::from_secs(1),
|
||||
[true, false],
|
||||
),
|
||||
(LEGACY_ADD_MAX_AGE + Duration::from_secs(1), [false, false]),
|
||||
] {
|
||||
// A concurrent fork can retain the previous pass's locks until exec.
|
||||
// Wait for both locks and explicitly release them before cleanup.
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
lock.unlock()?;
|
||||
}
|
||||
remove_stale_staging_dirs(home.path(), now + age)?;
|
||||
assert!(!unpublished.exists());
|
||||
assert_eq!(
|
||||
[legacy_add.exists(), legacy_upgrade.exists()],
|
||||
expected_legacy_dirs,
|
||||
"legacy directories remaining after {age:?}"
|
||||
);
|
||||
}
|
||||
assert!(unrelated.exists());
|
||||
assert!(foreign.exists());
|
||||
assert_eq!(fs::read_to_string(unrelated_file)?, "keep");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cleanup_does_not_follow_symlinks() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let outside = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
fs::create_dir_all(&staging_root)?;
|
||||
fs::write(outside.path().join("payload"), "keep")?;
|
||||
let alias = staging_root.join(format!(
|
||||
"{}directory-link",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
));
|
||||
std::os::unix::fs::symlink(outside.path(), &alias)?;
|
||||
let legacy_alias = staging_root.join("marketplace-upgrade-link");
|
||||
std::os::unix::fs::symlink(outside.path(), &legacy_alias)?;
|
||||
let invalid_owner =
|
||||
staging_root.join(format!("{}link", MarketplaceStagingDir::directory_prefix()));
|
||||
fs::create_dir_all(&invalid_owner)?;
|
||||
std::os::unix::fs::symlink(
|
||||
outside.path().join("payload"),
|
||||
invalid_owner.join(OWNER_LOCK),
|
||||
)?;
|
||||
|
||||
remove_stale_staging_dirs(home.path(), SystemTime::now() + LEGACY_ADD_MAX_AGE)?;
|
||||
assert_eq!(fs::read_to_string(outside.path().join("payload"))?, "keep");
|
||||
assert!(alias.is_symlink());
|
||||
assert!(legacy_alias.is_symlink());
|
||||
assert!(invalid_owner.exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_limits_each_pass_and_skips_contended_locks() -> Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let staging_root = home.path().join(".staging");
|
||||
let count = MAX_CLEANUP_DIRECTORIES + 1;
|
||||
for index in 0..count {
|
||||
fs::create_dir_all(staging_root.join(format!(
|
||||
"{}{index}",
|
||||
MarketplaceStagingDir::directory_prefix()
|
||||
)))?;
|
||||
}
|
||||
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert_eq!(fs::read_dir(&staging_root)?.count(), count);
|
||||
if name == CLEANUP_LOCK {
|
||||
// A cleanup worker must not prevent another operation from creating a checkout.
|
||||
drop(MarketplaceStagingDir::new(home.path())?);
|
||||
}
|
||||
}
|
||||
|
||||
for remaining in [1, 0] {
|
||||
// Other tests can fork while cleanup holds a lock. The child retains
|
||||
// that lock until exec, even after this process closes its file.
|
||||
// Wait for both locks, then release them before testing the batch size.
|
||||
for name in [CLEANUP_LOCK, COORDINATION_LOCK] {
|
||||
let lock = open_lock(&home.path().join(name))?;
|
||||
lock.lock()?;
|
||||
lock.unlock()?;
|
||||
}
|
||||
cleanup_marketplace_staging(home.path());
|
||||
assert_eq!(fs::read_dir(&staging_root)?.count(), remaining);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
2285
codex-rs/core-plugins/src/marketplace_tests.rs
Normal file
2285
codex-rs/core-plugins/src/marketplace_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
397
codex-rs/core-plugins/src/marketplace_upgrade.rs
Normal file
397
codex-rs/core-plugins/src/marketplace_upgrade.rs
Normal file
@@ -0,0 +1,397 @@
|
||||
mod activation;
|
||||
mod git;
|
||||
|
||||
use self::activation::activate_marketplace_root;
|
||||
use self::activation::installed_marketplace_metadata_matches;
|
||||
use self::activation::read_installed_marketplace_snapshot;
|
||||
use self::activation::write_installed_marketplace_metadata;
|
||||
use self::git::clone_git_source;
|
||||
use self::git::git_remote_revision;
|
||||
use crate::PluginGitMode;
|
||||
use crate::installed_marketplaces::marketplace_install_root;
|
||||
use crate::marketplace::has_symlinked_marketplace_manifest;
|
||||
use crate::marketplace::validate_marketplace_root;
|
||||
use crate::marketplace_add::MarketplaceSource;
|
||||
use crate::marketplace_policy::MarketplacePolicy;
|
||||
use crate::marketplace_policy::validate_marketplace_name_for_add;
|
||||
use crate::marketplace_staging::MarketplaceStagingDir;
|
||||
use crate::marketplace_staging::cleanup_marketplace_staging;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::types::MarketplaceConfig;
|
||||
use codex_config::types::MarketplaceSourceType;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Reloads configuration with the initiating operation's settings. Called only on a blocking worker.
|
||||
pub type ConfigLayerReload = Arc<dyn Fn() -> std::io::Result<ConfigLayerStack> + Send + Sync>;
|
||||
|
||||
const MARKETPLACE_UPGRADE_GIT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConfiguredMarketplaceUpgradeError {
|
||||
pub marketplace_name: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ConfiguredMarketplaceUpgradeOutcome {
|
||||
pub selected_marketplaces: Vec<String>,
|
||||
pub upgraded_roots: Vec<AbsolutePathBuf>,
|
||||
pub errors: Vec<ConfiguredMarketplaceUpgradeError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ConfiguredGitMarketplace {
|
||||
name: String,
|
||||
source: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct CheckoutInputs {
|
||||
configured_name: Box<str>,
|
||||
source_sha256: Box<str>,
|
||||
ref_name: Option<Box<str>>,
|
||||
sparse_paths: Box<[Box<str>]>,
|
||||
revision: Box<str>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct MarketplaceNameMismatch {
|
||||
inputs: CheckoutInputs,
|
||||
found_name: Box<str>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ConfiguredGitMarketplaceLoadOutcome {
|
||||
marketplaces: Vec<ConfiguredGitMarketplace>,
|
||||
errors: Vec<ConfiguredMarketplaceUpgradeError>,
|
||||
}
|
||||
|
||||
impl ConfiguredMarketplaceUpgradeOutcome {
|
||||
pub fn all_succeeded(&self) -> bool {
|
||||
self.errors.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configured_git_marketplace_names(config_layer_stack: &ConfigLayerStack) -> Vec<String> {
|
||||
let mut names = load_configured_git_marketplaces(config_layer_stack)
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.map(|marketplace| marketplace.name)
|
||||
.collect::<Vec<_>>();
|
||||
names.sort_unstable();
|
||||
names
|
||||
}
|
||||
|
||||
pub fn upgrade_configured_git_marketplaces(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
marketplace_name: Option<&str>,
|
||||
reload_config: &ConfigLayerReload,
|
||||
) -> ConfiguredMarketplaceUpgradeOutcome {
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home,
|
||||
config_layer_stack,
|
||||
marketplace_name,
|
||||
PluginGitMode::Manual,
|
||||
reload_config,
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies the initiating operation's Git trust policy to every selected marketplace.
|
||||
pub(crate) fn upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home: &Path,
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
marketplace_name: Option<&str>,
|
||||
mode: PluginGitMode,
|
||||
reload_config: &ConfigLayerReload,
|
||||
) -> ConfiguredMarketplaceUpgradeOutcome {
|
||||
let install_root = marketplace_install_root(codex_home);
|
||||
cleanup_marketplace_staging(&install_root);
|
||||
let loaded = load_configured_git_marketplaces(config_layer_stack);
|
||||
let marketplaces = loaded
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.filter(|marketplace| marketplace_name.is_none_or(|name| marketplace.name.as_str() == name))
|
||||
.collect::<Vec<_>>();
|
||||
let mut errors = loaded
|
||||
.errors
|
||||
.into_iter()
|
||||
.filter(|error| marketplace_name.is_none_or(|name| error.marketplace_name.as_str() == name))
|
||||
.collect::<Vec<_>>();
|
||||
if marketplaces.is_empty() && errors.is_empty() {
|
||||
return ConfiguredMarketplaceUpgradeOutcome::default();
|
||||
}
|
||||
|
||||
let mut selected_marketplaces = marketplaces
|
||||
.iter()
|
||||
.map(|marketplace| marketplace.name.clone())
|
||||
.chain(errors.iter().map(|error| error.marketplace_name.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
selected_marketplaces.sort_unstable();
|
||||
selected_marketplaces.dedup();
|
||||
let mut upgraded_roots = Vec::new();
|
||||
let policy = MarketplacePolicy::from_requirements(config_layer_stack.requirements());
|
||||
for marketplace in marketplaces {
|
||||
let normalized_source =
|
||||
match validate_marketplace_name_for_add(/*expected_name*/ None, &marketplace.name)
|
||||
.and_then(|()| {
|
||||
policy.validate_git_source(&marketplace.source, marketplace.ref_name.clone())
|
||||
}) {
|
||||
Ok(normalized_source) => normalized_source,
|
||||
Err(message) => {
|
||||
errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: marketplace.name,
|
||||
message,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match upgrade_configured_git_marketplace(
|
||||
codex_home,
|
||||
&install_root,
|
||||
&marketplace,
|
||||
reload_config,
|
||||
normalized_source.as_ref(),
|
||||
mode,
|
||||
) {
|
||||
Ok(Some(upgraded_root)) => upgraded_roots.push(upgraded_root),
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: marketplace.name,
|
||||
message: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces,
|
||||
upgraded_roots,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_configured_git_marketplaces(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
) -> ConfiguredGitMarketplaceLoadOutcome {
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return ConfiguredGitMarketplaceLoadOutcome::default();
|
||||
};
|
||||
|
||||
let mut outcome = ConfiguredGitMarketplaceLoadOutcome::default();
|
||||
for (name, marketplace) in marketplaces {
|
||||
match parse_configured_git_marketplace(name, marketplace) {
|
||||
Ok(Some(marketplace)) => outcome.marketplaces.push(marketplace),
|
||||
Ok(None) => {}
|
||||
Err(message) => outcome.errors.push(ConfiguredMarketplaceUpgradeError {
|
||||
marketplace_name: name.clone(),
|
||||
message,
|
||||
}),
|
||||
}
|
||||
}
|
||||
outcome
|
||||
.marketplaces
|
||||
.sort_unstable_by(|left, right| left.name.cmp(&right.name));
|
||||
outcome
|
||||
.errors
|
||||
.sort_unstable_by(|left, right| left.marketplace_name.cmp(&right.marketplace_name));
|
||||
outcome
|
||||
}
|
||||
|
||||
fn parse_configured_git_marketplace(
|
||||
name: &str,
|
||||
marketplace: &toml::Value,
|
||||
) -> Result<Option<ConfiguredGitMarketplace>, String> {
|
||||
if marketplace.get("source_type").and_then(toml::Value::as_str) != Some("git") {
|
||||
return Ok(None);
|
||||
}
|
||||
let marketplace = marketplace
|
||||
.clone()
|
||||
.try_into::<MarketplaceConfig>()
|
||||
.map_err(|err| format!("invalid configured Git marketplace: {err}"))?;
|
||||
let MarketplaceConfig {
|
||||
last_updated: _,
|
||||
last_revision: _,
|
||||
source_type,
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
} = marketplace;
|
||||
if source_type != Some(MarketplaceSourceType::Git) {
|
||||
return Ok(None);
|
||||
}
|
||||
let source =
|
||||
source.ok_or_else(|| "configured Git marketplace is missing source".to_string())?;
|
||||
Ok(Some(ConfiguredGitMarketplace {
|
||||
name: name.to_string(),
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths: sparse_paths.unwrap_or_default(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn upgrade_configured_git_marketplace(
|
||||
codex_home: &Path,
|
||||
install_root: &Path,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
reload_config: &ConfigLayerReload,
|
||||
normalized_source: Option<&MarketplaceSource>,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<Option<AbsolutePathBuf>, String> {
|
||||
validate_plugin_segment(&marketplace.name, "marketplace name")?;
|
||||
let (source, ref_name) = match normalized_source {
|
||||
Some(MarketplaceSource::Git { url, ref_name }) => (url.as_str(), ref_name.as_deref()),
|
||||
Some(MarketplaceSource::Local { .. }) => {
|
||||
return Err("validated Git marketplace source resolved to a local path".to_string());
|
||||
}
|
||||
None => (marketplace.source.as_str(), marketplace.ref_name.as_deref()),
|
||||
};
|
||||
let remote_revision = git_remote_revision(
|
||||
codex_home,
|
||||
source,
|
||||
ref_name,
|
||||
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
|
||||
mode,
|
||||
)?;
|
||||
let destination = install_root.join(&marketplace.name);
|
||||
let previous_snapshot = read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
if validate_marketplace_root(&destination)
|
||||
.is_ok_and(|marketplace_name| marketplace_name == marketplace.name)
|
||||
&& installed_marketplace_metadata_matches(&previous_snapshot, marketplace, &remote_revision)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let name_mismatch = |found: &str| {
|
||||
format!(
|
||||
"upgraded marketplace name `{found}` does not match configured marketplace `{}`",
|
||||
marketplace.name
|
||||
)
|
||||
};
|
||||
// An unchanged checkout will declare the same name. Keep one rejection per
|
||||
// marketplace outside its untrusted checkout, without persisting the source URL.
|
||||
let rejection = match mode {
|
||||
PluginGitMode::Manual => None,
|
||||
PluginGitMode::Automatic => {
|
||||
let path = codex_home
|
||||
.join("cache/marketplaces")
|
||||
.join(format!("{}.json", marketplace.name));
|
||||
let inputs = CheckoutInputs {
|
||||
configured_name: Box::from(marketplace.name.as_str()),
|
||||
source_sha256: format!("{:x}", Sha256::digest(source)).into_boxed_str(),
|
||||
ref_name: ref_name.map(Box::from),
|
||||
sparse_paths: marketplace
|
||||
.sparse_paths
|
||||
.iter()
|
||||
.map(|path| Box::from(path.as_str()))
|
||||
.collect(),
|
||||
revision: remote_revision.into_boxed_str(),
|
||||
};
|
||||
Some((path, inputs))
|
||||
}
|
||||
};
|
||||
if let Some((path, inputs)) = &rejection
|
||||
&& let Ok(contents) = std::fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<MarketplaceNameMismatch>(&contents)
|
||||
&& cached.inputs == *inputs
|
||||
{
|
||||
return Err(name_mismatch(&cached.found_name));
|
||||
}
|
||||
|
||||
let staged_dir = MarketplaceStagingDir::new(install_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to create temporary marketplace upgrade directory in {}: {err}",
|
||||
install_root.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
let activated_revision = clone_git_source(
|
||||
codex_home,
|
||||
source,
|
||||
ref_name,
|
||||
&marketplace.sparse_paths,
|
||||
staged_dir.path(),
|
||||
MARKETPLACE_UPGRADE_GIT_TIMEOUT,
|
||||
mode,
|
||||
)?;
|
||||
let marketplace_name = validate_marketplace_root(staged_dir.path())
|
||||
.map_err(|err| format!("failed to validate upgraded marketplace root: {err}"))?;
|
||||
if marketplace_name != marketplace.name {
|
||||
let error = name_mismatch(&marketplace_name);
|
||||
// HEAD may have moved since ls-remote. Only cache the revision we validated.
|
||||
if let Some((path, inputs)) = rejection
|
||||
&& activated_revision.as_str() == inputs.revision.as_ref()
|
||||
&& !has_symlinked_marketplace_manifest(staged_dir.path())
|
||||
&& let Ok(contents) = serde_json::to_string_pretty(&MarketplaceNameMismatch {
|
||||
inputs,
|
||||
found_name: marketplace_name.into_boxed_str(),
|
||||
})
|
||||
{
|
||||
let _ = codex_utils_path::write_atomically(&path, &contents);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
write_installed_marketplace_metadata(staged_dir.path(), marketplace, &activated_revision)?;
|
||||
activate_marketplace_root(&destination, staged_dir.path(), &previous_snapshot, || {
|
||||
ensure_configured_git_marketplace_unchanged(reload_config, marketplace)
|
||||
})?;
|
||||
|
||||
AbsolutePathBuf::try_from(destination)
|
||||
.map(Some)
|
||||
.map_err(|err| format!("upgraded marketplace path is not absolute: {err}"))
|
||||
}
|
||||
fn ensure_configured_git_marketplace_unchanged(
|
||||
reload_config: &ConfigLayerReload,
|
||||
expected: &ConfiguredGitMarketplace,
|
||||
) -> Result<(), String> {
|
||||
let current = read_configured_git_marketplace(reload_config, &expected.name)?;
|
||||
match current {
|
||||
Some(current) if current == *expected => Ok(()),
|
||||
Some(_) => Err(format!(
|
||||
"configured marketplace `{}` changed while auto-upgrade was in flight",
|
||||
expected.name
|
||||
)),
|
||||
None => Err(format!(
|
||||
"configured marketplace `{}` was removed or is no longer a Git marketplace",
|
||||
expected.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_configured_git_marketplace(
|
||||
reload_config: &ConfigLayerReload,
|
||||
marketplace_name: &str,
|
||||
) -> Result<Option<ConfiguredGitMarketplace>, String> {
|
||||
let effective_config = reload_config()
|
||||
.map_err(|err| {
|
||||
format!("failed to reload config while checking marketplace upgrade: {err}")
|
||||
})?
|
||||
.effective_config();
|
||||
let Some(marketplace) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.and_then(|marketplaces| marketplaces.get(marketplace_name))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
parse_configured_git_marketplace(marketplace_name, marketplace)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "marketplace_upgrade_tests.rs"]
|
||||
mod tests;
|
||||
222
codex-rs/core-plugins/src/marketplace_upgrade/activation.rs
Normal file
222
codex-rs/core-plugins/src/marketplace_upgrade/activation.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
use super::ConfiguredGitMarketplace;
|
||||
use codex_config::types::MarketplaceSourceType;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tracing::warn;
|
||||
|
||||
const MARKETPLACE_INSTALL_METADATA_FILE: &str = ".codex-marketplace-install.json";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
struct InstalledMarketplaceMetadata {
|
||||
source_type: MarketplaceSourceType,
|
||||
source: String,
|
||||
ref_name: Option<String>,
|
||||
sparse_paths: Vec<String>,
|
||||
revision: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct InstalledMarketplaceSnapshot {
|
||||
marketplace_name: String,
|
||||
exists: bool,
|
||||
metadata: Option<InstalledMarketplaceMetadata>,
|
||||
}
|
||||
|
||||
pub(super) fn read_installed_marketplace_snapshot(
|
||||
root: &Path,
|
||||
marketplace_name: &str,
|
||||
) -> InstalledMarketplaceSnapshot {
|
||||
if !root.exists() {
|
||||
return InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: false,
|
||||
metadata: None,
|
||||
};
|
||||
}
|
||||
let metadata = match std::fs::read_to_string(installed_marketplace_metadata_path(root)) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(_) => {
|
||||
return InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: true,
|
||||
metadata: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
let metadata = match serde_json::from_str::<InstalledMarketplaceMetadata>(&metadata) {
|
||||
Ok(metadata) => Some(metadata),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
marketplace = marketplace_name,
|
||||
error = %err,
|
||||
"failed to parse activated marketplace metadata"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
InstalledMarketplaceSnapshot {
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
exists: true,
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn installed_marketplace_metadata_matches(
|
||||
snapshot: &InstalledMarketplaceSnapshot,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> bool {
|
||||
snapshot.metadata.as_ref() == Some(&installed_marketplace_metadata(marketplace, revision))
|
||||
}
|
||||
|
||||
pub(super) fn write_installed_marketplace_metadata(
|
||||
root: &Path,
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> Result<(), String> {
|
||||
let metadata = installed_marketplace_metadata(marketplace, revision);
|
||||
let contents = serde_json::to_string_pretty(&metadata)
|
||||
.map_err(|err| format!("failed to serialize activated marketplace metadata: {err}"))?;
|
||||
std::fs::write(installed_marketplace_metadata_path(root), contents)
|
||||
.map_err(|err| format!("failed to write activated marketplace metadata: {err}"))
|
||||
}
|
||||
|
||||
pub(super) fn activate_marketplace_root(
|
||||
destination: &Path,
|
||||
staged_root: &Path,
|
||||
previous_snapshot: &InstalledMarketplaceSnapshot,
|
||||
after_activate: impl FnOnce() -> Result<(), String>,
|
||||
) -> Result<(), String> {
|
||||
let Some(parent) = destination.parent() else {
|
||||
return Err(format!(
|
||||
"failed to determine marketplace install parent for {}",
|
||||
destination.display()
|
||||
));
|
||||
};
|
||||
std::fs::create_dir_all(parent).map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace install parent {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
if destination.exists() {
|
||||
let backup_dir = tempfile::Builder::new()
|
||||
.prefix("marketplace-backup-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace backup directory in {}: {err}",
|
||||
parent.display()
|
||||
)
|
||||
})?;
|
||||
let backup_root = backup_dir.path().join("root");
|
||||
std::fs::rename(destination, &backup_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to move previous marketplace root out of the way at {}: {err}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
if let Err(err) = std::fs::rename(staged_root, destination) {
|
||||
let rollback_result = std::fs::rename(&backup_root, destination);
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}",
|
||||
destination.display()
|
||||
)),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join("root");
|
||||
Err(format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}; failed to restore previous marketplace root (left at {}): {rollback_err}",
|
||||
destination.display(),
|
||||
backup_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let activation_result = if read_installed_marketplace_snapshot(
|
||||
&backup_root,
|
||||
&previous_snapshot.marketplace_name,
|
||||
) != *previous_snapshot
|
||||
{
|
||||
Err(installed_marketplace_snapshot_changed_error(
|
||||
previous_snapshot,
|
||||
))
|
||||
} else {
|
||||
after_activate()
|
||||
};
|
||||
if let Err(err) = activation_result {
|
||||
let remove_result = std::fs::remove_dir_all(destination);
|
||||
let rollback_result =
|
||||
remove_result.and_then(|()| std::fs::rename(&backup_root, destination));
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(err),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join("root");
|
||||
Err(format!(
|
||||
"{err}; failed to restore previous marketplace root at {} (left at {}): {rollback_err}",
|
||||
destination.display(),
|
||||
backup_path.display()
|
||||
))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
std::fs::rename(staged_root, destination).map_err(|err| {
|
||||
format!(
|
||||
"failed to activate upgraded marketplace at {}: {err}",
|
||||
destination.display()
|
||||
)
|
||||
})?;
|
||||
let activation_result = if previous_snapshot.exists {
|
||||
Err(installed_marketplace_snapshot_changed_error(
|
||||
previous_snapshot,
|
||||
))
|
||||
} else {
|
||||
after_activate()
|
||||
};
|
||||
if let Err(err) = activation_result {
|
||||
let remove_result = std::fs::remove_dir_all(destination);
|
||||
return match remove_result {
|
||||
Ok(()) => Err(err),
|
||||
Err(remove_err) => Err(format!(
|
||||
"{err}; failed to remove newly activated marketplace root at {}: {remove_err}",
|
||||
destination.display()
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn installed_marketplace_snapshot_changed_error(snapshot: &InstalledMarketplaceSnapshot) -> String {
|
||||
format!(
|
||||
"installed marketplace `{}` changed while auto-upgrade was in flight",
|
||||
snapshot.marketplace_name
|
||||
)
|
||||
}
|
||||
|
||||
fn installed_marketplace_metadata(
|
||||
marketplace: &ConfiguredGitMarketplace,
|
||||
revision: &str,
|
||||
) -> InstalledMarketplaceMetadata {
|
||||
InstalledMarketplaceMetadata {
|
||||
source_type: MarketplaceSourceType::Git,
|
||||
source: marketplace.source.clone(),
|
||||
ref_name: marketplace.ref_name.clone(),
|
||||
sparse_paths: marketplace.sparse_paths.clone(),
|
||||
revision: revision.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn installed_marketplace_metadata_path(root: &Path) -> PathBuf {
|
||||
root.join(MARKETPLACE_INSTALL_METADATA_FILE)
|
||||
}
|
||||
309
codex-rs/core-plugins/src/marketplace_upgrade/git.rs
Normal file
309
codex-rs/core-plugins/src/marketplace_upgrade/git.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
use crate::PluginGitMode;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) fn git_remote_revision(
|
||||
codex_home: &Path,
|
||||
source: &str,
|
||||
ref_name: Option<&str>,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
if let Some(ref_name) = ref_name
|
||||
&& is_full_git_sha(ref_name)
|
||||
{
|
||||
return Ok(ref_name.to_string());
|
||||
}
|
||||
|
||||
let ref_name = ref_name.unwrap_or("HEAD");
|
||||
let mut command = git_command(mode);
|
||||
let _trusted_repository = matches!(mode, PluginGitMode::Automatic)
|
||||
.then(|| crate::configure_trusted_git_repository(&mut command, codex_home))
|
||||
.transpose()?;
|
||||
let output = run_git_command_with_timeout(
|
||||
command.arg("ls-remote").arg(source).arg(ref_name),
|
||||
"git ls-remote marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git ls-remote marketplace source")?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let Some(first_line) = stdout.lines().next() else {
|
||||
return Err("git ls-remote returned empty output for marketplace source".to_string());
|
||||
};
|
||||
let Some((revision, _)) = first_line.split_once('\t') else {
|
||||
return Err(format!(
|
||||
"unexpected git ls-remote output for marketplace source: {first_line}"
|
||||
));
|
||||
};
|
||||
let revision = revision.trim();
|
||||
if revision.is_empty() {
|
||||
return Err("git ls-remote returned empty revision for marketplace source".to_string());
|
||||
}
|
||||
Ok(revision.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn clone_git_source(
|
||||
codex_home: &Path,
|
||||
source: &str,
|
||||
ref_name: Option<&str>,
|
||||
sparse_paths: &[String],
|
||||
destination: &Path,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
let git_destination = git_path_arg(destination);
|
||||
let mut command = git_command(mode);
|
||||
let _trusted_repository = matches!(mode, PluginGitMode::Automatic)
|
||||
.then(|| crate::configure_trusted_git_repository(&mut command, codex_home))
|
||||
.transpose()?;
|
||||
if sparse_paths.is_empty() {
|
||||
let output = run_git_command_with_timeout(
|
||||
command.arg("clone").arg(source).arg(&git_destination),
|
||||
"git clone marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git clone marketplace source")?;
|
||||
if let Some(ref_name) = ref_name {
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("checkout")
|
||||
.arg(ref_name),
|
||||
"git checkout marketplace ref",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git checkout marketplace ref")?;
|
||||
}
|
||||
return git_worktree_revision(&git_destination, timeout, mode);
|
||||
}
|
||||
|
||||
let output = run_git_command_with_timeout(
|
||||
command
|
||||
.arg("clone")
|
||||
.arg("--filter=blob:none")
|
||||
.arg("--no-checkout")
|
||||
.arg(source)
|
||||
.arg(&git_destination),
|
||||
"git clone marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git clone marketplace source")?;
|
||||
|
||||
let mut sparse_checkout = git_command(mode);
|
||||
sparse_checkout
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("sparse-checkout")
|
||||
.arg("set")
|
||||
.args(sparse_paths);
|
||||
let output = run_git_command_with_timeout(
|
||||
&mut sparse_checkout,
|
||||
"git sparse-checkout marketplace source",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git sparse-checkout marketplace source")?;
|
||||
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(&git_destination)
|
||||
.arg("checkout")
|
||||
.arg(ref_name.unwrap_or("HEAD")),
|
||||
"git checkout marketplace ref",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git checkout marketplace ref")?;
|
||||
git_worktree_revision(&git_destination, timeout, mode)
|
||||
}
|
||||
|
||||
fn git_worktree_revision(
|
||||
destination: &Path,
|
||||
timeout: Duration,
|
||||
mode: PluginGitMode,
|
||||
) -> Result<String, String> {
|
||||
let output = run_git_command_with_timeout(
|
||||
git_command(mode)
|
||||
.arg("-C")
|
||||
.arg(destination)
|
||||
.arg("rev-parse")
|
||||
.arg("HEAD"),
|
||||
"git rev-parse marketplace revision",
|
||||
timeout,
|
||||
)?;
|
||||
ensure_git_success(&output, "git rev-parse marketplace revision")?;
|
||||
|
||||
let revision = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if revision.is_empty() {
|
||||
Err("git rev-parse returned empty revision for marketplace source".to_string())
|
||||
} else {
|
||||
Ok(revision)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_full_git_sha(value: &str) -> bool {
|
||||
value.len() == 40 && value.chars().all(|ch| ch.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn git_command(mode: PluginGitMode) -> Command {
|
||||
let mut command = mode.command(Path::new("git"));
|
||||
command
|
||||
.env("GIT_OPTIONAL_LOCKS", "0")
|
||||
.env("GIT_TERMINAL_PROMPT", "0");
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn git_path_arg(path: &Path) -> PathBuf {
|
||||
strip_windows_verbatim_path_prefix(&path.to_string_lossy())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn git_path_arg(path: &Path) -> PathBuf {
|
||||
path.to_path_buf()
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn strip_windows_verbatim_path_prefix(path: &str) -> Option<String> {
|
||||
let stripped = path.strip_prefix(r"\\?\")?;
|
||||
let stripped = stripped
|
||||
.strip_prefix(r"UNC\")
|
||||
.map(|unc_path| format!(r"\\{unc_path}"))
|
||||
.unwrap_or_else(|| stripped.to_string());
|
||||
Some(stripped)
|
||||
}
|
||||
|
||||
fn run_git_command_with_timeout(
|
||||
command: &mut Command,
|
||||
context: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<Output, String> {
|
||||
let mut child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|err| format!("failed to run {context}: {err}"))?;
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => {
|
||||
return child
|
||||
.wait_with_output()
|
||||
.map_err(|err| format!("failed to wait for {context}: {err}"));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(err) => return Err(format!("failed to poll {context}: {err}")),
|
||||
}
|
||||
|
||||
if start.elapsed() >= timeout {
|
||||
let _ = child.kill();
|
||||
let output = child
|
||||
.wait_with_output()
|
||||
.map_err(|err| format!("failed to wait for {context} after timeout: {err}"))?;
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return if stderr.is_empty() {
|
||||
Err(format!("{context} timed out after {}s", timeout.as_secs()))
|
||||
} else {
|
||||
Err(format!(
|
||||
"{context} timed out after {}s: {stderr}",
|
||||
timeout.as_secs()
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_git_success(output: &Output, context: &str) -> Result<(), String> {
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if stderr.is_empty() {
|
||||
Err(format!("{context} failed with status {}", output.status))
|
||||
} else {
|
||||
Err(format!(
|
||||
"{context} failed with status {}: {stderr}",
|
||||
output.status
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::git_command;
|
||||
use super::is_full_git_sha;
|
||||
use super::strip_windows_verbatim_path_prefix;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::ffi::OsStr;
|
||||
|
||||
#[test]
|
||||
fn full_git_sha_ref_is_already_a_remote_revision() {
|
||||
assert!(is_full_git_sha("0123456789abcdef0123456789abcdef01234567"));
|
||||
assert!(!is_full_git_sha("main"));
|
||||
assert!(!is_full_git_sha("0123456"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_command_uses_path_lookup_with_stable_noninteractive_env() {
|
||||
let command = git_command(crate::PluginGitMode::Automatic);
|
||||
|
||||
assert_eq!(command.get_program(), OsStr::new("git"));
|
||||
assert_eq!(
|
||||
command.get_args().collect::<Vec<_>>(),
|
||||
[
|
||||
OsStr::new("-c"),
|
||||
OsStr::new(codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
command_env(&command, "GIT_OPTIONAL_LOCKS"),
|
||||
Some(Some(OsStr::new("0")))
|
||||
);
|
||||
assert_eq!(
|
||||
command_env(&command, "GIT_TERMINAL_PROMPT"),
|
||||
Some(Some(OsStr::new("0")))
|
||||
);
|
||||
assert_eq!(command_env(&command, "PATH"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_windows_verbatim_disk_prefix_for_git() {
|
||||
assert_eq!(
|
||||
strip_windows_verbatim_path_prefix(r"\\?\C:\Users\alice\marketplace"),
|
||||
Some(r"C:\Users\alice\marketplace".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_windows_verbatim_unc_prefix_for_git() {
|
||||
assert_eq!(
|
||||
strip_windows_verbatim_path_prefix(r"\\?\UNC\server\share\marketplace"),
|
||||
Some(r"\\server\share\marketplace".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_non_verbatim_path_without_rewrite() {
|
||||
assert_eq!(strip_windows_verbatim_path_prefix(r"C:\Users\alice"), None);
|
||||
}
|
||||
|
||||
fn command_env<'a>(
|
||||
command: &'a std::process::Command,
|
||||
name: &str,
|
||||
) -> Option<Option<&'a OsStr>> {
|
||||
command
|
||||
.get_envs()
|
||||
.find(|(key, _)| key == &OsStr::new(name))
|
||||
.map(|(_, value)| value)
|
||||
}
|
||||
}
|
||||
633
codex-rs/core-plugins/src/marketplace_upgrade_tests.rs
Normal file
633
codex-rs/core-plugins/src/marketplace_upgrade_tests.rs
Normal file
@@ -0,0 +1,633 @@
|
||||
use super::*;
|
||||
use crate::PluginGitMode;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn readback_ignores_unrelated_malformed_marketplace() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
std::fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[marketplaces.bad]
|
||||
source_type = "git"
|
||||
source = 17
|
||||
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = "https://github.com/example/good.git"
|
||||
ref = "main"
|
||||
sparse_paths = ["plugins"]
|
||||
last_revision = "abc123"
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
|
||||
assert_eq!(
|
||||
read_configured_git_marketplace(&config_reloader(codex_home.path()), "good")
|
||||
.expect("read configured marketplace"),
|
||||
Some(ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: "https://github.com/example/good.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
sparse_paths: vec!["plugins".to_string()],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_upgrade_failure_does_not_block_another_marketplace() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let remote_repo = TempDir::new().expect("create remote repository");
|
||||
init_marketplace_repo(remote_repo.path(), "good");
|
||||
let good_url = url::Url::from_directory_path(remote_repo.path())
|
||||
.expect("remote repository URL")
|
||||
.to_string();
|
||||
let missing_url = url::Url::from_directory_path(codex_home.path().join("missing-repository"))
|
||||
.expect("missing repository URL")
|
||||
.to_string();
|
||||
let config = format!(
|
||||
r#"
|
||||
[marketplaces.bad]
|
||||
source_type = "git"
|
||||
source = {missing_url:?}
|
||||
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = {good_url:?}
|
||||
"#
|
||||
);
|
||||
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), &config).expect("write config");
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let stack = reload_config().expect("load config");
|
||||
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
/*marketplace_name*/ None,
|
||||
&reload_config,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
outcome.selected_marketplaces,
|
||||
vec!["bad".to_string(), "good".to_string()]
|
||||
);
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert_eq!(outcome.errors[0].marketplace_name, "bad");
|
||||
assert_eq!(
|
||||
outcome.upgraded_roots,
|
||||
vec![
|
||||
AbsolutePathBuf::try_from(marketplace_install_root(codex_home.path()).join("good"))
|
||||
.expect("installed marketplace root")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_marketplace_git_ignores_inherited_repository_configuration() {
|
||||
const CHILD_HOME: &str = "CODEX_MARKETPLACE_GIT_ISOLATION_CHILD_HOME";
|
||||
const CHILD_SOURCE: &str = "CODEX_MARKETPLACE_GIT_ISOLATION_CHILD_SOURCE";
|
||||
|
||||
if let Some(codex_home) = std::env::var_os(CHILD_HOME) {
|
||||
let codex_home = PathBuf::from(codex_home);
|
||||
let source = std::env::var(CHILD_SOURCE).expect("read configured marketplace source");
|
||||
let config =
|
||||
format!("[marketplaces.trusted]\nsource_type = \"git\"\nsource = {source:?}\n");
|
||||
std::fs::write(codex_home.join(CONFIG_TOML_FILE), &config).expect("write config");
|
||||
let reload_config = config_reloader(&codex_home);
|
||||
let stack = reload_config().expect("load config");
|
||||
let outcome = upgrade_configured_git_marketplaces_with_mode(
|
||||
&codex_home,
|
||||
&stack,
|
||||
/*marketplace_name*/ None,
|
||||
PluginGitMode::Automatic,
|
||||
&reload_config,
|
||||
);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces: vec!["trusted".to_string()],
|
||||
upgraded_roots: vec![
|
||||
AbsolutePathBuf::try_from(
|
||||
marketplace_install_root(&codex_home).join("trusted")
|
||||
)
|
||||
.expect("installed marketplace root"),
|
||||
],
|
||||
errors: Vec::new(),
|
||||
}
|
||||
);
|
||||
for (url, mode) in [
|
||||
("global:marketplace", PluginGitMode::Automatic),
|
||||
("manual:marketplace", PluginGitMode::Manual),
|
||||
] {
|
||||
let materialized = crate::loader::materialize_marketplace_plugin_source_with_mode(
|
||||
&codex_home,
|
||||
&crate::marketplace::MarketplacePluginSource::Git {
|
||||
url: url.to_string(),
|
||||
path: None,
|
||||
ref_name: matches!(mode, PluginGitMode::Manual)
|
||||
.then(|| "manual-filter".to_string()),
|
||||
sha: None,
|
||||
},
|
||||
mode,
|
||||
)
|
||||
.expect("materialize automatic or manually installed Git plugin");
|
||||
if matches!(mode, PluginGitMode::Manual) {
|
||||
assert!(
|
||||
std::fs::read_to_string(materialized.path.as_path().join("manual.txt"))
|
||||
.expect("read manually filtered checkout")
|
||||
.starts_with("git version ")
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let root = TempDir::new().expect("create temporary directory");
|
||||
let project = root.path().join("project");
|
||||
let codex_home = project.join("codex-home");
|
||||
let remote = root.path().join("remote");
|
||||
std::fs::create_dir_all(&codex_home).expect("create Codex home");
|
||||
std::fs::create_dir_all(&remote).expect("create remote marketplace");
|
||||
init_marketplace_repo(&remote, "trusted");
|
||||
run_git(&remote, &["switch", "--create", "manual-filter"]);
|
||||
std::fs::write(
|
||||
remote.join(".gitattributes"),
|
||||
"manual.txt filter=codex-required\n",
|
||||
)
|
||||
.expect("write required manual checkout filter");
|
||||
std::fs::write(remote.join("manual.txt"), "manual checkout")
|
||||
.expect("write manual checkout fixture");
|
||||
run_git(&remote, &["add", "."]);
|
||||
run_git(
|
||||
&remote,
|
||||
&["commit", "-m", "add required manual checkout filter"],
|
||||
);
|
||||
run_git(&remote, &["switch", "-"]);
|
||||
run_git(&project, &["init", "--quiet"]);
|
||||
|
||||
let source = url::Url::from_directory_path(&remote)
|
||||
.expect("remote marketplace URL")
|
||||
.to_string();
|
||||
let untrusted = url::Url::from_directory_path(root.path().join("missing"))
|
||||
.expect("malicious replacement URL")
|
||||
.to_string();
|
||||
let rewrite_key = format!("url.{untrusted}.insteadOf");
|
||||
run_git(&project, &["config", &rewrite_key, &source]);
|
||||
std::fs::write(
|
||||
root.path().join("global.conf"),
|
||||
"[url \"../remote\"]\n\tinsteadOf = global:marketplace\n[protocol \"file\"]\n\tallow = always\n",
|
||||
)
|
||||
.expect("write global Git configuration");
|
||||
std::fs::write(
|
||||
root.path().join("system.conf"),
|
||||
"[protocol \"file\"]\n\tallow = never\n",
|
||||
)
|
||||
.expect("write system Git configuration");
|
||||
let output = Command::new(std::env::current_exe().expect("locate test binary"))
|
||||
.args([
|
||||
"--exact",
|
||||
"marketplace_upgrade::tests::automatic_marketplace_git_ignores_inherited_repository_configuration",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&project)
|
||||
.env(CHILD_HOME, &codex_home)
|
||||
.env(CHILD_SOURCE, &source)
|
||||
.env("GIT_CONFIG_GLOBAL", "../global.conf")
|
||||
.env("GIT_CONFIG_SYSTEM", "../system.conf")
|
||||
.env("GIT_DIR", project.join(".git"))
|
||||
.env("GIT_CONFIG_COUNT", "3")
|
||||
.env("GIT_CONFIG_KEY_0", &rewrite_key)
|
||||
.env("GIT_CONFIG_VALUE_0", &source)
|
||||
.env("GIT_CONFIG_KEY_1", "url.../remote.insteadOf")
|
||||
.env("GIT_CONFIG_VALUE_1", "manual:marketplace")
|
||||
.env("GIT_CONFIG_KEY_2", "filter.codex-required.smudge")
|
||||
.env("GIT_CONFIG_VALUE_2", "git version")
|
||||
.output()
|
||||
.expect("run marketplace Git isolation regression");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"marketplace Git isolation failed: {}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_uses_validated_source_for_git_operations() {
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let remote_repo = TempDir::new().expect("create remote repository");
|
||||
init_marketplace_repo(remote_repo.path(), "good");
|
||||
let normalized_url = url::Url::from_directory_path(remote_repo.path())
|
||||
.expect("remote repository URL")
|
||||
.to_string();
|
||||
let raw_source = codex_home.path().join("missing-raw-source");
|
||||
let raw_source = raw_source.to_string_lossy().into_owned();
|
||||
let config = format!(
|
||||
r#"
|
||||
[marketplaces.good]
|
||||
source_type = "git"
|
||||
source = {raw_source:?}
|
||||
ref = "missing-ref"
|
||||
"#
|
||||
);
|
||||
std::fs::write(codex_home.path().join(CONFIG_TOML_FILE), config).expect("write config");
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: raw_source,
|
||||
ref_name: Some("missing-ref".to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
let normalized_source = MarketplaceSource::Git {
|
||||
url: normalized_url,
|
||||
ref_name: Some("HEAD".to_string()),
|
||||
};
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
|
||||
let upgraded_root = upgrade_configured_git_marketplace(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&marketplace,
|
||||
&config_reloader(codex_home.path()),
|
||||
Some(&normalized_source),
|
||||
PluginGitMode::Manual,
|
||||
)
|
||||
.expect("upgrade should use the validated source")
|
||||
.expect("marketplace should be upgraded");
|
||||
|
||||
assert_eq!(
|
||||
upgraded_root,
|
||||
AbsolutePathBuf::try_from(install_root.join("good")).expect("installed marketplace root")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_to_date_fast_path_validates_marketplace_name() {
|
||||
const REVISION: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
let destination = install_root.join("good");
|
||||
let manifest_dir = destination.join(".agents/plugins");
|
||||
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
|
||||
std::fs::write(
|
||||
manifest_dir.join("marketplace.json"),
|
||||
r#"{"name":"wrong","plugins":[]}"#,
|
||||
)
|
||||
.expect("write mismatched marketplace manifest");
|
||||
let missing_source = codex_home.path().join("missing-source");
|
||||
let missing_source = missing_source.to_string_lossy().into_owned();
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: missing_source.clone(),
|
||||
ref_name: Some(REVISION.to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
super::activation::write_installed_marketplace_metadata(&destination, &marketplace, REVISION)
|
||||
.expect("write installed marketplace metadata");
|
||||
let normalized_source = MarketplaceSource::Git {
|
||||
url: missing_source,
|
||||
ref_name: Some(REVISION.to_string()),
|
||||
};
|
||||
|
||||
let err = upgrade_configured_git_marketplace(
|
||||
codex_home.path(),
|
||||
&install_root,
|
||||
&marketplace,
|
||||
&config_reloader(codex_home.path()),
|
||||
Some(&normalized_source),
|
||||
PluginGitMode::Manual,
|
||||
)
|
||||
.expect_err("mismatched marketplace name must not use the up-to-date fast path");
|
||||
|
||||
assert!(err.contains("git clone marketplace source failed"));
|
||||
assert_eq!(
|
||||
std::fs::read_dir(install_root.join(".staging"))
|
||||
.expect("read marketplace staging directory")
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_activation_restores_newer_concurrently_installed_marketplace() {
|
||||
const INITIAL_REVISION: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const STALE_REVISION: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const NEWER_REVISION: &str = "cccccccccccccccccccccccccccccccccccccccc";
|
||||
|
||||
let codex_home = TempDir::new().expect("create Codex home");
|
||||
let install_root = marketplace_install_root(codex_home.path());
|
||||
let destination = install_root.join("good");
|
||||
std::fs::create_dir_all(&destination).expect("create installed marketplace root");
|
||||
let marketplace = ConfiguredGitMarketplace {
|
||||
name: "good".to_string(),
|
||||
source: "https://github.com/example/good.git".to_string(),
|
||||
ref_name: Some("main".to_string()),
|
||||
sparse_paths: Vec::new(),
|
||||
};
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
&destination,
|
||||
&marketplace,
|
||||
INITIAL_REVISION,
|
||||
)
|
||||
.expect("write initial installed marketplace metadata");
|
||||
let previous_snapshot =
|
||||
super::activation::read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
|
||||
std::fs::write(destination.join("marker.txt"), "newer snapshot")
|
||||
.expect("write newer installed marketplace snapshot");
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
&destination,
|
||||
&marketplace,
|
||||
NEWER_REVISION,
|
||||
)
|
||||
.expect("write newer installed marketplace metadata");
|
||||
|
||||
let staged_dir =
|
||||
MarketplaceStagingDir::new(&install_root).expect("create stale upgrade staging directory");
|
||||
std::fs::create_dir_all(staged_dir.path()).expect("create stale upgrade checkout");
|
||||
std::fs::write(staged_dir.path().join("marker.txt"), "stale snapshot")
|
||||
.expect("write stale staged marketplace snapshot");
|
||||
super::activation::write_installed_marketplace_metadata(
|
||||
staged_dir.path(),
|
||||
&marketplace,
|
||||
STALE_REVISION,
|
||||
)
|
||||
.expect("write stale staged marketplace metadata");
|
||||
|
||||
let err = super::activation::activate_marketplace_root(
|
||||
&destination,
|
||||
staged_dir.path(),
|
||||
&previous_snapshot,
|
||||
|| Ok(()),
|
||||
)
|
||||
.expect_err("stale upgrade must not replace a newer installed snapshot");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"installed marketplace `good` changed while auto-upgrade was in flight"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(destination.join("marker.txt"))
|
||||
.expect("read restored marketplace snapshot"),
|
||||
"newer snapshot"
|
||||
);
|
||||
let restored_snapshot =
|
||||
super::activation::read_installed_marketplace_snapshot(&destination, &marketplace.name);
|
||||
assert!(super::activation::installed_marketplace_metadata_matches(
|
||||
&restored_snapshot,
|
||||
&marketplace,
|
||||
NEWER_REVISION
|
||||
));
|
||||
drop(staged_dir);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(install_root.join(".staging"))
|
||||
.expect("read marketplace staging directory")
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
fn config_reloader(codex_home: &Path) -> ConfigLayerReload {
|
||||
let codex_home = codex_home.to_path_buf();
|
||||
let options = LoaderOverrides {
|
||||
system_config_path: Some(codex_home.join("system.toml")),
|
||||
managed_config_path: Some(codex_home.join("managed.toml")),
|
||||
system_requirements_path: Some(codex_home.join("requirements.toml")),
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("create config loading runtime");
|
||||
Arc::new(move || {
|
||||
runtime.block_on(load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
&codex_home,
|
||||
Some(AbsolutePathBuf::try_from(codex_home.join("project"))?),
|
||||
&[],
|
||||
options.clone(),
|
||||
&codex_config::NoopThreadConfigLoader,
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn system_marketplace_stack(codex_home: &Path, system: &str, user: &str) -> ConfigLayerStack {
|
||||
let system_file = AbsolutePathBuf::try_from(codex_home.join("system.toml")).unwrap();
|
||||
std::fs::write(&system_file, system).unwrap();
|
||||
if !user.is_empty() {
|
||||
std::fs::write(codex_home.join(CONFIG_TOML_FILE), user).unwrap();
|
||||
}
|
||||
config_reloader(codex_home)().expect("load system and user config")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_marketplace_downloads_and_updates_without_writing_user_config() {
|
||||
for user_config in ["", "[marketplaces.good]\nsparse_paths = []\n"] {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "good");
|
||||
run_git(remote.path(), &["checkout", "-b", "release"]);
|
||||
std::fs::write(remote.path().join("marker"), "release").unwrap();
|
||||
run_git(remote.path(), &["add", "."]);
|
||||
run_git(remote.path(), &["commit", "-m", "release"]);
|
||||
run_git(remote.path(), &["checkout", "-b", "other"]);
|
||||
std::fs::write(remote.path().join("marker"), "wrong branch").unwrap();
|
||||
run_git(remote.path(), &["commit", "-am", "other"]);
|
||||
let source = url::Url::from_directory_path(remote.path())
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let system = format!(
|
||||
"[marketplaces.good]\nsource_type = \"git\"\nsource = {source:?}\nref = \"release\"\n"
|
||||
);
|
||||
let stack = system_marketplace_stack(codex_home.path(), &system, user_config);
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let root =
|
||||
AbsolutePathBuf::try_from(marketplace_install_root(codex_home.path()).join("good"))
|
||||
.unwrap();
|
||||
for marker in ["release", "updated"] {
|
||||
if marker == "updated" {
|
||||
run_git(remote.path(), &["checkout", "release"]);
|
||||
std::fs::write(remote.path().join("marker"), marker).unwrap();
|
||||
run_git(remote.path(), &["commit", "-am", "update release"]);
|
||||
}
|
||||
assert_eq!(
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
PluginGitMode::Automatic,
|
||||
&reload_config,
|
||||
),
|
||||
ConfiguredMarketplaceUpgradeOutcome {
|
||||
selected_marketplaces: vec!["good".to_string()],
|
||||
upgraded_roots: vec![root.clone()],
|
||||
errors: Vec::new(),
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("marker")).unwrap(),
|
||||
marker
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(codex_home.path().join("system.toml")).unwrap(),
|
||||
system
|
||||
);
|
||||
let user_file = codex_home.path().join(CONFIG_TOML_FILE);
|
||||
if user_config.is_empty() {
|
||||
assert!(!user_file.exists());
|
||||
} else {
|
||||
assert_eq!(std::fs::read_to_string(user_file).unwrap(), user_config);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_config_rolls_back_marketplace_activation() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "good");
|
||||
let source = url::Url::from_directory_path(remote.path())
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let system = format!("[marketplaces.good]\nsource_type = \"git\"\nsource = {source:?}\n");
|
||||
let stack = system_marketplace_stack(codex_home.path(), &system, "");
|
||||
let reload_config = config_reloader(codex_home.path());
|
||||
let initial = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
&reload_config,
|
||||
);
|
||||
assert!(initial.all_succeeded());
|
||||
let root = &initial.upgraded_roots[0];
|
||||
let original_metadata = std::fs::read(root.join(".codex-marketplace-install.json")).unwrap();
|
||||
std::fs::write(remote.path().join("new-file"), "new revision").unwrap();
|
||||
run_git(remote.path(), &["add", "."]);
|
||||
run_git(remote.path(), &["commit", "-m", "update"]);
|
||||
for (file, changed_config) in [
|
||||
("system.toml", format!("{system}ref = \"different\"\n")),
|
||||
("system.toml", String::new()),
|
||||
(
|
||||
CONFIG_TOML_FILE,
|
||||
"[marketplaces.good]\nref = \"user-override\"\n".to_string(),
|
||||
),
|
||||
(CONFIG_TOML_FILE, "invalid = [".to_string()),
|
||||
] {
|
||||
std::fs::write(codex_home.path().join("system.toml"), &system).unwrap();
|
||||
std::fs::write(codex_home.path().join(file), changed_config).unwrap();
|
||||
let outcome = upgrade_configured_git_marketplaces(
|
||||
codex_home.path(),
|
||||
&stack,
|
||||
Some("good"),
|
||||
&reload_config,
|
||||
);
|
||||
assert_eq!(outcome.upgraded_roots, Vec::new());
|
||||
assert_eq!(outcome.errors.len(), 1);
|
||||
assert!(!root.join("new-file").exists());
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".codex-marketplace-install.json")).unwrap(),
|
||||
original_metadata
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_upgrade_skips_known_name_mismatch_until_the_ref_or_revision_changes() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let home = codex_home.path();
|
||||
let remote = TempDir::new().unwrap();
|
||||
init_marketplace_repo(remote.path(), "renamed");
|
||||
let config = format!(
|
||||
"[marketplaces.original]\nsource_type = 'git'\nsource = {:?}\n",
|
||||
remote.path().to_str().unwrap()
|
||||
);
|
||||
let config_path = home.join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&config_path, &config).unwrap();
|
||||
let reload = config_reloader(home);
|
||||
let upgrade = |mode| {
|
||||
upgrade_configured_git_marketplaces_with_mode(
|
||||
home,
|
||||
&reload().unwrap(),
|
||||
/*marketplace_name*/ None,
|
||||
mode,
|
||||
&reload,
|
||||
)
|
||||
};
|
||||
|
||||
let first = upgrade(PluginGitMode::Automatic);
|
||||
assert_eq!(first.errors.len(), 1);
|
||||
assert!(
|
||||
first.errors[0]
|
||||
.message
|
||||
.contains("upgraded marketplace name `renamed`")
|
||||
);
|
||||
|
||||
// Only a fresh checkout recreates the staging directory.
|
||||
let staging = marketplace_install_root(home).join(".staging");
|
||||
std::fs::remove_dir(&staging).unwrap();
|
||||
assert_eq!(upgrade(PluginGitMode::Automatic).errors, first.errors);
|
||||
assert!(!staging.exists());
|
||||
assert_eq!(upgrade(PluginGitMode::Manual).errors, first.errors);
|
||||
assert!(staging.is_dir());
|
||||
|
||||
// A different ref still needs a checkout even when it points to the same commit.
|
||||
run_git(remote.path(), &["checkout", "-b", "same-revision"]);
|
||||
std::fs::write(&config_path, format!("{config}ref = 'same-revision'\n")).unwrap();
|
||||
std::fs::remove_dir(&staging).unwrap();
|
||||
assert_eq!(upgrade(PluginGitMode::Automatic).errors, first.errors);
|
||||
assert!(staging.is_dir());
|
||||
|
||||
std::fs::write(
|
||||
remote.path().join(".agents/plugins/marketplace.json"),
|
||||
r#"{"name":"original","plugins":[]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
run_git(
|
||||
remote.path(),
|
||||
&["commit", "-am", "restore marketplace name"],
|
||||
);
|
||||
let recovered = upgrade(PluginGitMode::Automatic);
|
||||
assert!(recovered.errors.is_empty());
|
||||
assert_eq!(recovered.upgraded_roots.len(), 1);
|
||||
}
|
||||
|
||||
fn init_marketplace_repo(repo: &Path, marketplace_name: &str) {
|
||||
let manifest_dir = repo.join(".agents/plugins");
|
||||
std::fs::create_dir_all(&manifest_dir).expect("create marketplace manifest directory");
|
||||
std::fs::write(
|
||||
manifest_dir.join("marketplace.json"),
|
||||
format!(r#"{{"name":"{marketplace_name}","plugins":[]}}"#),
|
||||
)
|
||||
.expect("write marketplace manifest");
|
||||
run_git(repo, &["init"]);
|
||||
run_git(repo, &["config", "user.email", "codex-test@example.com"]);
|
||||
run_git(repo, &["config", "user.name", "Codex Test"]);
|
||||
run_git(repo, &["add", "."]);
|
||||
run_git(repo, &["commit", "-m", "initial"]);
|
||||
}
|
||||
|
||||
fn run_git(repo: &Path, args: &[&str]) {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("run git");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git {args:?} failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
187
codex-rs/core-plugins/src/npm_source.rs
Normal file
187
codex-rs/core-plugins/src/npm_source.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const NPM_PLUGIN_SOURCE_STAGING_DIR: &str = "plugins/.marketplace-plugin-source-staging";
|
||||
const NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES: u64 = 50 * 1024 * 1024;
|
||||
const NPM_PLUGIN_SOURCE_MAX_EXTRACTED_BYTES: u64 = 250 * 1024 * 1024;
|
||||
const NPM_PACKAGE_ARCHIVE_ROOT: &str = "package";
|
||||
|
||||
pub(crate) fn materialize_npm_plugin_source(
|
||||
codex_home: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
) -> Result<(AbsolutePathBuf, TempDir), String> {
|
||||
materialize_npm_plugin_source_with_command(
|
||||
codex_home,
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
OsStr::new(npm_command()),
|
||||
)
|
||||
}
|
||||
|
||||
fn materialize_npm_plugin_source_with_command(
|
||||
codex_home: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
npm_command: &OsStr,
|
||||
) -> Result<(AbsolutePathBuf, TempDir), String> {
|
||||
let staging_root = codex_home.join(NPM_PLUGIN_SOURCE_STAGING_DIR);
|
||||
fs::create_dir_all(&staging_root).map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace plugin source staging directory {}: {err}",
|
||||
staging_root.display()
|
||||
)
|
||||
})?;
|
||||
let tempdir = tempfile::Builder::new()
|
||||
.prefix("marketplace-plugin-source-")
|
||||
.tempdir_in(&staging_root)
|
||||
.map_err(|err| {
|
||||
format!(
|
||||
"failed to create marketplace plugin source staging directory in {}: {err}",
|
||||
staging_root.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
pack_npm_package(tempdir.path(), package, version, registry, npm_command)?;
|
||||
let archive_path = find_npm_package_archive(tempdir.path())?;
|
||||
let archive_bytes = read_npm_package_archive(&archive_path)?;
|
||||
|
||||
let extraction_root = tempdir.path().join("extracted");
|
||||
unpack_plugin_bundle_tar_gz(
|
||||
&archive_bytes,
|
||||
&extraction_root,
|
||||
NPM_PLUGIN_SOURCE_MAX_EXTRACTED_BYTES,
|
||||
)
|
||||
.map_err(|err| format!("failed to extract npm plugin package: {err}"))?;
|
||||
let plugin_root = extraction_root.join(NPM_PACKAGE_ARCHIVE_ROOT);
|
||||
if !plugin_root.is_dir() {
|
||||
return Err(format!(
|
||||
"npm pack completed without creating plugin package directory {}",
|
||||
plugin_root.display()
|
||||
));
|
||||
}
|
||||
validate_npm_package_metadata(&plugin_root, package)?;
|
||||
let plugin_root = AbsolutePathBuf::try_from(plugin_root)
|
||||
.map_err(|err| format!("failed to resolve materialized plugin source path: {err}"))?;
|
||||
Ok((plugin_root, tempdir))
|
||||
}
|
||||
|
||||
fn pack_npm_package(
|
||||
destination: &Path,
|
||||
package: &str,
|
||||
version: Option<&str>,
|
||||
registry: Option<&str>,
|
||||
npm_command: &OsStr,
|
||||
) -> Result<(), String> {
|
||||
let package_spec = version.map_or_else(
|
||||
|| package.to_string(),
|
||||
|version| format!("{package}@{version}"),
|
||||
);
|
||||
let mut command = codex_utils_process::background_command(npm_command);
|
||||
command
|
||||
.current_dir(destination)
|
||||
.arg("pack")
|
||||
.arg("--ignore-scripts")
|
||||
.arg("--pack-destination")
|
||||
.arg(destination);
|
||||
if let Some(registry) = registry {
|
||||
command.arg("--registry").arg(registry);
|
||||
}
|
||||
command.arg("--").arg(package_spec);
|
||||
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|err| format!("failed to run npm pack: {err}"))?;
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"npm pack failed with status {}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout).trim(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
))
|
||||
}
|
||||
|
||||
fn find_npm_package_archive(destination: &Path) -> Result<PathBuf, String> {
|
||||
let mut archives = fs::read_dir(destination)
|
||||
.map_err(|err| format!("failed to read npm pack destination: {err}"))?
|
||||
.filter_map(std::result::Result::ok)
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
let is_file = entry.file_type().is_ok_and(|file_type| file_type.is_file());
|
||||
(is_file && path.extension() == Some(OsStr::new("tgz"))).then_some(path)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if archives.len() != 1 {
|
||||
return Err(format!(
|
||||
"npm pack completed with {} package archives; expected exactly one",
|
||||
archives.len()
|
||||
));
|
||||
}
|
||||
Ok(archives.remove(0))
|
||||
}
|
||||
|
||||
fn read_npm_package_archive(archive_path: &Path) -> Result<Vec<u8>, String> {
|
||||
let archive_size = fs::metadata(archive_path)
|
||||
.map_err(|err| format!("failed to inspect npm package archive: {err}"))?
|
||||
.len();
|
||||
if archive_size > NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES {
|
||||
return Err(format!(
|
||||
"npm package archive is {archive_size} bytes, exceeding maximum size of {NPM_PLUGIN_SOURCE_MAX_ARCHIVE_BYTES} bytes"
|
||||
));
|
||||
}
|
||||
fs::read(archive_path).map_err(|err| format!("failed to read npm package archive: {err}"))
|
||||
}
|
||||
|
||||
fn validate_npm_package_metadata(plugin_root: &Path, package: &str) -> Result<(), String> {
|
||||
#[derive(Deserialize)]
|
||||
struct NpmPackageMetadata {
|
||||
name: String,
|
||||
}
|
||||
|
||||
let package_json_path = plugin_root.join("package.json");
|
||||
let package_json = fs::read_to_string(&package_json_path).map_err(|err| {
|
||||
format!(
|
||||
"failed to read npm plugin package metadata {}: {err}",
|
||||
package_json_path.display()
|
||||
)
|
||||
})?;
|
||||
let metadata: NpmPackageMetadata = serde_json::from_str(&package_json).map_err(|err| {
|
||||
format!(
|
||||
"failed to parse npm plugin package metadata {}: {err}",
|
||||
package_json_path.display()
|
||||
)
|
||||
})?;
|
||||
if metadata.name != package {
|
||||
return Err(format!(
|
||||
"npm plugin package name '{}' does not match requested package '{package}'",
|
||||
metadata.name
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn npm_command() -> &'static str {
|
||||
"npm.cmd"
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn npm_command() -> &'static str {
|
||||
"npm"
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "npm_source_tests.rs"]
|
||||
mod tests;
|
||||
104
codex-rs/core-plugins/src/npm_source_tests.rs
Normal file
104
codex-rs/core-plugins/src/npm_source_tests.rs
Normal file
@@ -0,0 +1,104 @@
|
||||
use super::*;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Cursor;
|
||||
use std::io::Write;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn materialize_npm_plugin_source_uses_packed_package_root() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let fake_npm_dir = tempfile::tempdir().expect("create fake npm directory");
|
||||
let archive_bytes =
|
||||
npm_package_archive_bytes("@acme/plugin", "1.2.0").expect("build fixture archive");
|
||||
let archive_path = fake_npm_dir.path().join("fixture.tgz");
|
||||
fs::write(&archive_path, &archive_bytes).expect("write fixture archive");
|
||||
let fake_npm = fake_npm_dir.path().join("npm");
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&fake_npm,
|
||||
&format!(
|
||||
r#"#!/bin/sh
|
||||
destination=""
|
||||
previous=""
|
||||
for argument in "$@"; do
|
||||
if [ "$previous" = "--pack-destination" ]; then
|
||||
destination="$argument"
|
||||
fi
|
||||
previous="$argument"
|
||||
done
|
||||
cp "{}" "$destination/acme-plugin-1.2.0.tgz"
|
||||
printf '%s\n' "$@" > "$destination/args.txt"
|
||||
pwd > "$destination/pwd.txt"
|
||||
"#,
|
||||
archive_path.display()
|
||||
),
|
||||
)
|
||||
.expect("write fake npm");
|
||||
|
||||
let (plugin_root, tempdir) = materialize_npm_plugin_source_with_command(
|
||||
codex_home.path(),
|
||||
"@acme/plugin",
|
||||
Some("^1.2.0"),
|
||||
Some("https://npm.example.com"),
|
||||
fake_npm.as_os_str(),
|
||||
)
|
||||
.expect("materialize npm source");
|
||||
|
||||
assert_eq!(
|
||||
plugin_root.as_path(),
|
||||
tempdir.path().join("extracted/package")
|
||||
);
|
||||
assert!(
|
||||
plugin_root
|
||||
.as_path()
|
||||
.join(".codex-plugin/plugin.json")
|
||||
.is_file()
|
||||
);
|
||||
let args = fs::read_to_string(tempdir.path().join("args.txt")).expect("read npm arguments");
|
||||
assert!(args.contains("pack"));
|
||||
assert!(args.contains("--ignore-scripts"));
|
||||
assert!(args.contains("--registry"));
|
||||
assert!(args.contains("https://npm.example.com"));
|
||||
assert!(args.contains("@acme/plugin@^1.2.0"));
|
||||
assert!(!args.contains("install"));
|
||||
let npm_working_directory = fs::canonicalize(
|
||||
fs::read_to_string(tempdir.path().join("pwd.txt"))
|
||||
.expect("read npm working directory")
|
||||
.trim(),
|
||||
)
|
||||
.expect("canonicalize npm working directory");
|
||||
assert_eq!(
|
||||
npm_working_directory,
|
||||
fs::canonicalize(tempdir.path()).expect("canonicalize tempdir")
|
||||
);
|
||||
}
|
||||
|
||||
fn npm_package_archive_bytes(package: &str, version: &str) -> std::io::Result<Vec<u8>> {
|
||||
let encoder = GzEncoder::new(Vec::new(), Compression::default());
|
||||
let mut archive = tar::Builder::new(encoder);
|
||||
append_archive_file(
|
||||
&mut archive,
|
||||
"package/package.json",
|
||||
format!(r#"{{"name":"{package}","version":"{version}"}}"#).as_bytes(),
|
||||
)?;
|
||||
append_archive_file(
|
||||
&mut archive,
|
||||
"package/.codex-plugin/plugin.json",
|
||||
br#"{"name":"plugin"}"#,
|
||||
)?;
|
||||
let encoder = archive.into_inner()?;
|
||||
encoder.finish()
|
||||
}
|
||||
|
||||
fn append_archive_file<W: Write>(
|
||||
archive: &mut tar::Builder<W>,
|
||||
path: &str,
|
||||
contents: &[u8],
|
||||
) -> std::io::Result<()> {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
archive.append_data(&mut header, path, Cursor::new(contents))
|
||||
}
|
||||
322
codex-rs/core-plugins/src/plugin_bundle_archive.rs
Normal file
322
codex-rs/core-plugins/src/plugin_bundle_archive.rs
Normal file
@@ -0,0 +1,322 @@
|
||||
use crate::manifest::load_plugin_manifest;
|
||||
use flate2::Compression;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use std::fmt;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tar::Archive;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum PluginBundlePackError {
|
||||
#[error("invalid plugin path `{path}`: {reason}")]
|
||||
InvalidPluginPath { path: PathBuf, reason: String },
|
||||
|
||||
#[error("plugin archive would be {bytes} bytes, exceeding maximum size of {max_bytes} bytes")]
|
||||
ArchiveTooLarge { bytes: usize, max_bytes: usize },
|
||||
|
||||
#[error("failed to archive plugin bundle: {source}")]
|
||||
Io {
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum PluginBundleUnpackError {
|
||||
#[error(
|
||||
"plugin bundle extracted size would be {bytes} bytes, exceeding maximum total size of {max_bytes} bytes"
|
||||
)]
|
||||
ExtractedBundleTooLarge { bytes: u64, max_bytes: u64 },
|
||||
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
|
||||
#[error("{0}")]
|
||||
InvalidBundle(String),
|
||||
}
|
||||
|
||||
impl PluginBundleUnpackError {
|
||||
fn io(context: &'static str, source: io::Error) -> Self {
|
||||
Self::Io { context, source }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pack_plugin_bundle_tar_gz(
|
||||
plugin_path: &Path,
|
||||
max_bytes: usize,
|
||||
) -> Result<Vec<u8>, PluginBundlePackError> {
|
||||
if !plugin_path.is_dir() {
|
||||
return Err(PluginBundlePackError::InvalidPluginPath {
|
||||
path: plugin_path.to_path_buf(),
|
||||
reason: "expected a plugin directory".to_string(),
|
||||
});
|
||||
}
|
||||
if !plugin_path.join(".codex-plugin/plugin.json").is_file()
|
||||
&& load_plugin_manifest(plugin_path).is_none()
|
||||
{
|
||||
return Err(PluginBundlePackError::InvalidPluginPath {
|
||||
path: plugin_path.to_path_buf(),
|
||||
reason: "missing .codex-plugin/plugin.json or valid Agent Plugin manifest".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let encoder = GzEncoder::new(SizeLimitedBuffer::new(max_bytes), Compression::default());
|
||||
let mut archive = tar::Builder::new(encoder);
|
||||
append_plugin_tree(&mut archive, plugin_path, plugin_path).map_err(archive_io_error)?;
|
||||
let encoder = archive.into_inner().map_err(archive_io_error)?;
|
||||
encoder
|
||||
.finish()
|
||||
.map(SizeLimitedBuffer::into_inner)
|
||||
.map_err(archive_io_error)
|
||||
}
|
||||
|
||||
fn append_plugin_tree<W: Write>(
|
||||
archive: &mut tar::Builder<W>,
|
||||
plugin_root: &Path,
|
||||
current: &Path,
|
||||
) -> io::Result<()> {
|
||||
let mut entries = fs::read_dir(current)?.collect::<Result<Vec<_>, io::Error>>()?;
|
||||
entries.sort_by_key(fs::DirEntry::file_name);
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
let file_type = entry.file_type()?;
|
||||
let relative_path = path.strip_prefix(plugin_root).map_err(|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to compute plugin archive path for `{}`: {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
if file_type.is_dir() {
|
||||
archive.append_dir(relative_path, &path)?;
|
||||
append_plugin_tree(archive, plugin_root, &path)?;
|
||||
} else if file_type.is_file() {
|
||||
archive.append_path_with_name(&path, relative_path)?;
|
||||
} else {
|
||||
return Err(io::Error::other(format!(
|
||||
"unsupported plugin archive entry type: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn archive_io_error(source: io::Error) -> PluginBundlePackError {
|
||||
if let Some(limit) = source
|
||||
.get_ref()
|
||||
.and_then(|err| err.downcast_ref::<ArchiveSizeLimitExceeded>())
|
||||
{
|
||||
return PluginBundlePackError::ArchiveTooLarge {
|
||||
bytes: limit.bytes,
|
||||
max_bytes: limit.max_bytes,
|
||||
};
|
||||
}
|
||||
|
||||
PluginBundlePackError::Io { source }
|
||||
}
|
||||
|
||||
pub(crate) fn unpack_plugin_bundle_tar_gz(
|
||||
bytes: &[u8],
|
||||
destination: &Path,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
fs::create_dir_all(destination).map_err(|source| {
|
||||
PluginBundleUnpackError::io(
|
||||
"failed to create plugin bundle extraction directory",
|
||||
source,
|
||||
)
|
||||
})?;
|
||||
|
||||
let archive = GzDecoder::new(std::io::Cursor::new(bytes));
|
||||
let mut archive = Archive::new(archive);
|
||||
unpack_plugin_bundle_tar(&mut archive, destination, max_total_bytes)
|
||||
}
|
||||
|
||||
fn unpack_plugin_bundle_tar<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
destination: &Path,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
let mut extracted_bytes = 0u64;
|
||||
let entries = archive.entries().map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar", source)
|
||||
})?;
|
||||
for entry in entries {
|
||||
let mut entry = entry.map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar entry", source)
|
||||
})?;
|
||||
let entry_type = entry.header().entry_type();
|
||||
let entry_size = entry.size();
|
||||
let entry_path = entry
|
||||
.path()
|
||||
.map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to read plugin bundle tar entry path", source)
|
||||
})?
|
||||
.into_owned();
|
||||
let output_path = checked_tar_output_path(destination, &entry_path)?;
|
||||
|
||||
if entry_type.is_dir() {
|
||||
fs::create_dir_all(&output_path).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to create plugin bundle directory", source)
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
|
||||
if entry_type.is_file() {
|
||||
enforce_total_extracted_size(entry_size, &mut extracted_bytes, max_total_bytes)?;
|
||||
let Some(parent) = output_path.parent() else {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle output path has no parent: {}",
|
||||
output_path.display()
|
||||
)));
|
||||
};
|
||||
fs::create_dir_all(parent).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to create plugin bundle directory", source)
|
||||
})?;
|
||||
entry.unpack(&output_path).map_err(|source| {
|
||||
PluginBundleUnpackError::io("failed to unpack plugin bundle entry", source)
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
|
||||
if entry_type.is_hard_link() || entry_type.is_symlink() {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` is a link",
|
||||
entry_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` has unsupported type {:?}",
|
||||
entry_path.display(),
|
||||
entry_type
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn checked_tar_output_path(
|
||||
destination: &Path,
|
||||
entry_name: &Path,
|
||||
) -> Result<PathBuf, PluginBundleUnpackError> {
|
||||
let mut output_path = destination.to_path_buf();
|
||||
let mut has_component = false;
|
||||
for component in entry_name.components() {
|
||||
match component {
|
||||
std::path::Component::Normal(component) => {
|
||||
has_component = true;
|
||||
output_path.push(component);
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir
|
||||
| std::path::Component::RootDir
|
||||
| std::path::Component::Prefix(_) => {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(format!(
|
||||
"plugin bundle tar entry `{}` escapes extraction root",
|
||||
entry_name.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has_component {
|
||||
return Err(PluginBundleUnpackError::InvalidBundle(
|
||||
"plugin bundle tar entry has an empty path".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(output_path)
|
||||
}
|
||||
|
||||
fn enforce_total_extracted_size(
|
||||
entry_size: u64,
|
||||
extracted_bytes: &mut u64,
|
||||
max_total_bytes: u64,
|
||||
) -> Result<(), PluginBundleUnpackError> {
|
||||
let next_total = extracted_bytes.checked_add(entry_size).ok_or(
|
||||
PluginBundleUnpackError::ExtractedBundleTooLarge {
|
||||
bytes: u64::MAX,
|
||||
max_bytes: max_total_bytes,
|
||||
},
|
||||
)?;
|
||||
if next_total > max_total_bytes {
|
||||
return Err(PluginBundleUnpackError::ExtractedBundleTooLarge {
|
||||
bytes: next_total,
|
||||
max_bytes: max_total_bytes,
|
||||
});
|
||||
}
|
||||
*extracted_bytes = next_total;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SizeLimitedBuffer {
|
||||
bytes: Vec<u8>,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl SizeLimitedBuffer {
|
||||
fn new(max_bytes: usize) -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
max_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_inner(self) -> Vec<u8> {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for SizeLimitedBuffer {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let next_len = self.bytes.len().checked_add(buf.len()).ok_or_else(|| {
|
||||
io::Error::other(ArchiveSizeLimitExceeded {
|
||||
bytes: usize::MAX,
|
||||
max_bytes: self.max_bytes,
|
||||
})
|
||||
})?;
|
||||
if next_len > self.max_bytes {
|
||||
return Err(io::Error::other(ArchiveSizeLimitExceeded {
|
||||
bytes: next_len,
|
||||
max_bytes: self.max_bytes,
|
||||
}));
|
||||
}
|
||||
|
||||
self.bytes.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ArchiveSizeLimitExceeded {
|
||||
bytes: usize,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl fmt::Display for ArchiveSizeLimitExceeded {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"archive would be {} bytes, exceeding maximum size of {} bytes",
|
||||
self.bytes, self.max_bytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ArchiveSizeLimitExceeded {}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_bundle_archive_tests.rs"]
|
||||
mod tests;
|
||||
41
codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs
Normal file
41
codex-rs/core-plugins/src/plugin_bundle_archive_tests.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn portable_root_manifest_can_be_packed_and_unpacked() {
|
||||
let source = tempdir().expect("source tempdir");
|
||||
fs::write(
|
||||
source.path().join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"portable"}"#,
|
||||
)
|
||||
.expect("write portable manifest");
|
||||
fs::create_dir_all(source.path().join("skills/demo")).expect("create skill directory");
|
||||
fs::write(source.path().join("skills/demo/SKILL.md"), "# Demo\n").expect("write skill");
|
||||
|
||||
let archive =
|
||||
pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024).expect("pack portable plugin");
|
||||
let destination = tempdir().expect("destination tempdir");
|
||||
unpack_plugin_bundle_tar_gz(&archive, destination.path(), 1024 * 1024)
|
||||
.expect("unpack portable plugin");
|
||||
|
||||
assert!(destination.path().join("plugin.json").is_file());
|
||||
assert!(destination.path().join("skills/demo/SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_portable_manifest_is_rejected_before_packing() {
|
||||
let source = tempdir().expect("source tempdir");
|
||||
fs::write(
|
||||
source.path().join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"UPPER"}"#,
|
||||
)
|
||||
.expect("write invalid portable manifest");
|
||||
|
||||
let error = pack_plugin_bundle_tar_gz(source.path(), 1024 * 1024)
|
||||
.expect_err("invalid Agent Plugin manifest should fail");
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
PluginBundlePackError::InvalidPluginPath { .. }
|
||||
));
|
||||
}
|
||||
63
codex-rs/core-plugins/src/plugin_measurement_catalog.rs
Normal file
63
codex-rs/core-plugins/src/plugin_measurement_catalog.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! Selects one authenticated installed GLOBAL plugin without capability loading.
|
||||
|
||||
use super::*;
|
||||
use crate::store::validate_plugin_version_segment;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
|
||||
/// Fetches installation authorization and download metadata, but materializes no
|
||||
/// other installed plugins and never publishes to the shared plugin catalog.
|
||||
pub(crate) async fn fetch_measurement_reference_bundle(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
target: &crate::script_attribution::PluginMeasurementTarget,
|
||||
) -> anyhow::Result<Option<(String, crate::remote_bundle::ValidatedRemotePluginBundle)>> {
|
||||
ensure_chatgpt_auth(Some(auth))?;
|
||||
let installed = fetch_installed_plugins(
|
||||
config,
|
||||
auth,
|
||||
RemoteInstalledPluginScope::Single(RemotePluginScope::Global),
|
||||
/*include_download_urls*/ true,
|
||||
InstalledPluginDisplayAssets::Include,
|
||||
)
|
||||
.await?;
|
||||
let mut matching = installed.into_iter().filter(|installed| {
|
||||
let plugin = &installed.plugin;
|
||||
let Some(version) = plugin.release.version.as_deref().map(str::trim) else {
|
||||
return false;
|
||||
};
|
||||
if validate_plugin_version_segment(version).is_err() {
|
||||
return false;
|
||||
}
|
||||
// Compare with the executor's path rules, retaining the catalog's
|
||||
// spelling for the validated bundle and cache identity below.
|
||||
let matches_target = match target.path_convention {
|
||||
PathConvention::Windows => target
|
||||
.plugin_id
|
||||
.plugin_name
|
||||
.eq_ignore_ascii_case(&plugin.name),
|
||||
PathConvention::Posix => target.plugin_id.plugin_name == plugin.name,
|
||||
};
|
||||
installed.enabled
|
||||
&& plugin.scope == RemotePluginScope::Global
|
||||
&& matches_target
|
||||
&& plugin.availability == PluginAvailability::Available
|
||||
&& plugin.installation_policy != PluginInstallPolicy::NotAvailable
|
||||
&& plugin.disabled_reason.is_none()
|
||||
});
|
||||
let Some(installed) = matching.next() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if matching.next().is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let plugin = installed.plugin;
|
||||
let bundle = crate::remote_bundle::validate_remote_plugin_bundle(
|
||||
&plugin.id,
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
&plugin.name,
|
||||
plugin.release.version.as_deref(),
|
||||
plugin.release.bundle_download_url.as_deref(),
|
||||
plugin.release.app_manifest,
|
||||
)?;
|
||||
Ok(Some((plugin.id, bundle)))
|
||||
}
|
||||
244
codex-rs/core-plugins/src/plugin_measurement_references.rs
Normal file
244
codex-rs/core-plugins/src/plugin_measurement_references.rs
Normal file
@@ -0,0 +1,244 @@
|
||||
//! Authenticated, immutable references for one executor plugin's measurements.
|
||||
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::TrustedPluginRoots;
|
||||
use crate::manager::RemoteInstalledPluginsAuthIdentity;
|
||||
use crate::remote::fetch_measurement_reference_bundle;
|
||||
use crate::remote_bundle::download_remote_plugin_bundle;
|
||||
use crate::remote_bundle::install_remote_plugin_bundle;
|
||||
use crate::script_attribution::PluginMeasurementTarget;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::watch;
|
||||
|
||||
const MAX_CACHED_REFERENCES: usize = 4;
|
||||
|
||||
/// Owns the immutable files backing its roots. Keep the reference alive for the
|
||||
/// full command/turn that consumes those roots, including asynchronous commands.
|
||||
pub struct PluginMeasurementReference {
|
||||
roots: TrustedPluginRoots,
|
||||
home: Option<TempDir>,
|
||||
}
|
||||
|
||||
impl Drop for PluginMeasurementReference {
|
||||
fn drop(&mut self) {
|
||||
let Some(home) = self.home.take() else {
|
||||
return;
|
||||
};
|
||||
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
|
||||
runtime.spawn_blocking(move || drop(home));
|
||||
} else {
|
||||
drop(home);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginMeasurementReference {
|
||||
pub fn roots(&self) -> &TrustedPluginRoots {
|
||||
&self.roots
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct ReferenceKey {
|
||||
actor: RemoteInstalledPluginsAuthIdentity,
|
||||
endpoint: String,
|
||||
remote_id: String,
|
||||
plugin_id: PluginId,
|
||||
version: String,
|
||||
}
|
||||
|
||||
type ReferenceCell = Arc<watch::Receiver<Option<Arc<PluginMeasurementReference>>>>;
|
||||
|
||||
fn is_preparing(cell: &ReferenceCell) -> bool {
|
||||
cell.has_changed().is_ok() && cell.borrow().is_none()
|
||||
}
|
||||
|
||||
/// A thread-scoped cache, separate from the installed plugin/capability store.
|
||||
/// Each version has its own store so installing a new version cannot remove
|
||||
/// files still leased by an earlier turn. At most four entries are retained,
|
||||
/// including active preparations; command-held leases can outlive eviction.
|
||||
#[derive(Default)]
|
||||
pub struct RemotePluginMeasurementCache {
|
||||
references: Mutex<Vec<(ReferenceKey, ReferenceCell)>>,
|
||||
}
|
||||
|
||||
impl RemotePluginMeasurementCache {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Rechecks current installation authorization, then prepares only the
|
||||
/// requested version. Previously authenticated versions remain reusable after
|
||||
/// a release update; a cache miss can download only the current release.
|
||||
/// Callers apply analytics consent and product gates.
|
||||
/// Concurrent callers share a download even if one caller is cancelled.
|
||||
/// Returns no reference when all cache entries are actively preparing.
|
||||
/// Failures omit authenticated URLs and response bodies from diagnostics.
|
||||
pub async fn prepare(
|
||||
&self,
|
||||
config: &PluginsConfigInput,
|
||||
auth: &CodexAuth,
|
||||
target: &PluginMeasurementTarget,
|
||||
runtime_auth: Option<(RuntimeAuthSlot, RuntimeAuthMode)>,
|
||||
) -> anyhow::Result<Option<Arc<PluginMeasurementReference>>> {
|
||||
if !config.plugins_enabled || !config.remote_plugin_enabled || !auth.uses_codex_backend() {
|
||||
return Ok(None);
|
||||
}
|
||||
// Like normal remote loading, the authenticated installed catalog is
|
||||
// authoritative for enabled state, including default installations.
|
||||
// GLOBAL plugins have already passed server-side admission; local
|
||||
// marketplace product policy and skill capability loading are separate.
|
||||
let service = config
|
||||
.remote_plugin_service_config(runtime_auth)
|
||||
.for_current_account();
|
||||
let Some((remote_id, bundle)) = fetch_measurement_reference_bundle(&service, auth, target)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("plugin measurement catalog lookup failed"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
// The executor hint follows its filesystem's case rules. The cache and
|
||||
// local store use the authenticated bundle's exact identity instead.
|
||||
let plugin_id = bundle.plugin_id.clone();
|
||||
let version = bundle.plugin_version.clone();
|
||||
let current_version = match target.path_convention {
|
||||
PathConvention::Windows => target.version.eq_ignore_ascii_case(&version),
|
||||
PathConvention::Posix => target.version == version,
|
||||
};
|
||||
let key = ReferenceKey {
|
||||
actor: RemoteInstalledPluginsAuthIdentity::from_auth(Some(auth)),
|
||||
endpoint: config.chatgpt_base_url.clone(),
|
||||
remote_id: remote_id.clone(),
|
||||
plugin_id: plugin_id.clone(),
|
||||
version: if current_version {
|
||||
version.clone()
|
||||
} else {
|
||||
target.version.clone()
|
||||
},
|
||||
};
|
||||
let (cell, initializer, retired) = {
|
||||
let mut references = self.references.lock().await;
|
||||
let mut retired = Vec::new();
|
||||
// Keep active preparations admitted until they finish, even after an
|
||||
// identity change; they can never match the new key.
|
||||
for index in (0..references.len()).rev() {
|
||||
let (existing, cell) = &references[index];
|
||||
// A closed, empty result is a completed failure. Only a new
|
||||
// caller can admit a retry; existing waiters observe that failure.
|
||||
if (cell.has_changed().is_err() && cell.borrow().is_none())
|
||||
|| (!is_preparing(cell)
|
||||
&& (existing.actor != key.actor
|
||||
|| existing.endpoint != key.endpoint
|
||||
|| (existing.plugin_id == key.plugin_id
|
||||
&& existing.remote_id != key.remote_id)))
|
||||
{
|
||||
retired.push(references.remove(index));
|
||||
}
|
||||
}
|
||||
let mut initializer = None;
|
||||
let mut matching = references.iter().enumerate().filter(|(_, (existing, _))| {
|
||||
if current_version {
|
||||
return existing == &key;
|
||||
}
|
||||
existing.actor == key.actor
|
||||
&& existing.endpoint == key.endpoint
|
||||
&& existing.remote_id == key.remote_id
|
||||
&& existing.plugin_id == key.plugin_id
|
||||
&& match target.path_convention {
|
||||
PathConvention::Windows => {
|
||||
existing.version.eq_ignore_ascii_case(&key.version)
|
||||
}
|
||||
PathConvention::Posix => existing.version == key.version,
|
||||
}
|
||||
});
|
||||
// Historical Windows hints must not select between case-distinct releases.
|
||||
let cached_index = match (matching.next(), matching.next()) {
|
||||
(Some((index, _)), None) => Some(index),
|
||||
_ => None,
|
||||
};
|
||||
let cell = if let Some(index) = cached_index {
|
||||
let entry = references.remove(index);
|
||||
let cell = Arc::clone(&entry.1);
|
||||
references.push(entry);
|
||||
Some(cell)
|
||||
} else if !current_version {
|
||||
// The catalog cannot supply a trusted historical bundle.
|
||||
None
|
||||
} else if references.len() < MAX_CACHED_REFERENCES {
|
||||
let (sender, receiver) = watch::channel(None);
|
||||
let cell = Arc::new(receiver);
|
||||
initializer = Some(sender);
|
||||
references.push((key, Arc::clone(&cell)));
|
||||
Some(cell)
|
||||
} else if let Some(index) = references.iter().position(|(_, cell)| !is_preparing(cell))
|
||||
{
|
||||
retired.push(references.remove(index));
|
||||
let (sender, receiver) = watch::channel(None);
|
||||
let cell = Arc::new(receiver);
|
||||
initializer = Some(sender);
|
||||
references.push((key, Arc::clone(&cell)));
|
||||
Some(cell)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(cell, initializer, retired)
|
||||
};
|
||||
// Final reference drops schedule store cleanup outside the cache mutex.
|
||||
drop(retired);
|
||||
let Some(cell) = cell else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(sender) = initializer {
|
||||
// The cache keeps the receiver alive when individual callers cancel.
|
||||
// Once the cache and all callers disappear, stop waiting/downloading.
|
||||
tokio::spawn(async move {
|
||||
let reference = tokio::select! {
|
||||
biased;
|
||||
_ = sender.closed() => return,
|
||||
reference = async {
|
||||
let bytes = download_remote_plugin_bundle(&service, &bundle).await?;
|
||||
// Blocking extraction cannot be aborted once started. Its
|
||||
// owner must keep the store alive even if this task stops.
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let home = tempfile::tempdir()?;
|
||||
install_remote_plugin_bundle(home.path().to_owned(), bundle, bytes)?;
|
||||
let roots = TrustedPluginRoots::from_measurement_reference(
|
||||
home.path(),
|
||||
&plugin_id,
|
||||
&version,
|
||||
&remote_id,
|
||||
)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid plugin measurement reference"))?;
|
||||
Ok::<_, anyhow::Error>(Arc::new(PluginMeasurementReference {
|
||||
roots,
|
||||
home: Some(home),
|
||||
}))
|
||||
}).await?
|
||||
} => reference,
|
||||
};
|
||||
if let Ok(reference) = reference {
|
||||
sender.send_replace(Some(reference));
|
||||
}
|
||||
// Closing an empty channel reports failure without retaining
|
||||
// authenticated URLs or response bodies in the shared result.
|
||||
});
|
||||
}
|
||||
let mut receiver = cell.as_ref().clone();
|
||||
let reference = receiver
|
||||
.wait_for(Option::is_some)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("plugin measurement preparation failed"))?;
|
||||
Ok(reference.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_measurement_references_tests.rs"]
|
||||
mod tests;
|
||||
775
codex-rs/core-plugins/src/plugin_measurement_references_tests.rs
Normal file
775
codex-rs/core-plugins/src/plugin_measurement_references_tests.rs
Normal file
@@ -0,0 +1,775 @@
|
||||
//! Real bundle preparation tests without mutating the parent test environment.
|
||||
|
||||
use super::*;
|
||||
use crate::test_support::load_plugins_config;
|
||||
use crate::test_support::write_file;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::mpsc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
const SCRIPT: &str = "console.log('installed');\n";
|
||||
const ANALYTICS: &str = "version: 1\noperations:\n install:\n path: scripts/install.mjs\n measurements:\n duration_ms:\n dimensions:\n outcome: [success, error]\n";
|
||||
|
||||
fn isolated_bundle_test(name: &str) -> Result<bool> {
|
||||
const CHILD: &str = "CODEX_MEASUREMENT_REFERENCE_TEST";
|
||||
if std::env::var(CHILD).as_deref() == Ok(name) {
|
||||
return Ok(true);
|
||||
}
|
||||
let output = Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
&format!("plugin_measurement_references::tests::{name}"),
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD, name)
|
||||
.env("CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS", "1")
|
||||
.output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn installed(server: &MockServer, version: &str) -> Value {
|
||||
json!({
|
||||
"id": "plugins~sites", "name": "sites", "scope": "GLOBAL", "enabled": true,
|
||||
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", "status": "ENABLED",
|
||||
"release": {"version": version, "display_name": "Sites", "description": "",
|
||||
"bundle_download_url": format!("{}/bundle/{version}", server.uri()), "interface": {}}
|
||||
})
|
||||
}
|
||||
|
||||
async fn catalog(server: &MockServer, plugins: Vec<Value>) {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/ps/plugins/installed"))
|
||||
.and(query_param("scope", "GLOBAL"))
|
||||
.and(query_param("includeDownloadUrls", "true"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"plugins": plugins, "pagination": {}})),
|
||||
)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn archive(plugin_name: &str) -> Result<Vec<u8>> {
|
||||
let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
|
||||
let manifest = json!({"name": plugin_name, "version": "1.0.0"}).to_string();
|
||||
for (name, bytes) in [
|
||||
(".codex-plugin/plugin.json", manifest.as_str()),
|
||||
("scripts/install.mjs", SCRIPT),
|
||||
("analytics.yaml", ANALYTICS),
|
||||
// Invalid capability files must not be parsed by measurement preparation.
|
||||
(".mcp.json", "invalid json"),
|
||||
("skills/broken/SKILL.md", "invalid skill"),
|
||||
] {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(bytes.len() as u64);
|
||||
header.set_mode(0o644);
|
||||
header.set_cksum();
|
||||
archive.append_data(&mut header, name, bytes.as_bytes())?;
|
||||
}
|
||||
Ok(archive.into_inner()?.finish()?)
|
||||
}
|
||||
|
||||
async fn bundle(server: &MockServer, version: &str, count: u64) -> Result<()> {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/bundle/{version}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("sites")?))
|
||||
.expect(count)
|
||||
.mount(server)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_until_removed(path: &Path) -> Result<()> {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while path.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn named_plugin(server: &MockServer, name: &str) -> Result<(Value, PluginMeasurementTarget)> {
|
||||
let mut plugin = installed(server, "1.0.0");
|
||||
plugin["name"] = json!(name);
|
||||
plugin["id"] = json!(format!("plugins~{name}"));
|
||||
plugin["release"]["bundle_download_url"] = json!(format!("{}/bundle/{name}", server.uri()));
|
||||
let target = PluginMeasurementTarget {
|
||||
plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?,
|
||||
version: "1.0.0".to_owned(),
|
||||
path_convention: PathConvention::Posix,
|
||||
};
|
||||
Ok((plugin, target))
|
||||
}
|
||||
|
||||
async fn target(
|
||||
executor: &Path,
|
||||
version: &str,
|
||||
) -> Result<(PluginMeasurementTarget, Vec<String>, PathUri)> {
|
||||
let script = executor.join(format!(
|
||||
"plugins/cache/openai-curated-remote/sites/{version}/scripts/install.mjs"
|
||||
));
|
||||
write_file(&script, SCRIPT);
|
||||
let command = vec!["node".to_owned(), script.to_string_lossy().into_owned()];
|
||||
let cwd = PathUri::from_host_native_path(executor)?;
|
||||
let target = PluginMeasurementTarget::from_command(&command, &cwd, LOCAL_FS.as_ref())
|
||||
.await
|
||||
.context("canonical plugin target")?;
|
||||
Ok((target, command, cwd))
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
server: MockServer,
|
||||
home: TempDir,
|
||||
executor: TempDir,
|
||||
config: PluginsConfigInput,
|
||||
auth: CodexAuth,
|
||||
cache: RemotePluginMeasurementCache,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Result<Self> {
|
||||
let server = MockServer::start().await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let executor = tempfile::tempdir()?;
|
||||
let mut config = load_plugins_config(home.path(), executor.path()).await;
|
||||
config.chatgpt_base_url = server.uri();
|
||||
Ok(Self {
|
||||
server,
|
||||
home,
|
||||
executor,
|
||||
config,
|
||||
auth: CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
cache: RemotePluginMeasurementCache::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn prepare(
|
||||
&self,
|
||||
target: &PluginMeasurementTarget,
|
||||
) -> Result<Option<Arc<PluginMeasurementReference>>> {
|
||||
self.cache
|
||||
.prepare(&self.config, &self.auth, target, /*runtime_auth*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn assert_request_count(&self, expected: usize) {
|
||||
assert_eq!(
|
||||
self.server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("requests")
|
||||
.len(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
async fn wait_for_cached_reference(
|
||||
&self,
|
||||
ready: impl Fn(&ReferenceCell) -> bool,
|
||||
) -> Result<()> {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let is_ready = {
|
||||
let references = self.cache.references.lock().await;
|
||||
ready(&references[0].1)
|
||||
};
|
||||
if is_ready {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn narrow_preparation_reuses_versions_and_keeps_old_leases_alive() -> Result<()> {
|
||||
if !isolated_bundle_test("narrow_preparation_reuses_versions_and_keeps_old_leases_alive")? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut f = Fixture::new().await?;
|
||||
let (first, command, cwd) = target(f.executor.path(), "1.0.0").await?;
|
||||
let mut unrelated = installed(&f.server, "1.0.0");
|
||||
unrelated["id"] = json!("plugins~unrelated");
|
||||
unrelated["name"] = json!("unrelated");
|
||||
unrelated["release"]["bundle_download_url"] = json!("invalid URL must never be examined");
|
||||
catalog(&f.server, vec![unrelated, installed(&f.server, "1.0.0")]).await;
|
||||
bundle(&f.server, "1.0.0", /*count*/ 1).await?;
|
||||
let (left, right) = tokio::join!(f.prepare(&first), f.prepare(&first));
|
||||
let first_ref = left?.context("first reference")?;
|
||||
assert!(Arc::ptr_eq(
|
||||
&first_ref,
|
||||
&right?.context("parallel reference")?
|
||||
));
|
||||
let warm = f.prepare(&first).await?.context("warm reference")?;
|
||||
assert!(Arc::ptr_eq(&first_ref, &warm));
|
||||
let old_home = first_ref
|
||||
.home
|
||||
.as_ref()
|
||||
.expect("reference store")
|
||||
.path()
|
||||
.to_owned();
|
||||
let resolved = first_ref
|
||||
.roots()
|
||||
.resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref())
|
||||
.await
|
||||
.context("real resolver")?;
|
||||
assert_eq!(resolved.operation.operation_name, "install");
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
|
||||
let (second, _, _) = target(f.executor.path(), "2.0.0").await?;
|
||||
catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await;
|
||||
assert!(Arc::ptr_eq(
|
||||
&first_ref,
|
||||
&f.prepare(&first).await?.context("reference after update")?
|
||||
));
|
||||
// A newer release cannot supply an older version's declaration on a cold cache.
|
||||
assert!(
|
||||
RemotePluginMeasurementCache::new()
|
||||
.prepare(&f.config, &f.auth, &first, /*runtime_auth*/ None)
|
||||
.await?
|
||||
.is_none()
|
||||
);
|
||||
bundle(&f.server, "2.0.0", /*count*/ 1).await?;
|
||||
let new_ref = f.prepare(&second).await?.context("new reference")?;
|
||||
assert_ne!(
|
||||
new_ref.home.as_ref().expect("reference store").path(),
|
||||
old_home
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&first_ref,
|
||||
&f.prepare(&first).await?.context("retained older version")?
|
||||
));
|
||||
assert!(
|
||||
first_ref
|
||||
.roots()
|
||||
.resolve_metrics_operation_in_filesystem(&command, &cwd, LOCAL_FS.as_ref())
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
|
||||
let mut disabled = installed(&f.server, "2.0.0");
|
||||
disabled["enabled"] = json!(false);
|
||||
let mut replaced = installed(&f.server, "2.0.0");
|
||||
replaced["id"] = json!("plugins~replacement");
|
||||
for plugins in [vec![], vec![disabled], vec![replaced]] {
|
||||
catalog(&f.server, plugins).await;
|
||||
assert!(f.prepare(&first).await?.is_none());
|
||||
f.assert_request_count(/*expected*/ 1).await;
|
||||
f.server.reset().await;
|
||||
}
|
||||
drop(warm);
|
||||
drop(first_ref);
|
||||
|
||||
catalog(&f.server, vec![installed(&f.server, "2.0.0")]).await;
|
||||
bundle(&f.server, "2.0.0", /*count*/ 1).await?;
|
||||
f.auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.other",
|
||||
"other-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?;
|
||||
let other_ref = f.prepare(&second).await?.context("other actor reference")?;
|
||||
assert!(!Arc::ptr_eq(&new_ref, &other_ref));
|
||||
assert!(f.prepare(&first).await?.is_none());
|
||||
wait_until_removed(&old_home).await?;
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
|
||||
let mut disabled = installed(&f.server, "2.0.0");
|
||||
disabled["enabled"] = json!(false);
|
||||
catalog(&f.server, vec![disabled]).await;
|
||||
assert!(f.prepare(&second).await?.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preparation_preserves_catalog_spelling_and_executor_case_rules() -> Result<()> {
|
||||
if !isolated_bundle_test("preparation_preserves_catalog_spelling_and_executor_case_rules")? {
|
||||
return Ok(());
|
||||
}
|
||||
let f = Fixture::new().await?;
|
||||
let mut plugin = installed(&f.server, "2.0.0-RC1");
|
||||
plugin["name"] = json!("Sites");
|
||||
plugin["release"]["version"] = json!(" 2.0.0-RC1\n");
|
||||
catalog(&f.server, vec![plugin.clone()]).await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/bundle/2.0.0-RC1"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?))
|
||||
.expect(1)
|
||||
.mount(&f.server)
|
||||
.await;
|
||||
|
||||
// Drive and UNC preselection normalize these hints identically on every host.
|
||||
let windows = PluginMeasurementTarget {
|
||||
plugin_id: PluginId::parse("sites@openai-curated-remote")?,
|
||||
version: "2.0.0-rc1".to_owned(),
|
||||
path_convention: PathConvention::Windows,
|
||||
};
|
||||
let reference = f.prepare(&windows).await?.context("Windows reference")?;
|
||||
let exact = PluginMeasurementTarget {
|
||||
plugin_id: PluginId::parse("Sites@openai-curated-remote")?,
|
||||
version: "2.0.0-RC1".to_owned(),
|
||||
path_convention: PathConvention::Posix,
|
||||
};
|
||||
assert!(Arc::ptr_eq(
|
||||
&reference,
|
||||
&f.prepare(&exact)
|
||||
.await?
|
||||
.context("same authenticated bundle")?
|
||||
));
|
||||
let store = crate::store::PluginStore::new(
|
||||
reference
|
||||
.home
|
||||
.as_ref()
|
||||
.expect("reference store")
|
||||
.path()
|
||||
.to_owned(),
|
||||
);
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&exact.plugin_id),
|
||||
Some(exact.version.clone())
|
||||
);
|
||||
let root = store.plugin_root(&exact.plugin_id, &exact.version);
|
||||
let command = vec![
|
||||
"node".to_owned(),
|
||||
root.join("scripts/install.mjs")
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
];
|
||||
let operation = reference
|
||||
.roots()
|
||||
.resolve_metrics_operation(&command, &root)
|
||||
.context("trusted declaration retains the authenticated identity")?;
|
||||
assert_eq!(
|
||||
(operation.plugin_id, operation.operation.operation_name),
|
||||
(exact.plugin_id.clone(), "install".to_owned())
|
||||
);
|
||||
for (name, version) in [("sites", "2.0.0-RC1"), ("Sites", "2.0.0-rc1")] {
|
||||
let mismatch = PluginMeasurementTarget {
|
||||
plugin_id: PluginId::new(name.to_owned(), "openai-curated-remote".to_owned())?,
|
||||
version: version.to_owned(),
|
||||
path_convention: PathConvention::Posix,
|
||||
};
|
||||
assert!(f.prepare(&mismatch).await?.is_none());
|
||||
}
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
|
||||
let mut ambiguous = installed(&f.server, "2.0.0-rc1");
|
||||
ambiguous["id"] = json!("plugins~other-case");
|
||||
catalog(&f.server, vec![plugin.clone(), ambiguous]).await;
|
||||
assert!(f.prepare(&windows).await?.is_none());
|
||||
f.assert_request_count(/*expected*/ 1).await;
|
||||
// POSIX still selects its exact entry, even when another entry folds the same way.
|
||||
assert!(Arc::ptr_eq(
|
||||
&reference,
|
||||
&f.prepare(&exact)
|
||||
.await?
|
||||
.context("exact POSIX catalog entry")?
|
||||
));
|
||||
f.server.reset().await;
|
||||
|
||||
plugin["release"]["version"] = json!("2.0.0-rc1");
|
||||
catalog(&f.server, vec![plugin.clone()]).await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/bundle/2.0.0-RC1"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive("Sites")?))
|
||||
.expect(1)
|
||||
.mount(&f.server)
|
||||
.await;
|
||||
let lower_case = f
|
||||
.prepare(&windows)
|
||||
.await?
|
||||
.context("current catalog version")?;
|
||||
assert!(!Arc::ptr_eq(&reference, &lower_case));
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
|
||||
plugin["release"]["version"] = json!("3.0.0");
|
||||
catalog(&f.server, vec![plugin]).await;
|
||||
assert!(f.prepare(&windows).await?.is_none());
|
||||
assert!(Arc::ptr_eq(
|
||||
&reference,
|
||||
&f.prepare(&exact)
|
||||
.await?
|
||||
.context("unambiguous historical version")?
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preparation_requires_enabled_matching_installed_global_plugin() -> Result<()> {
|
||||
if !isolated_bundle_test("preparation_requires_enabled_matching_installed_global_plugin")? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut f = Fixture::new().await?;
|
||||
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
|
||||
for (field, value) in [
|
||||
("/enabled", json!(false)),
|
||||
("/scope", json!("WORKSPACE")),
|
||||
("/installation_policy", json!("NOT_AVAILABLE")),
|
||||
("/status", json!("DISABLED_BY_ADMIN")),
|
||||
("/name", json!("other")),
|
||||
("/release/version", json!(" ")),
|
||||
("/release/version", json!("../1.0.0")),
|
||||
] {
|
||||
let mut plugin = installed(&f.server, "1.0.0");
|
||||
*plugin.pointer_mut(field).expect("catalog field") = value;
|
||||
catalog(&f.server, vec![plugin]).await;
|
||||
assert!(f.prepare(&target).await?.is_none(), "{field}");
|
||||
f.assert_request_count(/*expected*/ 1).await;
|
||||
f.server.reset().await;
|
||||
}
|
||||
catalog(&f.server, vec![installed(&f.server, "1.0.0"); 2]).await;
|
||||
assert!(f.prepare(&target).await?.is_none());
|
||||
f.server.reset().await;
|
||||
for (enabled, auth) in [
|
||||
(false, f.auth.clone()),
|
||||
(true, CodexAuth::from_api_key("test")),
|
||||
] {
|
||||
f.config.remote_plugin_enabled = enabled;
|
||||
f.auth = auth;
|
||||
assert!(f.prepare(&target).await?.is_none());
|
||||
}
|
||||
f.assert_request_count(/*expected*/ 0).await;
|
||||
|
||||
write_file(
|
||||
&f.home.path().join("config.toml"),
|
||||
"[plugins.\"sites@openai-curated-remote\"]\nenabled = false\n",
|
||||
);
|
||||
f.config = load_plugins_config(f.home.path(), f.executor.path()).await;
|
||||
f.config.chatgpt_base_url = f.server.uri();
|
||||
f.auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let mut forced = installed(&f.server, "1.0.0");
|
||||
forced["installation_policy"] = json!("INSTALLED_BY_DEFAULT");
|
||||
catalog(&f.server, vec![forced]).await;
|
||||
bundle(&f.server, "1.0.0", /*count*/ 1).await?;
|
||||
assert!(f.prepare(&target).await?.is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preparation_failures_do_not_expose_authenticated_urls_or_response_bodies() -> Result<()> {
|
||||
if !isolated_bundle_test(
|
||||
"preparation_failures_do_not_expose_authenticated_urls_or_response_bodies",
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
let f = Fixture::new().await?;
|
||||
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
|
||||
for invalid_url in [true, false] {
|
||||
let mut plugin = installed(&f.server, "1.0.0");
|
||||
plugin["release"]["bundle_download_url"] = json!(if invalid_url {
|
||||
"not a URL?sig=query-secret".to_owned()
|
||||
} else {
|
||||
format!("{}/bundle/1.0.0?sig=query-secret", f.server.uri())
|
||||
});
|
||||
catalog(&f.server, vec![plugin]).await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/bundle/1.0.0"))
|
||||
.respond_with(ResponseTemplate::new(500).set_body_string("response-body-secret"))
|
||||
.expect(u64::from(!invalid_url))
|
||||
.mount(&f.server)
|
||||
.await;
|
||||
let error = match f.prepare(&target).await {
|
||||
Err(error) => error,
|
||||
Ok(_) => anyhow::bail!("expected a preparation failure"),
|
||||
};
|
||||
for diagnostic in [
|
||||
format!("{error}"),
|
||||
format!("{error:#}"),
|
||||
format!("{error:?}"),
|
||||
format!("{error:#?}"),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(error.chain().map(ToString::to_string))
|
||||
{
|
||||
for secret in [
|
||||
"query-secret",
|
||||
"response-body-secret",
|
||||
"sig=",
|
||||
f.server.uri().as_str(),
|
||||
] {
|
||||
assert!(!diagnostic.contains(secret), "diagnostic exposed {secret}");
|
||||
}
|
||||
}
|
||||
f.server.verify().await;
|
||||
f.server.reset().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceled_waiters_do_not_retry_a_failed_preparation() -> Result<()> {
|
||||
if !isolated_bundle_test("canceled_waiters_do_not_retry_a_failed_preparation")? {
|
||||
return Ok(());
|
||||
}
|
||||
let f = Arc::new(Fixture::new().await?);
|
||||
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
|
||||
let target = Arc::new(target);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let mut plugin = installed(&f.server, "1.0.0");
|
||||
plugin["release"]["bundle_download_url"] =
|
||||
json!(format!("http://{}/bundle", listener.local_addr()?));
|
||||
catalog(&f.server, vec![plugin]).await;
|
||||
let release = Arc::new(Semaphore::new(0));
|
||||
let (requested, mut requests) = mpsc::unbounded_channel();
|
||||
let bundle_server = tokio::spawn({
|
||||
let release = Arc::clone(&release);
|
||||
async move {
|
||||
for attempt in 0..2 {
|
||||
let (socket, _) = listener.accept().await?;
|
||||
let mut socket = tokio::io::BufReader::new(socket);
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
socket.read_line(&mut line).await?;
|
||||
if line == "\r\n" || line.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
requested.send(attempt)?;
|
||||
let (status, body) = if attempt == 0 {
|
||||
release.acquire().await?.forget();
|
||||
("500 Internal Server Error", Vec::new())
|
||||
} else {
|
||||
("200 OK", archive("sites")?)
|
||||
};
|
||||
socket
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await?;
|
||||
socket.write_all(&body).await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
});
|
||||
let mut callers = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let f = Arc::clone(&f);
|
||||
let target = Arc::clone(&target);
|
||||
callers.push(tokio::spawn(async move { f.prepare(&target).await }));
|
||||
}
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), requests.recv()).await?,
|
||||
Some(0)
|
||||
);
|
||||
// Wait until all four callers hold the cell alongside the cache before
|
||||
// canceling the callers during the held download.
|
||||
f.wait_for_cached_reference(|cell| Arc::strong_count(cell) >= 5)
|
||||
.await?;
|
||||
for caller in callers {
|
||||
caller.abort();
|
||||
assert!(matches!(caller.await, Err(error) if error.is_cancelled()));
|
||||
}
|
||||
release.add_permits(1);
|
||||
// Observe all admitted workers finishing before checking the request count;
|
||||
// an abandoned waiter must not become a second initializer after the failure.
|
||||
f.wait_for_cached_reference(|cell| cell.has_changed().is_err())
|
||||
.await?;
|
||||
assert!(requests.try_recv().is_err(), "canceled caller retried");
|
||||
let reference = tokio::time::timeout(Duration::from_secs(5), f.prepare(&target))
|
||||
.await??
|
||||
.context("a new caller can retry the failed preparation")?;
|
||||
assert_eq!(requests.recv().await, Some(1));
|
||||
assert!(Arc::ptr_eq(
|
||||
&reference,
|
||||
&f.prepare(&target).await?.context("retry is cached")?
|
||||
));
|
||||
bundle_server.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cache_evicts_least_recently_used_bundles_without_invalidating_command_leases() -> Result<()>
|
||||
{
|
||||
if !isolated_bundle_test(
|
||||
"cache_evicts_least_recently_used_bundles_without_invalidating_command_leases",
|
||||
)? {
|
||||
return Ok(());
|
||||
}
|
||||
let f = Fixture::new().await?;
|
||||
let mut plugins = Vec::new();
|
||||
let mut targets = Vec::new();
|
||||
for index in 0..=MAX_CACHED_REFERENCES {
|
||||
let name = format!("plugin-{index}");
|
||||
let (plugin, target) = named_plugin(&f.server, &name)?;
|
||||
plugins.push(plugin);
|
||||
targets.push(target);
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/bundle/{name}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive(&name)?))
|
||||
.expect(if index == 1 { 2 } else { 1 })
|
||||
.mount(&f.server)
|
||||
.await;
|
||||
}
|
||||
catalog(&f.server, plugins).await;
|
||||
let mut leases = Vec::new();
|
||||
for target in &targets[..MAX_CACHED_REFERENCES] {
|
||||
leases.push(f.prepare(target).await?.context("initial reference")?);
|
||||
}
|
||||
// A concurrent warm reader must not make a completed entry unevictable.
|
||||
let completed_reader = Arc::clone(&f.cache.references.lock().await[1].1);
|
||||
assert!(Arc::ptr_eq(
|
||||
&leases[0],
|
||||
&f.prepare(&targets[0]).await?.context("recent reference")?
|
||||
));
|
||||
let extra = f
|
||||
.prepare(&targets[MAX_CACHED_REFERENCES])
|
||||
.await?
|
||||
.context("new plugin")?;
|
||||
let evicted_home = leases[1]
|
||||
.home
|
||||
.as_ref()
|
||||
.expect("reference store")
|
||||
.path()
|
||||
.to_owned();
|
||||
assert!(
|
||||
evicted_home.exists(),
|
||||
"command lease survives cache eviction"
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&leases[0],
|
||||
&f.prepare(&targets[0])
|
||||
.await?
|
||||
.context("retained recent reference")?
|
||||
));
|
||||
let replacement = f
|
||||
.prepare(&targets[1])
|
||||
.await?
|
||||
.context("evicted plugin reload")?;
|
||||
assert_ne!(
|
||||
replacement.home.as_ref().expect("reference store").path(),
|
||||
evicted_home
|
||||
);
|
||||
drop(completed_reader);
|
||||
drop(leases.remove(1));
|
||||
wait_until_removed(&evicted_home).await?;
|
||||
assert!(
|
||||
extra
|
||||
.home
|
||||
.as_ref()
|
||||
.expect("reference store")
|
||||
.path()
|
||||
.exists()
|
||||
);
|
||||
f.server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_the_cache_cancels_an_unused_download() -> Result<()> {
|
||||
if !isolated_bundle_test("dropping_the_cache_cancels_an_unused_download")? {
|
||||
return Ok(());
|
||||
}
|
||||
let f = Arc::new(Fixture::new().await?);
|
||||
let (target, _, _) = target(f.executor.path(), "1.0.0").await?;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let mut plugin = installed(&f.server, "1.0.0");
|
||||
plugin["release"]["bundle_download_url"] =
|
||||
json!(format!("http://{}/bundle", listener.local_addr()?));
|
||||
catalog(&f.server, vec![plugin]).await;
|
||||
let (requested, request) = tokio::sync::oneshot::channel();
|
||||
let download = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await?;
|
||||
let mut socket = tokio::io::BufReader::new(socket);
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
socket.read_line(&mut line).await?;
|
||||
if line == "\r\n" || line.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
requested.send(()).expect("test awaits bundle request");
|
||||
// Hold the response until cancellation closes the download connection.
|
||||
let mut remainder = Vec::new();
|
||||
socket.read_to_end(&mut remainder).await?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
let caller = tokio::spawn({
|
||||
let f = Arc::clone(&f);
|
||||
async move { f.prepare(&target).await }
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), request).await??;
|
||||
caller.abort();
|
||||
assert!(matches!(caller.await, Err(error) if error.is_cancelled()));
|
||||
drop(f);
|
||||
tokio::time::timeout(Duration::from_secs(5), download).await???;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_store_cleanup_runs_outside_the_async_worker() -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
let _ = started.send(());
|
||||
let _ = wait.recv();
|
||||
});
|
||||
ready.await?;
|
||||
let home = tempfile::tempdir()?;
|
||||
let path = home.path().to_owned();
|
||||
drop(PluginMeasurementReference {
|
||||
roots: TrustedPluginRoots::default(),
|
||||
home: Some(home),
|
||||
});
|
||||
assert!(path.exists(), "cleanup must wait for the blocking worker");
|
||||
release.send(())?;
|
||||
blocker.await?;
|
||||
wait_until_removed(&path).await
|
||||
})?;
|
||||
|
||||
// References may also outlive their runtime and still need ordinary cleanup.
|
||||
let home = tempfile::tempdir()?;
|
||||
let path = home.path().to_owned();
|
||||
drop(runtime);
|
||||
drop(PluginMeasurementReference {
|
||||
roots: TrustedPluginRoots::default(),
|
||||
home: Some(home),
|
||||
});
|
||||
assert!(!path.exists());
|
||||
Ok(())
|
||||
}
|
||||
158
codex-rs/core-plugins/src/plugin_metrics.rs
Normal file
158
codex-rs/core-plugins/src/plugin_metrics.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use crate::script_attribution::normalized_relative_script_path;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::items::is_safe_plugin_relative_path;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
|
||||
const ANALYTICS_MANIFEST_FILE: &str = "analytics.yaml";
|
||||
const MAX_ANALYTICS_MANIFEST_BYTES: u64 = 64 * 1024;
|
||||
const MAX_IDENTIFIER_LEN: usize = 64;
|
||||
const MAX_DIMENSIONS_PER_MEASUREMENT: usize = 8;
|
||||
|
||||
/// The manifest declaration for one numeric measurement.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginMeasurementDefinition {
|
||||
pub enum_dimensions: BTreeMap<String, BTreeSet<String>>,
|
||||
}
|
||||
|
||||
/// Custom metrics allowed for one trusted plugin script operation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginMetricsOperation {
|
||||
pub operation_name: String,
|
||||
pub measurements: BTreeMap<String, PluginMeasurementDefinition>,
|
||||
}
|
||||
|
||||
/// A metrics operation bound to identity from a fresh trusted command lookup.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedPluginMetricsOperation {
|
||||
pub plugin_id: PluginId,
|
||||
pub operation: PluginMetricsOperation,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AnalyticsManifest {
|
||||
version: u32,
|
||||
#[serde(with = "serde_with::rust::maps_duplicate_key_is_error")]
|
||||
operations: BTreeMap<String, OperationDeclaration>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OperationDeclaration {
|
||||
path: String,
|
||||
#[serde(with = "serde_with::rust::maps_duplicate_key_is_error")]
|
||||
measurements: BTreeMap<String, MeasurementDeclaration>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct MeasurementDeclaration {
|
||||
#[serde(default, with = "serde_with::rust::maps_duplicate_key_is_error")]
|
||||
dimensions: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_plugin_metrics_operations(
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
) -> Option<BTreeMap<String, PluginMetricsOperation>> {
|
||||
let manifest_path = plugin_root.join(ANALYTICS_MANIFEST_FILE);
|
||||
let canonical_manifest_path = manifest_path.canonicalize().ok()?;
|
||||
if canonical_manifest_path != manifest_path || !manifest_path.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut contents = Vec::new();
|
||||
File::open(manifest_path.as_path())
|
||||
.ok()?
|
||||
.take(MAX_ANALYTICS_MANIFEST_BYTES + 1)
|
||||
.read_to_end(&mut contents)
|
||||
.ok()?;
|
||||
if contents.len() as u64 > MAX_ANALYTICS_MANIFEST_BYTES {
|
||||
return None;
|
||||
}
|
||||
let manifest: AnalyticsManifest = serde_yaml::from_slice(&contents).ok()?;
|
||||
validate_manifest(manifest, plugin_root)
|
||||
}
|
||||
|
||||
fn validate_manifest(
|
||||
manifest: AnalyticsManifest,
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
) -> Option<BTreeMap<String, PluginMetricsOperation>> {
|
||||
if manifest.version != 1 || manifest.operations.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut operations_by_path = BTreeMap::new();
|
||||
for (operation_name, operation) in manifest.operations {
|
||||
if !valid_identifier(&operation_name) || operation.measurements.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let normalized_path = validated_operation_path(plugin_root, &operation.path)?;
|
||||
let mut measurements = BTreeMap::new();
|
||||
for (measurement_name, measurement) in operation.measurements {
|
||||
if !valid_identifier(&measurement_name)
|
||||
|| measurement.dimensions.len() > MAX_DIMENSIONS_PER_MEASUREMENT
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut enum_dimensions = BTreeMap::new();
|
||||
for (dimension_name, values) in measurement.dimensions {
|
||||
if !valid_identifier(&dimension_name) || values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let value_count = values.len();
|
||||
let values = values.into_iter().collect::<BTreeSet<_>>();
|
||||
if values.len() != value_count
|
||||
|| values.iter().any(|value| !valid_identifier(value))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
enum_dimensions.insert(dimension_name, values);
|
||||
}
|
||||
measurements.insert(
|
||||
measurement_name,
|
||||
PluginMeasurementDefinition { enum_dimensions },
|
||||
);
|
||||
}
|
||||
if operations_by_path
|
||||
.insert(
|
||||
normalized_path,
|
||||
PluginMetricsOperation {
|
||||
operation_name,
|
||||
measurements,
|
||||
},
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(operations_by_path)
|
||||
}
|
||||
|
||||
fn validated_operation_path(plugin_root: &AbsolutePathBuf, path: &str) -> Option<String> {
|
||||
let normalized_path = path.strip_prefix("./").unwrap_or(path);
|
||||
if !is_safe_plugin_relative_path(normalized_path) {
|
||||
return None;
|
||||
}
|
||||
let script = plugin_root.join(normalized_path).canonicalize().ok()?;
|
||||
if !script.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
let canonical_relative_path = script.as_path().strip_prefix(plugin_root.as_path()).ok()?;
|
||||
(normalized_relative_script_path(canonical_relative_path)?.as_str() == normalized_path)
|
||||
.then(|| normalized_path.to_string())
|
||||
}
|
||||
|
||||
fn valid_identifier(value: &str) -> bool {
|
||||
let mut chars = value.chars();
|
||||
matches!(chars.next(), Some('a'..='z'))
|
||||
&& value.len() <= MAX_IDENTIFIER_LEN
|
||||
&& chars.all(|character| {
|
||||
character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_'
|
||||
})
|
||||
}
|
||||
299
codex-rs/core-plugins/src/plugin_metrics_sidecar.rs
Normal file
299
codex-rs/core-plugins/src/plugin_metrics_sidecar.rs
Normal file
@@ -0,0 +1,299 @@
|
||||
use crate::ResolvedPluginMetricsOperation;
|
||||
use codex_analytics::PluginMeasurementRow;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::FileSystemReadStream;
|
||||
use codex_exec_server::RemoveOptions;
|
||||
use codex_exec_server::WriteFileOptions;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::FileSystemPermissions;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use futures::StreamExt;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::sync::Arc;
|
||||
use tempfile::NamedTempFile;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const PLUGIN_METRICS_OUTPUT_ENV_VAR: &str = "CODEX_PLUGIN_METRICS_OUTPUT";
|
||||
const MAX_OUTPUT_BYTES: u64 = 64 * 1024;
|
||||
const MAX_OUTPUT_ROWS: usize = 100;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct PluginMeasurementBatch {
|
||||
pub plugin_id: String,
|
||||
pub execution_id: String,
|
||||
pub operation: String,
|
||||
pub rows: Vec<PluginMeasurementRow>,
|
||||
}
|
||||
|
||||
pub struct PluginMetricsSidecar {
|
||||
output: PluginMetricsOutput,
|
||||
absolute_output_dir: AbsolutePathBuf,
|
||||
output_env_value: String,
|
||||
resolved: ResolvedPluginMetricsOperation,
|
||||
execution_id: String,
|
||||
}
|
||||
|
||||
enum PluginMetricsOutput {
|
||||
Local {
|
||||
file: NamedTempFile,
|
||||
_directory: tempfile::TempDir,
|
||||
},
|
||||
Remote {
|
||||
file_stream: tokio::sync::Mutex<FileSystemReadStream>,
|
||||
_directory: RemotePluginMetricsDirectory,
|
||||
},
|
||||
}
|
||||
|
||||
struct RemotePluginMetricsDirectory {
|
||||
filesystem: Arc<dyn ExecutorFileSystem>,
|
||||
path: PathUri,
|
||||
}
|
||||
|
||||
impl Drop for RemotePluginMetricsDirectory {
|
||||
fn drop(&mut self) {
|
||||
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
|
||||
return;
|
||||
};
|
||||
let filesystem = Arc::clone(&self.filesystem);
|
||||
let path = self.path.clone();
|
||||
runtime.spawn(async move {
|
||||
let _ = filesystem
|
||||
.remove(
|
||||
&path,
|
||||
RemoveOptions {
|
||||
recursive: true,
|
||||
force: true,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OutputEnvelope {
|
||||
version: u32,
|
||||
measurements: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OutputMeasurement {
|
||||
name: String,
|
||||
value: f64,
|
||||
#[serde(default)]
|
||||
dimensions: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl PluginMetricsSidecar {
|
||||
pub fn create(resolved: ResolvedPluginMetricsOperation) -> Option<Self> {
|
||||
let sidecar_dir = tempfile::Builder::new()
|
||||
.prefix("codex-plugin-metrics-")
|
||||
.tempdir()
|
||||
.ok()?;
|
||||
let output_file = tempfile::Builder::new()
|
||||
.prefix("measurements-")
|
||||
.suffix(".json")
|
||||
.tempfile_in(sidecar_dir.path())
|
||||
.ok()?;
|
||||
let absolute_output_dir = AbsolutePathBuf::from_absolute_path(sidecar_dir.path()).ok()?;
|
||||
let absolute_output_path = AbsolutePathBuf::from_absolute_path(output_file.path()).ok()?;
|
||||
let output_env_value = absolute_output_path.as_path().to_str()?.to_string();
|
||||
Some(Self {
|
||||
output: PluginMetricsOutput::Local {
|
||||
file: output_file,
|
||||
_directory: sidecar_dir,
|
||||
},
|
||||
absolute_output_dir,
|
||||
output_env_value,
|
||||
resolved,
|
||||
execution_id: Uuid::new_v4().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn create_remote(
|
||||
environment: &Environment,
|
||||
resolved: ResolvedPluginMetricsOperation,
|
||||
) -> Option<Self> {
|
||||
let temp_dir = environment.info().await.ok()?.temp_dir?;
|
||||
// Permission overlays still use host-native AbsolutePathBuf roots, so a
|
||||
// foreign executor path cannot be granted its exact sidecar directory.
|
||||
if !cfg!(unix) || temp_dir.infer_path_convention() != Some(PathConvention::Posix) {
|
||||
tracing::debug!(
|
||||
executor_temp_dir = %temp_dir,
|
||||
"plugin metrics require POSIX executor paths on a POSIX frontend"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let execution_id = Uuid::new_v4().to_string();
|
||||
let directory_path = temp_dir
|
||||
.join(&format!("codex-plugin-metrics-{execution_id}"))
|
||||
.ok()?;
|
||||
let absolute_output_dir = directory_path.to_abs_path().ok()?;
|
||||
let filesystem = environment.get_filesystem();
|
||||
filesystem
|
||||
.create_directory(
|
||||
&directory_path,
|
||||
CreateDirectoryOptions {
|
||||
recursive: false,
|
||||
follow_symlinks: true,
|
||||
},
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let directory = RemotePluginMetricsDirectory {
|
||||
filesystem,
|
||||
path: directory_path,
|
||||
};
|
||||
let output_path = directory.path.join("measurements.json").ok()?;
|
||||
directory
|
||||
.filesystem
|
||||
.write_file(
|
||||
&output_path,
|
||||
Vec::new(),
|
||||
WriteFileOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let file_stream = directory
|
||||
.filesystem
|
||||
.read_file_stream(&output_path, /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
Some(Self {
|
||||
output: PluginMetricsOutput::Remote {
|
||||
file_stream: tokio::sync::Mutex::new(file_stream),
|
||||
_directory: directory,
|
||||
},
|
||||
absolute_output_dir,
|
||||
output_env_value: output_path.inferred_native_path_string(),
|
||||
resolved,
|
||||
execution_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn install_output_env(&self, env: &mut HashMap<String, String>) {
|
||||
env.insert(
|
||||
PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(),
|
||||
self.output_env_value.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn absolute_output_path(&self) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(&self.output_env_value).expect("absolute output path")
|
||||
}
|
||||
|
||||
pub fn additional_permissions(&self) -> AdditionalPermissionProfile {
|
||||
AdditionalPermissionProfile {
|
||||
file_system: Some(FileSystemPermissions::from_read_write_roots(
|
||||
/*read*/ None,
|
||||
/*write*/ Some(vec![self.absolute_output_dir.clone()]),
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn finish(mut self, exit_code: i32) -> Option<PluginMeasurementBatch> {
|
||||
if exit_code != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
match &mut self.output {
|
||||
PluginMetricsOutput::Local { file, .. } => {
|
||||
let output_file = file.as_file_mut();
|
||||
output_file.seek(SeekFrom::Start(0)).ok()?;
|
||||
output_file
|
||||
.take(MAX_OUTPUT_BYTES + 1)
|
||||
.read_to_end(&mut contents)
|
||||
.ok()?;
|
||||
}
|
||||
PluginMetricsOutput::Remote { file_stream, .. } => {
|
||||
let file_stream = file_stream.get_mut();
|
||||
while let Some(chunk) = file_stream.next().await {
|
||||
let chunk = chunk.ok()?;
|
||||
if contents.len().saturating_add(chunk.len()) > MAX_OUTPUT_BYTES as usize {
|
||||
return None;
|
||||
}
|
||||
contents.extend_from_slice(&chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
let rows = parse_output(&contents, &self.resolved)?;
|
||||
(!rows.is_empty()).then(|| PluginMeasurementBatch {
|
||||
plugin_id: self.resolved.plugin_id.as_key(),
|
||||
execution_id: self.execution_id,
|
||||
operation: self.resolved.operation.operation_name,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn strip_output_env(env: &mut HashMap<String, String>) {
|
||||
if cfg!(windows) {
|
||||
env.retain(|key, _| !key.eq_ignore_ascii_case(PLUGIN_METRICS_OUTPUT_ENV_VAR));
|
||||
} else {
|
||||
env.remove(PLUGIN_METRICS_OUTPUT_ENV_VAR);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_output(
|
||||
contents: &[u8],
|
||||
resolved: &ResolvedPluginMetricsOperation,
|
||||
) -> Option<Vec<PluginMeasurementRow>> {
|
||||
if contents.len() as u64 > MAX_OUTPUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
let output: OutputEnvelope = serde_json::from_slice(contents).ok()?;
|
||||
if output.version != 1 || output.measurements.len() > MAX_OUTPUT_ROWS {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut rows = Vec::new();
|
||||
for value in output.measurements {
|
||||
let Ok(measurement) = serde_json::from_value::<OutputMeasurement>(value) else {
|
||||
continue;
|
||||
};
|
||||
let Some(definition) = resolved.operation.measurements.get(&measurement.name) else {
|
||||
continue;
|
||||
};
|
||||
if !measurement.value.is_finite()
|
||||
|| measurement.dimensions.len() != definition.enum_dimensions.len()
|
||||
|| !definition.enum_dimensions.iter().all(|(name, allowed)| {
|
||||
measurement
|
||||
.dimensions
|
||||
.get(name)
|
||||
.is_some_and(|value| allowed.contains(value))
|
||||
})
|
||||
|| !seen.insert((measurement.name.clone(), measurement.dimensions.clone()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
rows.push(PluginMeasurementRow {
|
||||
measurement_name: measurement.name,
|
||||
number_value: measurement.value,
|
||||
dimensions: measurement.dimensions,
|
||||
});
|
||||
}
|
||||
Some(rows)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_metrics_sidecar_tests.rs"]
|
||||
mod tests;
|
||||
195
codex-rs/core-plugins/src/plugin_metrics_sidecar_tests.rs
Normal file
195
codex-rs/core-plugins/src/plugin_metrics_sidecar_tests.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
use super::*;
|
||||
use crate::PluginMeasurementDefinition;
|
||||
use crate::PluginMetricsOperation;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::models::LegacyReadWriteRoots;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn create_sidecar() -> PluginMetricsSidecar {
|
||||
PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecar_is_created_in_system_temp_with_private_permissions() {
|
||||
let output_dir =
|
||||
AbsolutePathBuf::from_absolute_path(std::env::temp_dir()).expect("absolute temp directory");
|
||||
let sidecar = PluginMetricsSidecar::create(resolved_operation()).expect("create sidecar");
|
||||
|
||||
assert_eq!(
|
||||
sidecar.absolute_output_path().parent(),
|
||||
Some(sidecar.absolute_output_dir.clone())
|
||||
);
|
||||
assert_eq!(sidecar.absolute_output_dir.parent(), Some(output_dir));
|
||||
assert!(sidecar.absolute_output_dir.as_path().is_dir());
|
||||
let roots = sidecar
|
||||
.additional_permissions()
|
||||
.file_system
|
||||
.expect("file system permissions")
|
||||
.legacy_read_write_roots()
|
||||
.expect("legacy roots");
|
||||
assert_eq!(
|
||||
roots,
|
||||
LegacyReadWriteRoots {
|
||||
read: None,
|
||||
write: Some(vec![sidecar.absolute_output_dir]),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn resolved_operation() -> ResolvedPluginMetricsOperation {
|
||||
ResolvedPluginMetricsOperation {
|
||||
plugin_id: PluginId::parse("security@openai-curated").expect("valid plugin id"),
|
||||
operation: PluginMetricsOperation {
|
||||
operation_name: "security_scan".to_string(),
|
||||
measurements: BTreeMap::from([
|
||||
(
|
||||
"finding_count".to_string(),
|
||||
PluginMeasurementDefinition {
|
||||
enum_dimensions: BTreeMap::from([(
|
||||
"severity".to_string(),
|
||||
BTreeSet::from(["high".to_string(), "low".to_string()]),
|
||||
)]),
|
||||
},
|
||||
),
|
||||
(
|
||||
"files_scanned".to_string(),
|
||||
PluginMeasurementDefinition {
|
||||
enum_dimensions: BTreeMap::new(),
|
||||
},
|
||||
),
|
||||
]),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sidecar_keeps_valid_rows_and_first_duplicate_then_cleans_up() {
|
||||
let sidecar = create_sidecar();
|
||||
let path = sidecar.absolute_output_path();
|
||||
std::fs::write(
|
||||
path.as_path(),
|
||||
json!({
|
||||
"version": 1,
|
||||
"measurements": [
|
||||
{"name": "finding_count", "value": 3, "dimensions": {"severity": "high"}},
|
||||
{"name": "unknown", "value": 1},
|
||||
{"name": "finding_count", "value": 4},
|
||||
{"name": "finding_count", "value": 5, "dimensions": {"severity": "critical"}},
|
||||
{"name": "finding_count", "value": 6, "dimensions": {"severity": "high", "extra": "x"}},
|
||||
{"name": "finding_count", "value": 99, "dimensions": {"severity": "high"}},
|
||||
{"name": "files_scanned", "value": 17},
|
||||
{"name": "files_scanned", "value": "not-a-number"},
|
||||
{"name": "files_scanned", "value": 18, "unknown": true}
|
||||
]
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("write output");
|
||||
|
||||
let batch = sidecar
|
||||
.finish(/*exit_code*/ 0)
|
||||
.await
|
||||
.expect("valid measurements");
|
||||
let execution_id = batch.execution_id.clone();
|
||||
assert_eq!(
|
||||
batch,
|
||||
PluginMeasurementBatch {
|
||||
plugin_id: "security@openai-curated".to_string(),
|
||||
execution_id: execution_id.clone(),
|
||||
operation: "security_scan".to_string(),
|
||||
rows: vec![
|
||||
PluginMeasurementRow {
|
||||
measurement_name: "finding_count".to_string(),
|
||||
number_value: 3.0,
|
||||
dimensions: BTreeMap::from([("severity".to_string(), "high".to_string(),)]),
|
||||
},
|
||||
PluginMeasurementRow {
|
||||
measurement_name: "files_scanned".to_string(),
|
||||
number_value: 17.0,
|
||||
dimensions: BTreeMap::new(),
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
Uuid::parse_str(&execution_id)
|
||||
.expect("execution id UUID")
|
||||
.get_version(),
|
||||
Some(uuid::Version::Random)
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn malformed_oversized_and_nonzero_outputs_are_ignored_and_cleaned_up() {
|
||||
for output in [
|
||||
r#"{"version":2,"measurements":[]}"#.as_bytes().to_vec(),
|
||||
r#"{"version":1,"measurements":[],"unknown":true}"#.as_bytes().to_vec(),
|
||||
json!({
|
||||
"version": 1,
|
||||
"measurements": vec![json!({"name": "files_scanned", "value": 1}); MAX_OUTPUT_ROWS + 1]
|
||||
})
|
||||
.to_string()
|
||||
.into_bytes(),
|
||||
vec![b' '; MAX_OUTPUT_BYTES as usize + 1],
|
||||
] {
|
||||
let sidecar = create_sidecar();
|
||||
let path = sidecar.absolute_output_path();
|
||||
std::fs::write(path.as_path(), output).expect("write output");
|
||||
assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
let sidecar = create_sidecar();
|
||||
let path = sidecar.absolute_output_path();
|
||||
std::fs::write(
|
||||
path.as_path(),
|
||||
r#"{"version":1,"measurements":[{"name":"files_scanned","value":1}]}"#,
|
||||
)
|
||||
.expect("write output");
|
||||
assert_eq!(sidecar.finish(/*exit_code*/ 1).await, None);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_output_env_is_absent_without_sidecar_and_cannot_be_overridden() {
|
||||
let mut env = HashMap::from([
|
||||
(
|
||||
PLUGIN_METRICS_OUTPUT_ENV_VAR.to_string(),
|
||||
"/user/path".to_string(),
|
||||
),
|
||||
("KEEP".to_string(), "value".to_string()),
|
||||
]);
|
||||
strip_output_env(&mut env);
|
||||
assert_eq!(
|
||||
env,
|
||||
HashMap::from([("KEEP".to_string(), "value".to_string())])
|
||||
);
|
||||
|
||||
let sidecar = create_sidecar();
|
||||
let path = sidecar.absolute_output_path();
|
||||
sidecar.install_output_env(&mut env);
|
||||
assert_eq!(
|
||||
env.get(PLUGIN_METRICS_OUTPUT_ENV_VAR).map(String::as_str),
|
||||
path.as_path().to_str()
|
||||
);
|
||||
drop(sidecar);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn sidecar_reads_the_original_file_after_path_replacement() {
|
||||
let sidecar = create_sidecar();
|
||||
let path = sidecar.absolute_output_path();
|
||||
std::fs::remove_file(path.as_path()).expect("remove original output path");
|
||||
std::fs::write(
|
||||
path.as_path(),
|
||||
r#"{"version":1,"measurements":[{"name":"files_scanned","value":99}]}"#,
|
||||
)
|
||||
.expect("write replacement output");
|
||||
|
||||
assert_eq!(sidecar.finish(/*exit_code*/ 0).await, None);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
132
codex-rs/core-plugins/src/plugins_config_input_tests.rs
Normal file
132
codex-rs/core-plugins/src/plugins_config_input_tests.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
//! Verify connection reuse without retaining request metadata or crossing config lifetimes.
|
||||
|
||||
use super::PluginsConfigInput;
|
||||
use crate::remote::fetch_recommended_plugins;
|
||||
use crate::test_support::test_http_client_factory;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_login::CodexAuth;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[test]
|
||||
fn repeated_service_configs_and_early_clones_share_one_lazy_pool() {
|
||||
let input = PluginsConfigInput::new(
|
||||
ConfigLayerStack::default(),
|
||||
Default::default(),
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ true,
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let clone = input.clone();
|
||||
assert!(input.remote_http_clients.get().is_none());
|
||||
let first = input.remote_plugin_service_config(/*runtime_auth*/ None);
|
||||
let reuse: Vec<_> = (0..220)
|
||||
.map(|_| {
|
||||
Arc::ptr_eq(
|
||||
&first.http_clients,
|
||||
&clone
|
||||
.remote_plugin_service_config(/*runtime_auth*/ None)
|
||||
.http_clients,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let new_input = PluginsConfigInput::new(
|
||||
input.config_layer_stack.clone(),
|
||||
input.plugins.clone(),
|
||||
input.model_provider_id.clone(),
|
||||
input.plugins_enabled,
|
||||
input.remote_plugin_enabled,
|
||||
input.chatgpt_base_url.clone(),
|
||||
input.http_client_factory.clone(),
|
||||
input.product_sku,
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
reuse,
|
||||
Arc::ptr_eq(
|
||||
&first.http_clients,
|
||||
&new_input
|
||||
.remote_plugin_service_config(/*runtime_auth*/ None)
|
||||
.http_clients,
|
||||
),
|
||||
),
|
||||
(vec![true; 220], false)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reused_pool_uses_current_endpoint_product_and_authentication() {
|
||||
let first_server = MockServer::start().await;
|
||||
let second_server = MockServer::start().await;
|
||||
for (server, token, account, product_sku) in [
|
||||
(&first_server, "header.e30.first", "first-account", "codex"),
|
||||
(
|
||||
&second_server,
|
||||
"header.e30.second",
|
||||
"second-account",
|
||||
"updated",
|
||||
),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/suggested/codex"))
|
||||
.and(header("authorization", format!("Bearer {token}")))
|
||||
.and(header("chatgpt-account-id", account))
|
||||
.and(header("oai-product-sku", product_sku))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"enabled": true,
|
||||
"plugins": [],
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
let mut input = PluginsConfigInput::new(
|
||||
ConfigLayerStack::default(),
|
||||
Default::default(),
|
||||
"openai".to_string(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ true,
|
||||
format!("{}/backend-api", first_server.uri()),
|
||||
test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let first = input.remote_plugin_service_config(/*runtime_auth*/ None);
|
||||
let first_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.first",
|
||||
"first-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let first_result = fetch_recommended_plugins(&first, Some(&first_auth))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
input.chatgpt_base_url = format!("{}/backend-api", second_server.uri());
|
||||
input.product_sku = Some("updated".to_string());
|
||||
let second = input.remote_plugin_service_config(/*runtime_auth*/ None);
|
||||
let second_auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.second",
|
||||
"second-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let second_result = fetch_recommended_plugins(&second, Some(&second_auth))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
first_result,
|
||||
Arc::ptr_eq(&first.http_clients, &second.http_clients),
|
||||
),
|
||||
(second_result, true)
|
||||
);
|
||||
}
|
||||
46
codex-rs/core-plugins/src/provider.rs
Normal file
46
codex-rs/core-plugins/src/provider.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
//! Plugin catalog listing interface and source inputs used to request snapshots.
|
||||
|
||||
use crate::ExecutorPluginProviderError;
|
||||
use crate::PluginCatalog;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Identifiers, MCP client, and executor inventories used to request one catalog snapshot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PluginListQuery {
|
||||
pub thread_id: String,
|
||||
pub turn_id: String,
|
||||
pub mcp_resources: Option<Arc<McpResourceClient>>,
|
||||
/// Already-acquired V2 inventories; empty for cloud listing.
|
||||
pub snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
|
||||
}
|
||||
|
||||
/// Failure to list plugin metadata.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PluginProviderError {
|
||||
#[error(transparent)]
|
||||
Executor(#[from] ExecutorPluginProviderError),
|
||||
#[error("{0}")]
|
||||
Message(String),
|
||||
}
|
||||
|
||||
pub type PluginProviderResult<T> = Result<T, PluginProviderError>;
|
||||
|
||||
pub type PluginProviderFuture<'a, T> =
|
||||
Pin<Box<dyn Future<Output = PluginProviderResult<T>> + Send + 'a>>;
|
||||
|
||||
/// Lists plugin metadata without resolving packages or binding filesystems.
|
||||
///
|
||||
/// Cloud providers implement `list`; executor listing is not yet supported.
|
||||
/// Package access uses [`crate::ExecutorPluginProvider::resolve_bound`] directly.
|
||||
pub trait PluginProvider: Send + Sync {
|
||||
/// Returns a snapshot; on error, callers retain the previous snapshot.
|
||||
/// Providers set `is_partial` when listing omits entries; warnings are diagnostic only.
|
||||
fn list(&self, _query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
Box::pin(async { Ok(PluginCatalog::default()) })
|
||||
}
|
||||
}
|
||||
28
codex-rs/core-plugins/src/recommended_plugin_install.rs
Normal file
28
codex-rs/core-plugins/src/recommended_plugin_install.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use crate::remote::RemotePluginCatalogError;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_tools::DiscoverableTool;
|
||||
|
||||
pub async fn hydrate_selected_recommended_plugin_install_metadata(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
mut tool: DiscoverableTool,
|
||||
) -> Result<Option<DiscoverableTool>, RemotePluginCatalogError> {
|
||||
let DiscoverableTool::Plugin(plugin) = &mut tool else {
|
||||
return Ok(Some(tool));
|
||||
};
|
||||
let remote_plugin_id = plugin.remote_plugin_id.clone().ok_or_else(|| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"recommended plugin `{}` is missing remote plugin identity",
|
||||
plugin.id
|
||||
))
|
||||
})?;
|
||||
let Some(app_connector_ids) =
|
||||
crate::remote::fetch_recommended_plugin_install_metadata(config, auth, &remote_plugin_id)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
plugin.app_connector_ids = app_connector_ids;
|
||||
Ok(Some(tool))
|
||||
}
|
||||
2515
codex-rs/core-plugins/src/remote.rs
Normal file
2515
codex-rs/core-plugins/src/remote.rs
Normal file
File diff suppressed because it is too large
Load Diff
335
codex-rs/core-plugins/src/remote/catalog_cache.rs
Normal file
335
codex-rs/core-plugins/src/remote/catalog_cache.rs
Normal file
@@ -0,0 +1,335 @@
|
||||
use super::RemotePluginCatalogCacheMode;
|
||||
use super::RemotePluginDirectoryItem;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_login::CodexAuth;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::de::IgnoredAny;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::SeqAccess;
|
||||
use serde::de::Visitor;
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tracing::warn;
|
||||
|
||||
// `plugin/list` and other callers that assume all plugins are available locally will be
|
||||
// deprecated soon. Remove this catalog cache when those callers migrate to on-demand fetching.
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION: u8 = 1;
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR: &str = "cache/remote_plugin_catalog";
|
||||
const REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL: Duration = Duration::from_secs(60 * 60 * 3);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: String,
|
||||
account_id: Option<String>,
|
||||
chatgpt_user_id: Option<String>,
|
||||
is_workspace_account: bool,
|
||||
// Global catalogs predate scoped cache keys and must keep their existing filenames.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
scope: Option<RemotePluginScope>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
collection: Option<String>,
|
||||
}
|
||||
|
||||
impl RemotePluginCatalogCacheKey {
|
||||
fn new(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) -> Option<Self> {
|
||||
let cache_key = Self {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
account_id: auth.get_account_id(),
|
||||
chatgpt_user_id: auth.get_chatgpt_user_id(),
|
||||
is_workspace_account: auth.is_workspace_account(),
|
||||
scope: (scope != RemotePluginScope::Global).then_some(scope),
|
||||
collection: collection.map(str::to_owned),
|
||||
};
|
||||
// Preserve global catalog caching for existing header-auth clients, but never share
|
||||
// user or workspace catalogs when the auth mode cannot identify their owner.
|
||||
if !matches!(scope, RemotePluginScope::Global)
|
||||
&& cache_key.account_id.is_none()
|
||||
&& cache_key.chatgpt_user_id.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(cache_key)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RemotePluginCatalogDiskCache<Plugins> {
|
||||
schema_version: u8,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
plugins: Plugins,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RemotePluginCatalogCacheFreshness {
|
||||
Fresh,
|
||||
Stale,
|
||||
}
|
||||
|
||||
pub(super) struct CachedDirectoryPlugins<T> {
|
||||
pub plugins: Vec<T>,
|
||||
pub freshness: RemotePluginCatalogCacheFreshness,
|
||||
}
|
||||
|
||||
pub(super) fn has_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> bool {
|
||||
// Ignore each entry so Serde still requires `plugins` to be an array.
|
||||
load_cached_directory_plugins::<IgnoredAny>(
|
||||
codex_home, config, auth, scope, /*collection*/ None, cache_mode,
|
||||
)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
pub(super) fn load_cached_directory_plugins<T: DeserializeOwned>(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> Option<CachedDirectoryPlugins<T>> {
|
||||
if cache_mode == RemotePluginCatalogCacheMode::ForceRefetch {
|
||||
return None;
|
||||
}
|
||||
let cache_key = RemotePluginCatalogCacheKey::new(config, auth, scope, collection)?;
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let bytes = match read_catalog_bytes(&cache_path, cache_mode) {
|
||||
Ok(bytes) => bytes?,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to read remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let cache: RemotePluginCatalogDiskCache<Vec<T>> = match serde_json::from_slice(&bytes) {
|
||||
Ok(cache) => cache,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to parse remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if cache.schema_version != REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION {
|
||||
let _ = std::fs::remove_file(cache_path);
|
||||
return None;
|
||||
}
|
||||
|
||||
let freshness = if is_fresh(cache.fetched_at, Utc::now()) {
|
||||
RemotePluginCatalogCacheFreshness::Fresh
|
||||
} else if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
return None;
|
||||
} else {
|
||||
RemotePluginCatalogCacheFreshness::Stale
|
||||
};
|
||||
Some(CachedDirectoryPlugins {
|
||||
plugins: cache.plugins,
|
||||
freshness,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_catalog_bytes(
|
||||
path: &Path,
|
||||
cache_mode: RemotePluginCatalogCacheMode,
|
||||
) -> io::Result<Option<Vec<u8>>> {
|
||||
let mut file = File::open(path)?;
|
||||
let mut bytes = Vec::new();
|
||||
if cache_mode == RemotePluginCatalogCacheMode::PreferFreshCache {
|
||||
const PREFIX_LEN: usize = 256;
|
||||
bytes.reserve_exact(PREFIX_LEN);
|
||||
file.by_ref()
|
||||
.take(PREFIX_LEN as u64)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes.len() < PREFIX_LEN {
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
if CatalogHeader::is_stale_prefix(&bytes, Utc::now()) {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
file.read_to_end(&mut bytes)?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CatalogHeader {
|
||||
schema_version: Option<u8>,
|
||||
fetched_at: Option<DateTime<Utc>>,
|
||||
metadata_before_plugins: bool,
|
||||
}
|
||||
|
||||
impl CatalogHeader {
|
||||
fn is_stale_prefix(bytes: &[u8], now: DateTime<Utc>) -> bool {
|
||||
let mut header = Self::default();
|
||||
let mut json = serde_json::Deserializer::from_slice(bytes);
|
||||
// A bounded read can end inside the payload. Only fully decoded fields count.
|
||||
let parsed = json.deserialize_map(&mut header).and_then(|()| json.end());
|
||||
if parsed.is_err_and(|err| !err.is_eof()) {
|
||||
return false;
|
||||
}
|
||||
header.metadata_before_plugins && !is_fresh(header.fetched_at, now)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the `plugins` field uses the seed. Serde calls `visit_seq` when it enters
|
||||
// that array, so a missing or wrongly typed payload still goes through the full reader.
|
||||
impl<'de> DeserializeSeed<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<(), D::Error> {
|
||||
deserializer.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for &mut CatalogHeader {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a plugin catalog object or its plugins array")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier, rename_all = "snake_case")]
|
||||
enum Field {
|
||||
SchemaVersion,
|
||||
FetchedAt,
|
||||
Plugins,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
|
||||
let mut saw_plugins = false;
|
||||
while let Some(field) = map.next_key()? {
|
||||
match field {
|
||||
Field::SchemaVersion if self.schema_version.is_none() => {
|
||||
self.schema_version = Some(map.next_value()?);
|
||||
}
|
||||
Field::FetchedAt if self.fetched_at.is_none() => {
|
||||
self.fetched_at = Some(map.next_value()?);
|
||||
}
|
||||
Field::Plugins if !saw_plugins => {
|
||||
saw_plugins = true;
|
||||
map.next_value_seed(&mut *self)?;
|
||||
}
|
||||
Field::SchemaVersion => {
|
||||
return Err(serde::de::Error::duplicate_field("schema_version"));
|
||||
}
|
||||
Field::FetchedAt => return Err(serde::de::Error::duplicate_field("fetched_at")),
|
||||
Field::Plugins => return Err(serde::de::Error::duplicate_field("plugins")),
|
||||
Field::Other => {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut plugins: A) -> Result<(), A::Error> {
|
||||
self.metadata_before_plugins = self.schema_version
|
||||
== Some(REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION)
|
||||
&& self.fetched_at.is_some();
|
||||
while plugins.next_element::<IgnoredAny>()?.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
plugins: &[RemotePluginDirectoryItem],
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
let Ok(contents) = serde_json::to_string_pretty(&RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let _ = codex_utils_path::write_atomically(&cache_path, &contents);
|
||||
}
|
||||
|
||||
pub(crate) fn remove_cached_directory_plugins(
|
||||
codex_home: &Path,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
scope: RemotePluginScope,
|
||||
collection: Option<&str>,
|
||||
) {
|
||||
let Some(cache_key) = RemotePluginCatalogCacheKey::new(config, auth, scope, collection) else {
|
||||
return;
|
||||
};
|
||||
let cache_path = cache_path(codex_home, &cache_key);
|
||||
match std::fs::remove_file(&cache_path) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cache_path = %cache_path.display(),
|
||||
"failed to remove remote plugin catalog disk cache: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_path(codex_home: &Path, cache_key: &RemotePluginCatalogCacheKey) -> PathBuf {
|
||||
let cache_key_json = serde_json::to_vec(cache_key).unwrap_or_default();
|
||||
let mut cache_key_hash = 0xcbf29ce484222325_u64;
|
||||
for byte in cache_key_json {
|
||||
cache_key_hash ^= u64::from(byte);
|
||||
cache_key_hash = cache_key_hash.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
codex_home
|
||||
.join(REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR)
|
||||
.join(format!("{cache_key_hash:016x}.json"))
|
||||
}
|
||||
|
||||
fn is_fresh(fetched_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
|
||||
let Some(fetched_at) = fetched_at else {
|
||||
return false;
|
||||
};
|
||||
let Ok(ttl) = chrono::Duration::from_std(REMOTE_PLUGIN_CATALOG_DISK_CACHE_TTL) else {
|
||||
return false;
|
||||
};
|
||||
let age = now.signed_duration_since(fetched_at);
|
||||
age >= chrono::Duration::zero() && age <= ttl
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "catalog_cache_tests.rs"]
|
||||
mod tests;
|
||||
246
codex-rs/core-plugins/src/remote/catalog_cache_tests.rs
Normal file
246
codex-rs/core-plugins/src/remote/catalog_cache_tests.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
use super::*;
|
||||
use chrono::TimeDelta;
|
||||
use codex_login::AuthHeaders;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_freshness_honors_ttl() {
|
||||
let now = Utc::now();
|
||||
|
||||
assert!(!is_fresh(/*fetched_at*/ None, now));
|
||||
assert!(is_fresh(Some(now), now));
|
||||
assert!(is_fresh(Some(now - TimeDelta::hours(3)), now,));
|
||||
assert!(!is_fresh(
|
||||
Some(now - TimeDelta::hours(3) - TimeDelta::milliseconds(1)),
|
||||
now,
|
||||
));
|
||||
assert!(!is_fresh(Some(now + TimeDelta::milliseconds(1)), now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_cache_paths_are_isolated_by_scope_and_collection() {
|
||||
let codex_home = Path::new("/tmp/codex-home");
|
||||
let cache_key_for_scope = |scope| RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
account_id: Some("account-id".to_string()),
|
||||
chatgpt_user_id: Some("user-id".to_string()),
|
||||
is_workspace_account: true,
|
||||
scope: (scope != RemotePluginScope::Global).then_some(scope),
|
||||
collection: None,
|
||||
};
|
||||
|
||||
let paths = [
|
||||
RemotePluginScope::Global,
|
||||
RemotePluginScope::User,
|
||||
RemotePluginScope::Workspace,
|
||||
]
|
||||
.map(|scope| cache_path(codex_home, &cache_key_for_scope(scope)));
|
||||
|
||||
assert_ne!(paths[0], paths[1]);
|
||||
assert_ne!(paths[0], paths[2]);
|
||||
assert_ne!(paths[1], paths[2]);
|
||||
|
||||
let mut collection_key = cache_key_for_scope(RemotePluginScope::Global);
|
||||
collection_key.collection = Some("vertical".to_string());
|
||||
assert!(!paths.contains(&cache_path(codex_home, &collection_key)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_catalog_cache_reuses_legacy_cache_file() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
let legacy_cache_path = codex_home
|
||||
.path()
|
||||
.join(REMOTE_PLUGIN_CATALOG_DISK_CACHE_DIR)
|
||||
.join("f22564d6f8ca89f6.json");
|
||||
let legacy_cache = serde_json::json!({
|
||||
"schema_version": REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
"plugins": [],
|
||||
});
|
||||
codex_utils_path::write_atomically(&legacy_cache_path, &legacy_cache.to_string())
|
||||
.expect("write legacy cache");
|
||||
|
||||
let cached = load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.expect("load legacy global cache");
|
||||
assert!(cached.plugins.is_empty());
|
||||
assert_eq!(cached.freshness, RemotePluginCatalogCacheFreshness::Stale);
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(has_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
RemotePluginCatalogCacheMode::PreferFreshCache,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freshness_probe_defers_plugin_validation_until_full_read() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
let scope = RemotePluginScope::Global;
|
||||
let key = RemotePluginCatalogCacheKey::new(&config, &auth, scope, /*collection*/ None)
|
||||
.expect("global cache key");
|
||||
let path = cache_path(codex_home.path(), &key);
|
||||
let probe = |mode| has_cached_directory_plugins(codex_home.path(), &config, &auth, scope, mode);
|
||||
let version = REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION;
|
||||
let now = serde_json::to_string(&Utc::now()).expect("serialize timestamp");
|
||||
let expired_at = "2000-01-01T00:00:00Z";
|
||||
let padding = " ".repeat(512);
|
||||
for contents in [
|
||||
serde_json::json!({"schema_version": version + 1, "plugins": []}).to_string(),
|
||||
serde_json::json!({"schema_version": version}).to_string(),
|
||||
serde_json::json!({"schema_version": version, "plugins": {}}).to_string(),
|
||||
format!(r#"{{"schema_version":{version},"plugins":[{{"#),
|
||||
format!(r#"{{"schema_version":{version},"fetched_at":{now},"plugins":[{padding}"#),
|
||||
format!(
|
||||
r#"{{"details":{{"fetched_at":"{expired_at}"}},"schema_version":{version},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","fetched_at":{now},"plugins":[{padding}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"schema_version":{version},"fetched_at":"{expired_at}","plugins":{{}}}}{padding}"#
|
||||
),
|
||||
] {
|
||||
codex_utils_path::write_atomically(&path, &contents).expect("write invalid cache");
|
||||
assert!(
|
||||
!probe(RemotePluginCatalogCacheMode::PreferFreshCache),
|
||||
"{contents}"
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
let expired = format!(
|
||||
r#"{{"note":"[","fetched\u005fat":"{expired_at}","schema_version":{version},"plugins":[{padding}"#
|
||||
);
|
||||
codex_utils_path::write_atomically(&path, &expired).expect("write expired cache");
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(path.exists());
|
||||
assert!(!probe(RemotePluginCatalogCacheMode::PreferCache));
|
||||
assert!(!path.exists());
|
||||
|
||||
let reordered =
|
||||
format!(r#"{{"plugins":[{padding}],"schema_version":{version},"fetched_at":{now}}}"#);
|
||||
codex_utils_path::write_atomically(&path, &reordered).expect("write reordered cache");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
|
||||
let contents = serde_json::json!({
|
||||
"schema_version": version,
|
||||
"fetched_at": Utc::now(),
|
||||
"plugins": [{}],
|
||||
});
|
||||
codex_utils_path::write_atomically(&path, &contents.to_string()).expect("write invalid plugin");
|
||||
assert!(probe(RemotePluginCatalogCacheMode::PreferFreshCache));
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_auth_does_not_cache_private_catalogs_without_a_stable_identity() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
"https://chatgpt.com/backend-api".to_string(),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new()));
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
|
||||
for scope in [RemotePluginScope::User, RemotePluginScope::Workspace] {
|
||||
let insecure_cache_key = RemotePluginCatalogCacheKey {
|
||||
chatgpt_base_url: config.chatgpt_base_url.clone(),
|
||||
account_id: None,
|
||||
chatgpt_user_id: None,
|
||||
is_workspace_account: false,
|
||||
scope: Some(scope),
|
||||
collection: None,
|
||||
};
|
||||
let insecure_cache_path = cache_path(codex_home.path(), &insecure_cache_key);
|
||||
|
||||
write_cached_directory_plugins(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
&[],
|
||||
);
|
||||
assert!(!insecure_cache_path.exists());
|
||||
|
||||
let insecure_cache = RemotePluginCatalogDiskCache {
|
||||
schema_version: REMOTE_PLUGIN_CATALOG_DISK_CACHE_SCHEMA_VERSION,
|
||||
fetched_at: Some(Utc::now()),
|
||||
plugins: Vec::<RemotePluginDirectoryItem>::new(),
|
||||
};
|
||||
let contents = serde_json::to_string_pretty(&insecure_cache).expect("serialize cache");
|
||||
codex_utils_path::write_atomically(&insecure_cache_path, &contents)
|
||||
.expect("write insecure cache");
|
||||
|
||||
assert!(
|
||||
load_cached_directory_plugins::<RemotePluginDirectoryItem>(
|
||||
codex_home.path(),
|
||||
&config,
|
||||
&auth,
|
||||
scope,
|
||||
/*collection*/ None,
|
||||
RemotePluginCatalogCacheMode::PreferCache,
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
64
codex-rs/core-plugins/src/remote/plugin_capabilities.rs
Normal file
64
codex-rs/core-plugins/src/remote/plugin_capabilities.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
//! Discovers best-effort runtime invalidation hints from locally cached plugin bundles.
|
||||
//!
|
||||
//! Discovery ignores runtime policy and does not prepare runtime directories. Repeated inclusion
|
||||
//! unions old and new declarations for updates; removals capture declarations before deletion.
|
||||
|
||||
use crate::loader::load_plugin_apps_from_manifest;
|
||||
use crate::loader::load_plugin_hooks;
|
||||
use crate::loader::load_plugin_mcp_servers_from_manifest_with_format;
|
||||
use crate::loader::plugin_skill_roots;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::store::PluginStore;
|
||||
use codex_hooks::plugin_hook_declarations;
|
||||
use codex_plugin::PluginId;
|
||||
|
||||
/// Runtime categories affected by a plugin change, before runtime policy filtering.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RemotePluginCapabilities {
|
||||
pub has_mcps: bool,
|
||||
pub has_apps: bool,
|
||||
pub has_hooks: bool,
|
||||
pub has_skills: bool,
|
||||
}
|
||||
|
||||
impl RemotePluginCapabilities {
|
||||
pub(crate) async fn include_active_bundle(
|
||||
&mut self,
|
||||
store: &PluginStore,
|
||||
plugin_id: &PluginId,
|
||||
) {
|
||||
let Some(root) = store.active_plugin_root(plugin_id) else {
|
||||
return;
|
||||
};
|
||||
let Some(loaded) = store.manifest_cache.load(root.as_path()) else {
|
||||
return;
|
||||
};
|
||||
let paths = &loaded.manifest.paths;
|
||||
self.has_skills |= !plugin_skill_roots(&root, paths, loaded.format).is_empty();
|
||||
self.has_mcps |= !load_plugin_mcp_servers_from_manifest_with_format(
|
||||
root.as_path(),
|
||||
paths,
|
||||
/*plugin_policy*/ None,
|
||||
// Declaration discovery must not create runtime directories or depend on their readiness.
|
||||
/*plugin_data_root*/
|
||||
None,
|
||||
loaded.format,
|
||||
)
|
||||
.await
|
||||
.is_empty();
|
||||
// Agent Plugins can declare Apps through an OpenAI extension even when the local
|
||||
// runtime does not activate them. Refresh hints describe declarations, not activation.
|
||||
self.has_apps |= !load_plugin_apps_from_manifest(root.as_path(), paths)
|
||||
.await
|
||||
.is_empty();
|
||||
if loaded.format == PluginManifestFormat::Legacy {
|
||||
let (sources, _) =
|
||||
load_plugin_hooks(&root, plugin_id, &store.plugin_data_root(plugin_id), paths);
|
||||
self.has_hooks |= !plugin_hook_declarations(&sources).is_empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_capabilities_tests.rs"]
|
||||
mod tests;
|
||||
158
codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs
Normal file
158
codex-rs/core-plugins/src/remote/plugin_capabilities_tests.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
//! Covers local capability accumulation and removal hints from the shared bundle sync.
|
||||
|
||||
use super::*;
|
||||
use crate::remote::RemoteInstalledPluginBundleSyncOutcome;
|
||||
use crate::remote::RemotePluginChange;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use crate::remote::sync_remote_installed_plugin_bundles_once;
|
||||
use crate::test_support::write_file;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_utils_plugins::AGENT_PLUGIN_SCHEMA_URI;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_plugin_capabilities_do_not_require_runtime_data_directory() {
|
||||
let codex_home = TempDir::new().expect("Codex home");
|
||||
let store = PluginStore::new(codex_home.path().to_path_buf());
|
||||
let plugin_id = PluginId::parse("example@test").expect("plugin id");
|
||||
let root = store.plugin_root(&plugin_id, "1.0.0");
|
||||
write_file(
|
||||
root.join("plugin.json").as_path(),
|
||||
&json!({
|
||||
"$schema": AGENT_PLUGIN_SCHEMA_URI,
|
||||
"name": "example",
|
||||
"extensions": {"com.openai": {"apps": "./connectors.json"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("mcp.json").as_path(),
|
||||
&json!({
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
|
||||
"mcpServers": {"example": {"type": "stdio", "command": "echo"}},
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
write_file(
|
||||
root.join("connectors.json").as_path(),
|
||||
&json!({"apps": {"example": {"id": "connector_example"}}}).to_string(),
|
||||
);
|
||||
let data_root = store.mcp_data_root(&plugin_id, PluginManifestFormat::AgentPlugin);
|
||||
|
||||
for block_data_root in [false, true] {
|
||||
if block_data_root {
|
||||
write_file(data_root.as_path(), "not a directory");
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
assert_eq!(
|
||||
capabilities,
|
||||
RemotePluginCapabilities {
|
||||
has_mcps: true,
|
||||
has_apps: true,
|
||||
// Agent Plugins declare a conventional skills root even if it is absent.
|
||||
has_skills: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(data_root.as_path().exists(), block_data_root);
|
||||
assert!(!data_root.as_path().is_dir());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capabilities_union_cached_versions_and_sync_reports_removal() -> anyhow::Result<()> {
|
||||
let codex_home = TempDir::new()?;
|
||||
let store = PluginStore::new(codex_home.path().to_path_buf());
|
||||
let plugin_id = PluginId::parse("example@openai-curated-remote")?;
|
||||
let old_root = store.plugin_root(&plugin_id, "1.0.0");
|
||||
for (path, contents) in [
|
||||
(".codex-plugin/plugin.json", r#"{"name":"example"}"#),
|
||||
(
|
||||
".mcp.json",
|
||||
r#"{"mcpServers":{"example":{"command":"unused"}}}"#,
|
||||
),
|
||||
(
|
||||
"hooks/hooks.json",
|
||||
r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo example"}]}]}}"#,
|
||||
),
|
||||
(
|
||||
"skills/example/SKILL.md",
|
||||
"---\nname: example\ndescription: Example skill\n---\nExample skill",
|
||||
),
|
||||
] {
|
||||
write_file(old_root.join(path).as_path(), contents);
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
|
||||
// Accumulate the old and new declarations without involving bundle transport.
|
||||
let new_root = store.plugin_root(&plugin_id, "2.0.0");
|
||||
write_file(
|
||||
new_root.join(".codex-plugin/plugin.json").as_path(),
|
||||
r#"{"name":"example"}"#,
|
||||
);
|
||||
write_file(
|
||||
new_root.join(".app.json").as_path(),
|
||||
r#"{"apps":{"example":{"id":"connector_example"}}}"#,
|
||||
);
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
assert_eq!(
|
||||
capabilities,
|
||||
RemotePluginCapabilities {
|
||||
has_mcps: true,
|
||||
has_apps: true,
|
||||
has_hooks: true,
|
||||
has_skills: true,
|
||||
}
|
||||
);
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
format!("{}/backend-api", server.uri()),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.and(query_param("includeDownloadUrls", "true"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
// Removal describes only the active version, not the union accumulated above.
|
||||
assert_eq!(
|
||||
sync_remote_installed_plugin_bundles_once(
|
||||
codex_home.path().to_path_buf(),
|
||||
&config,
|
||||
Some(&auth),
|
||||
)
|
||||
.await?,
|
||||
RemoteInstalledPluginBundleSyncOutcome {
|
||||
changed_plugins: vec![RemotePluginChange {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
capabilities: RemotePluginCapabilities {
|
||||
has_apps: true,
|
||||
..Default::default()
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert!(!store.plugin_base_root(&plugin_id).as_path().exists());
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
986
codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs
Normal file
986
codex-rs/core-plugins/src/remote/remote_installed_plugin_sync.rs
Normal file
@@ -0,0 +1,986 @@
|
||||
use super::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
|
||||
use super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
|
||||
use super::RemoteInstalledPlugin;
|
||||
use super::RemoteInstalledPluginScope;
|
||||
use super::RemotePluginCapabilities;
|
||||
use super::RemotePluginCatalogError;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use super::RemotePluginShareDiscoverability;
|
||||
use super::ensure_chatgpt_auth;
|
||||
use super::fetch_installed_plugins;
|
||||
use crate::remote::InstalledPluginDisplayAssets;
|
||||
use crate::store::PLUGINS_CACHE_DIR;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::PluginStoreError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
use tokio::fs;
|
||||
use tokio::sync::Semaphore;
|
||||
use tracing::warn;
|
||||
|
||||
static REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES: OnceLock<
|
||||
Mutex<HashMap<PathBuf, Weak<Semaphore>>>,
|
||||
> = OnceLock::new();
|
||||
static REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT: OnceLock<
|
||||
Mutex<HashMap<RemotePluginCacheMutationKey, usize>>,
|
||||
> = OnceLock::new();
|
||||
|
||||
/// A remote plugin bundle newly installed or updated from an authenticated snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginMaterialization {
|
||||
pub plugin_id: PluginId,
|
||||
pub scope: RemotePluginScope,
|
||||
pub discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
pub authenticated_account_id: Option<String>,
|
||||
}
|
||||
|
||||
/// A local plugin and the runtime categories affected by its bundle or installed-state change.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginChange {
|
||||
pub plugin_id: String,
|
||||
pub capabilities: RemotePluginCapabilities,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct RemoteInstalledPluginBundleSyncOutcome {
|
||||
/// Internal provenance for materialization-owned hook trust, not runtime change reporting.
|
||||
pub materialized_remote_plugins: Vec<RemotePluginMaterialization>,
|
||||
/// Affected plugins with capabilities from either side of the change, including removals.
|
||||
/// Installed-state removals do not depend on cache cleanup succeeding.
|
||||
pub changed_plugins: Vec<RemotePluginChange>,
|
||||
pub failed_remote_plugin_ids: Vec<String>,
|
||||
/// Failures that leave an otherwise valid installed plugin unavailable locally.
|
||||
pub failed_materialization_remote_plugin_ids: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteInstalledPluginBundleSyncResult {
|
||||
pub(crate) outcome: RemoteInstalledPluginBundleSyncOutcome,
|
||||
pub(crate) installed_plugins: Vec<RemoteInstalledPlugin>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemoteInstalledPluginBundleSyncError {
|
||||
#[error("{0}")]
|
||||
Catalog(#[from] RemotePluginCatalogError),
|
||||
|
||||
#[error("{0}")]
|
||||
Store(#[from] PluginStoreError),
|
||||
|
||||
#[error("timed out waiting for another remote plugin cache mutation; retry")]
|
||||
LockTimeout,
|
||||
|
||||
#[error("remote plugin state changed during reconciliation; retry reconciliation")]
|
||||
Superseded,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: PathBuf,
|
||||
marketplace_name: String,
|
||||
plugin_name: String,
|
||||
}
|
||||
|
||||
pub struct RemotePluginCacheMutationGuard {
|
||||
key: RemotePluginCacheMutationKey,
|
||||
}
|
||||
|
||||
pub(crate) fn remote_installed_plugin_bundle_sync_gate(codex_home: &Path) -> Arc<Semaphore> {
|
||||
let plugin_cache_root = remote_plugin_cache_root(codex_home);
|
||||
let gates =
|
||||
REMOTE_INSTALLED_PLUGIN_BUNDLE_SYNC_GATES.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut gates = match gates.lock() {
|
||||
Ok(gates) => gates,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(gate) = gates.get(&plugin_cache_root).and_then(Weak::upgrade) {
|
||||
return gate;
|
||||
}
|
||||
let gate = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
gates.insert(plugin_cache_root, Arc::downgrade(&gate));
|
||||
gate
|
||||
}
|
||||
|
||||
pub async fn sync_remote_installed_plugin_bundles_once(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Result<RemoteInstalledPluginBundleSyncOutcome, RemoteInstalledPluginBundleSyncError> {
|
||||
let result = sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home,
|
||||
config,
|
||||
auth,
|
||||
/*previous_plugin_ids*/ &[],
|
||||
)
|
||||
.await?;
|
||||
Ok(result.outcome)
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_remote_installed_plugin_bundles_once_with_snapshot(
|
||||
codex_home: PathBuf,
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
previous_plugin_ids: &[PluginId],
|
||||
) -> Result<RemoteInstalledPluginBundleSyncResult, RemoteInstalledPluginBundleSyncError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let config = &config.for_current_account();
|
||||
let authenticated_account_id = auth.get_account_id();
|
||||
let fetched_installed_plugins = fetch_installed_plugins(
|
||||
config,
|
||||
auth,
|
||||
RemoteInstalledPluginScope::All,
|
||||
/*include_download_urls*/ true,
|
||||
InstalledPluginDisplayAssets::Include,
|
||||
)
|
||||
.await?;
|
||||
// `/installed` is an authoritative full snapshot. If any row cannot be
|
||||
// canonicalized to a local cache key, omitting it makes an installed plugin
|
||||
// indistinguishable from an uninstall, so reject the pass before downloads,
|
||||
// publication, or stale cleanup.
|
||||
let mut validated_installed_plugins = Vec::with_capacity(fetched_installed_plugins.len());
|
||||
for installed_plugin in fetched_installed_plugins {
|
||||
let cached_plugin = super::remote_installed_plugin_to_cache_entry(&installed_plugin)?;
|
||||
let plugin_id = PluginId::new(
|
||||
installed_plugin.plugin.name.clone(),
|
||||
cached_plugin.marketplace_name.clone(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"remote installed plugin `{}` has an invalid local cache id: {err}",
|
||||
installed_plugin.plugin.id
|
||||
))
|
||||
})?;
|
||||
validated_installed_plugins.push((installed_plugin, cached_plugin, plugin_id));
|
||||
}
|
||||
let store = PluginStore::try_new(codex_home.clone())?;
|
||||
let installed_plugin_ids = validated_installed_plugins
|
||||
.iter()
|
||||
.map(|(_, _, plugin_id)| plugin_id.as_key())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut changed_plugins = BTreeMap::new();
|
||||
// Metadata publication removes these plugins even when cleanup fails or partially deletes
|
||||
// a bundle. Capture cached capabilities first so consumers can still invalidate runtimes;
|
||||
// plugins that were never available locally have no previous bundle to invalidate.
|
||||
for plugin_id in previous_plugin_ids {
|
||||
let key = plugin_id.as_key();
|
||||
if installed_plugin_ids.contains(&key) || store.active_plugin_root(plugin_id).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, plugin_id).await;
|
||||
changed_plugins.insert(
|
||||
key.clone(),
|
||||
RemotePluginChange {
|
||||
plugin_id: key,
|
||||
capabilities,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
let mut materialized_remote_plugins = BTreeMap::new();
|
||||
let mut failed_remote_plugin_ids = BTreeSet::new();
|
||||
let mut failed_materialization_remote_plugin_ids = BTreeSet::new();
|
||||
let mut installed_plugins = Vec::new();
|
||||
|
||||
for (installed_plugin, cached_plugin, plugin_id) in validated_installed_plugins {
|
||||
let marketplace_name = cached_plugin.marketplace_name.clone();
|
||||
let plugin = installed_plugin.plugin;
|
||||
let scope = plugin.scope;
|
||||
let discoverability = plugin.discoverability;
|
||||
installed_plugin_names_by_marketplace
|
||||
.entry(marketplace_name.clone())
|
||||
.or_default()
|
||||
.insert(plugin.name.clone());
|
||||
let release_version = plugin
|
||||
.release
|
||||
.version
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|version| !version.is_empty());
|
||||
if let Some(release_version) = release_version
|
||||
&& store.active_plugin_version(&plugin_id).as_deref() == Some(release_version)
|
||||
{
|
||||
if let Err(err) = store.write_remote_plugin_id(&plugin_id, &plugin.id) {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"failed to persist identity for cached remote installed plugin"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id);
|
||||
}
|
||||
installed_plugins.push(cached_plugin);
|
||||
continue;
|
||||
}
|
||||
|
||||
let bundle = match crate::remote_bundle::validate_remote_plugin_bundle(
|
||||
&plugin.id,
|
||||
&marketplace_name,
|
||||
&plugin.name,
|
||||
release_version,
|
||||
plugin.release.bundle_download_url.as_deref(),
|
||||
plugin.release.app_manifest.clone(),
|
||||
) {
|
||||
Ok(bundle) => bundle,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"skipping remote installed plugin bundle download"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id.clone());
|
||||
failed_materialization_remote_plugin_ids.insert(plugin.id);
|
||||
installed_plugins.push(cached_plugin);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Read the old bundle before installation replaces it, including capabilities removed
|
||||
// by the new version. Unchanged bundles never reach this metadata-loading path.
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
match crate::remote_bundle::download_and_install_remote_plugin_bundle(
|
||||
config,
|
||||
codex_home.clone(),
|
||||
bundle,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
let plugin_id = result.plugin_id;
|
||||
capabilities.include_active_bundle(&store, &plugin_id).await;
|
||||
changed_plugins.insert(
|
||||
plugin_id.as_key(),
|
||||
RemotePluginChange {
|
||||
plugin_id: plugin_id.as_key(),
|
||||
capabilities,
|
||||
},
|
||||
);
|
||||
materialized_remote_plugins.insert(
|
||||
plugin_id.as_key(),
|
||||
RemotePluginMaterialization {
|
||||
plugin_id,
|
||||
scope,
|
||||
discoverability,
|
||||
authenticated_account_id: authenticated_account_id.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
remote_plugin_id = %plugin.id,
|
||||
plugin = %plugin.name,
|
||||
marketplace = %marketplace_name,
|
||||
error = %err,
|
||||
"failed to download remote installed plugin bundle"
|
||||
);
|
||||
failed_remote_plugin_ids.insert(plugin.id.clone());
|
||||
failed_materialization_remote_plugin_ids.insert(plugin.id);
|
||||
}
|
||||
}
|
||||
installed_plugins.push(cached_plugin);
|
||||
}
|
||||
|
||||
installed_plugins.sort_by(|left, right| {
|
||||
left.marketplace_name
|
||||
.cmp(&right.marketplace_name)
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
let mut removed_cache_plugins = Vec::new();
|
||||
if let Err(err) = remove_stale_remote_plugin_caches(
|
||||
&store,
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed_cache_plugins,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(error = %err, "failed to remove stale remote plugin cache entries");
|
||||
}
|
||||
for plugin in removed_cache_plugins {
|
||||
changed_plugins
|
||||
.entry(plugin.plugin_id.clone())
|
||||
.or_insert(plugin);
|
||||
}
|
||||
|
||||
Ok(RemoteInstalledPluginBundleSyncResult {
|
||||
outcome: RemoteInstalledPluginBundleSyncOutcome {
|
||||
materialized_remote_plugins: materialized_remote_plugins.into_values().collect(),
|
||||
changed_plugins: changed_plugins.into_values().collect(),
|
||||
failed_remote_plugin_ids: failed_remote_plugin_ids.into_iter().collect(),
|
||||
failed_materialization_remote_plugin_ids: failed_materialization_remote_plugin_ids
|
||||
.into_iter()
|
||||
.collect(),
|
||||
},
|
||||
installed_plugins,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> RemotePluginCacheMutationGuard {
|
||||
let key = RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
};
|
||||
let mutations =
|
||||
REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
*mutations.entry(key.clone()).or_default() += 1;
|
||||
RemotePluginCacheMutationGuard { key }
|
||||
}
|
||||
|
||||
impl Drop for RemotePluginCacheMutationGuard {
|
||||
fn drop(&mut self) {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return;
|
||||
};
|
||||
let mut mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
if let Some(count) = mutations.get_mut(&self.key) {
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
mutations.remove(&self.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_stale_remote_plugin_caches(
|
||||
store: &PluginStore,
|
||||
installed_plugin_names_by_marketplace: &BTreeMap<String, BTreeSet<String>>,
|
||||
removed_plugins: &mut Vec<RemotePluginChange>,
|
||||
) -> Result<(), String> {
|
||||
let codex_home = store.codex_home().as_path();
|
||||
for marketplace_name in [
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME,
|
||||
] {
|
||||
let marketplace_root = codex_home.join(PLUGINS_CACHE_DIR).join(marketplace_name);
|
||||
if !marketplace_root.exists() {
|
||||
continue;
|
||||
}
|
||||
let installed_plugin_names = installed_plugin_names_by_marketplace
|
||||
.get(marketplace_name)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut entries = fs::read_dir(&marketplace_root).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to read remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})?;
|
||||
while let Some(entry) = entries.next_entry().await.map_err(|err| {
|
||||
format!(
|
||||
"failed to enumerate remote plugin cache directory {}: {err}",
|
||||
marketplace_root.display()
|
||||
)
|
||||
})? {
|
||||
let plugin_name = entry.file_name().into_string().map_err(|file_name| {
|
||||
format!(
|
||||
"remote plugin cache entry under {} is not valid UTF-8: {:?}",
|
||||
marketplace_root.display(),
|
||||
file_name
|
||||
)
|
||||
})?;
|
||||
if installed_plugin_names.contains(&plugin_name) {
|
||||
continue;
|
||||
}
|
||||
if is_remote_plugin_cache_mutation_in_flight(codex_home, marketplace_name, &plugin_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let cache_path = entry.path();
|
||||
let plugin_id = PluginId::new(plugin_name.clone(), marketplace_name.to_string());
|
||||
let mut capabilities = RemotePluginCapabilities::default();
|
||||
if let Ok(plugin_id) = &plugin_id {
|
||||
capabilities.include_active_bundle(store, plugin_id).await;
|
||||
}
|
||||
if cache_path.is_dir() {
|
||||
fs::remove_dir_all(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
} else {
|
||||
fs::remove_file(&cache_path).await.map_err(|err| {
|
||||
format!(
|
||||
"failed to remove stale remote plugin cache entry {}: {err}",
|
||||
cache_path.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
let plugin_key = plugin_id
|
||||
.map(|plugin_id| plugin_id.as_key())
|
||||
.unwrap_or_else(|_| format!("{plugin_name}@{marketplace_name}"));
|
||||
removed_plugins.push(RemotePluginChange {
|
||||
plugin_id: plugin_key,
|
||||
capabilities,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remote_plugin_cache_root(codex_home: &Path) -> PathBuf {
|
||||
codex_home.join(PLUGINS_CACHE_DIR)
|
||||
}
|
||||
|
||||
fn is_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> bool {
|
||||
let Some(mutations) = REMOTE_PLUGIN_CACHE_MUTATIONS_IN_FLIGHT.get() else {
|
||||
return false;
|
||||
};
|
||||
let mutations = match mutations.lock() {
|
||||
Ok(mutations) => mutations,
|
||||
Err(err) => err.into_inner(),
|
||||
};
|
||||
mutations.contains_key(&RemotePluginCacheMutationKey {
|
||||
plugin_cache_root: remote_plugin_cache_root(codex_home),
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
plugin_name: plugin_name.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
use wiremock::matchers::query_param_is_missing;
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_same_version_backfills_metadata_and_missing_version_requires_materialization() {
|
||||
let server = MockServer::start().await;
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
|
||||
.join("linear")
|
||||
.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":"linear","version":"1.2.3"}"#)
|
||||
.expect("write cached plugin manifest");
|
||||
let remote_plugin_id = "plugins~Plugin_linear";
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.and(query_param_is_missing("scope"))
|
||||
.and(query_param("limit", "200"))
|
||||
.and(query_param("includeDownloadUrls", "true"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [
|
||||
{
|
||||
"id": remote_plugin_id,
|
||||
"name": "linear",
|
||||
"scope": "GLOBAL",
|
||||
"installation_policy": "AVAILABLE",
|
||||
"authentication_policy": "ON_USE",
|
||||
"status": "ENABLED",
|
||||
"release": {
|
||||
"version": "1.2.3",
|
||||
"display_name": "Linear",
|
||||
"description": "Track work",
|
||||
"interface": {},
|
||||
},
|
||||
"enabled": true,
|
||||
},
|
||||
{
|
||||
"id": "plugins~Plugin_missing_version",
|
||||
"name": "missing-version",
|
||||
"scope": "GLOBAL",
|
||||
"installation_policy": "AVAILABLE",
|
||||
"authentication_policy": "ON_USE",
|
||||
"status": "ENABLED",
|
||||
"release": {
|
||||
"display_name": "Missing version",
|
||||
"description": "Needs materialization",
|
||||
"interface": {},
|
||||
},
|
||||
"enabled": true,
|
||||
},
|
||||
],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
format!("{}/backend-api", server.uri()),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let outcome = sync_remote_installed_plugin_bundles_once(
|
||||
codex_home.path().to_path_buf(),
|
||||
&config,
|
||||
Some(&auth),
|
||||
)
|
||||
.await
|
||||
.expect("sync current remote plugin bundle");
|
||||
|
||||
assert_eq!(
|
||||
outcome,
|
||||
RemoteInstalledPluginBundleSyncOutcome {
|
||||
failed_remote_plugin_ids: vec!["plugins~Plugin_missing_version".to_string()],
|
||||
failed_materialization_remote_plugin_ids: vec![
|
||||
"plugins~Plugin_missing_version".to_string()
|
||||
],
|
||||
..RemoteInstalledPluginBundleSyncOutcome::default()
|
||||
}
|
||||
);
|
||||
let plugin_id = PluginId::new(
|
||||
"linear".to_string(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.expect("valid plugin id");
|
||||
let metadata_path = PluginStore::new(codex_home.path().to_path_buf())
|
||||
.plugin_base_root(&plugin_id)
|
||||
.join(".codex-remote-plugin-install.json");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&std::fs::read_to_string(metadata_path.as_path())
|
||||
.expect("read remote plugin install metadata")
|
||||
)
|
||||
.expect("parse remote plugin install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": remote_plugin_id,
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
|
||||
.join("missing-version")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_all_scopes_paginates_and_reconciles_each_marketplace() {
|
||||
let server = MockServer::start().await;
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cached_plugins = [
|
||||
(
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"global-plugin",
|
||||
"GLOBAL",
|
||||
None,
|
||||
),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME,
|
||||
"user-plugin",
|
||||
"USER",
|
||||
None,
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME,
|
||||
"workspace-plugin",
|
||||
"WORKSPACE",
|
||||
Some("LISTED"),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME,
|
||||
"shared-plugin",
|
||||
"WORKSPACE",
|
||||
Some("PRIVATE"),
|
||||
),
|
||||
];
|
||||
for (marketplace_name, plugin_name, _, _) in cached_plugins {
|
||||
for cached_plugin_name in [plugin_name, "stale"] {
|
||||
let manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(marketplace_name)
|
||||
.join(cached_plugin_name)
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(manifest.parent().expect("manifest parent"))
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(
|
||||
&manifest,
|
||||
format!(r#"{{"name":"{cached_plugin_name}","version":"1.2.3"}}"#),
|
||||
)
|
||||
.expect("write cached plugin manifest");
|
||||
}
|
||||
}
|
||||
let installed_plugins = cached_plugins
|
||||
.iter()
|
||||
.map(|(_, plugin_name, scope, discoverability)| {
|
||||
let mut plugin = json!({
|
||||
"id": format!("plugins~Plugin_{plugin_name}"),
|
||||
"name": plugin_name,
|
||||
"scope": scope,
|
||||
"installation_policy": "AVAILABLE",
|
||||
"authentication_policy": "ON_USE",
|
||||
"status": "ENABLED",
|
||||
"release": {
|
||||
"version": "1.2.3",
|
||||
"display_name": plugin_name,
|
||||
"description": "Installed plugin",
|
||||
"interface": {},
|
||||
},
|
||||
"enabled": true,
|
||||
});
|
||||
if let Some(discoverability) = discoverability {
|
||||
plugin["discoverability"] = json!(discoverability);
|
||||
}
|
||||
plugin
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.and(query_param_is_missing("scope"))
|
||||
.and(query_param("limit", "200"))
|
||||
.and(query_param("includeDownloadUrls", "true"))
|
||||
.and(query_param_is_missing("pageToken"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": &installed_plugins[..2],
|
||||
"pagination": {"next_page_token": "page-2"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.and(query_param_is_missing("scope"))
|
||||
.and(query_param("limit", "200"))
|
||||
.and(query_param("includeDownloadUrls", "true"))
|
||||
.and(query_param("pageToken", "page-2"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": &installed_plugins[2..],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, selected_urls) = crate::test_support::recording_remote_plugin_service_config(
|
||||
format!("{}/backend-api", server.uri()),
|
||||
);
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let outcome = sync_remote_installed_plugin_bundles_once(
|
||||
codex_home.path().to_path_buf(),
|
||||
&config,
|
||||
Some(&auth),
|
||||
)
|
||||
.await
|
||||
.expect("sync installed plugins across every marketplace");
|
||||
let mut removed_cache_plugin_ids = cached_plugins
|
||||
.iter()
|
||||
.map(|(marketplace_name, _, _, _)| format!("stale@{marketplace_name}"))
|
||||
.collect::<Vec<_>>();
|
||||
removed_cache_plugin_ids.sort();
|
||||
|
||||
assert_eq!(
|
||||
outcome,
|
||||
RemoteInstalledPluginBundleSyncOutcome {
|
||||
materialized_remote_plugins: Vec::new(),
|
||||
changed_plugins: removed_cache_plugin_ids
|
||||
.into_iter()
|
||||
.map(|plugin_id| RemotePluginChange {
|
||||
plugin_id,
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
})
|
||||
.collect(),
|
||||
failed_remote_plugin_ids: Vec::new(),
|
||||
failed_materialization_remote_plugin_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
crate::test_support::recorded_http_client_urls(&selected_urls),
|
||||
vec![
|
||||
format!(
|
||||
"{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true",
|
||||
server.uri()
|
||||
),
|
||||
format!(
|
||||
"{}/backend-api/ps/plugins/installed?limit=200&includeDownloadUrls=true&pageToken=page-2",
|
||||
server.uri()
|
||||
),
|
||||
]
|
||||
);
|
||||
for (marketplace_name, plugin_name, _, _) in cached_plugins {
|
||||
let plugin_root = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(marketplace_name)
|
||||
.join(plugin_name);
|
||||
assert!(
|
||||
plugin_root
|
||||
.join("1.2.3/.codex-plugin/plugin.json")
|
||||
.is_file()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&std::fs::read_to_string(plugin_root.join(".codex-remote-plugin-install.json"))
|
||||
.expect("read remote plugin install metadata")
|
||||
)
|
||||
.expect("parse remote plugin install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": format!("plugins~Plugin_{plugin_name}"),
|
||||
})
|
||||
);
|
||||
assert!(
|
||||
!codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(marketplace_name)
|
||||
.join("stale")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_remote_plugin_cleanup_skips_cache_mutations_in_progress() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_GLOBAL_MARKETPLACE_NAME)
|
||||
.join("linear")
|
||||
.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":"linear"}"#)
|
||||
.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_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let second_guard = mark_remote_plugin_cache_mutation_in_flight(
|
||||
codex_home.path(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
"linear",
|
||||
);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while install is guarded");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup while second install guard is still active");
|
||||
assert_eq!(removed, Vec::<RemotePluginChange>::new());
|
||||
assert!(cached_manifest.is_file());
|
||||
|
||||
drop(second_guard);
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup after install guard is dropped");
|
||||
assert_eq!(
|
||||
removed,
|
||||
vec![RemotePluginChange {
|
||||
plugin_id: "linear@openai-curated-remote".to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
}]
|
||||
);
|
||||
assert!(!cached_manifest.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_remote_plugin_cleanup_removes_stale_marketplace_caches_and_keeps_canonical_cache()
|
||||
{
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let created_by_me_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_CREATED_BY_ME_MARKETPLACE_NAME)
|
||||
.join("created-by-me-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(
|
||||
created_by_me_cached_manifest
|
||||
.parent()
|
||||
.expect("manifest parent"),
|
||||
)
|
||||
.expect("create cached plugin manifest parent");
|
||||
std::fs::write(
|
||||
&created_by_me_cached_manifest,
|
||||
r#"{"name":"created-by-me-plugin"}"#,
|
||||
)
|
||||
.expect("write cached plugin manifest");
|
||||
let cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_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 canonical_cached_manifest = codex_home
|
||||
.path()
|
||||
.join(PLUGINS_CACHE_DIR)
|
||||
.join(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME)
|
||||
.join("shared-plugin")
|
||||
.join("1.2.3")
|
||||
.join(".codex-plugin")
|
||||
.join("plugin.json");
|
||||
std::fs::create_dir_all(canonical_cached_manifest.parent().expect("manifest parent"))
|
||||
.expect("create canonical cached plugin manifest parent");
|
||||
std::fs::write(&canonical_cached_manifest, r#"{"name":"shared-plugin"}"#)
|
||||
.expect("write canonical cached plugin manifest");
|
||||
let installed_plugin_names_by_marketplace =
|
||||
BTreeMap::<String, BTreeSet<String>>::from_iter([
|
||||
(REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(), BTreeSet::new()),
|
||||
(
|
||||
REMOTE_CREATED_BY_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::from(["shared-plugin".to_string()]),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME.to_string(),
|
||||
BTreeSet::new(),
|
||||
),
|
||||
]);
|
||||
|
||||
let mut removed = Vec::new();
|
||||
remove_stale_remote_plugin_caches(
|
||||
&PluginStore::new(codex_home.path().to_path_buf()),
|
||||
&installed_plugin_names_by_marketplace,
|
||||
&mut removed,
|
||||
)
|
||||
.await
|
||||
.expect("cleanup private shared-with-me cache");
|
||||
|
||||
assert_eq!(
|
||||
removed,
|
||||
[
|
||||
"created-by-me-plugin@created-by-me-remote",
|
||||
"private-plugin@workspace-shared-with-me-private",
|
||||
]
|
||||
.map(|plugin_id| RemotePluginChange {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
capabilities: RemotePluginCapabilities::default(),
|
||||
})
|
||||
.to_vec()
|
||||
);
|
||||
assert!(!created_by_me_cached_manifest.exists());
|
||||
assert!(!cached_manifest.exists());
|
||||
assert!(canonical_cached_manifest.is_file());
|
||||
}
|
||||
}
|
||||
91
codex-rs/core-plugins/src/remote/search.rs
Normal file
91
codex-rs/core-plugins/src/remote/search.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
use super::RemotePluginCatalogError;
|
||||
use super::RemotePluginListResponse;
|
||||
use super::RemotePluginScope;
|
||||
use super::RemotePluginServiceConfig;
|
||||
use super::RemotePluginSummary;
|
||||
use super::authenticated_request;
|
||||
use super::build_remote_plugin_summary;
|
||||
use super::ensure_chatgpt_auth;
|
||||
use super::send_and_decode;
|
||||
use codex_login::CodexAuth;
|
||||
use http::Method;
|
||||
use tracing::instrument;
|
||||
use url::Url;
|
||||
|
||||
/// Search parameters forwarded directly to plugin-service.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RemotePluginSearchRequest<'a> {
|
||||
pub query: &'a str,
|
||||
pub scope: Option<RemotePluginScope>,
|
||||
pub limit: u32,
|
||||
pub page_token: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// One uncached page of remote plugin search results.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RemotePluginSearchPage {
|
||||
pub plugins: Vec<RemotePluginSummary>,
|
||||
pub next_page_token: Option<String>,
|
||||
}
|
||||
|
||||
/// Searches plugin-service without reading or populating the remote catalog cache.
|
||||
#[instrument(
|
||||
level = "debug",
|
||||
skip_all,
|
||||
fields(plugin.scope = ?search.scope, plugin.limit = search.limit)
|
||||
)]
|
||||
pub async fn search_remote_plugins(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
search: RemotePluginSearchRequest<'_>,
|
||||
) -> Result<RemotePluginSearchPage, RemotePluginCatalogError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let mut url = Url::parse(&format!("{base_url}/ps/plugins/search"))
|
||||
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
|
||||
// Search terms and page tokens can contain user data. Keep the queryless endpoint for
|
||||
// diagnostics so neither value is exposed through errors or telemetry.
|
||||
let url_for_error = url.to_string();
|
||||
|
||||
{
|
||||
let mut query_pairs = url.query_pairs_mut();
|
||||
query_pairs.append_pair("q", search.query);
|
||||
if let Some(scope) = search.scope {
|
||||
query_pairs.append_pair("scope", scope.api_value());
|
||||
}
|
||||
query_pairs.append_pair("limit", &search.limit.to_string());
|
||||
if let Some(page_token) = search.page_token {
|
||||
query_pairs.append_pair("pageToken", page_token);
|
||||
}
|
||||
}
|
||||
|
||||
let url = url.to_string();
|
||||
let request = authenticated_request(config, Method::GET, &url, auth).await?;
|
||||
let response: RemotePluginListResponse = send_and_decode(request, &url_for_error)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
RemotePluginCatalogError::Request { url, source } => {
|
||||
RemotePluginCatalogError::Request {
|
||||
url,
|
||||
source: source.without_url(),
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
})?;
|
||||
let plugins = response
|
||||
.plugins
|
||||
.iter()
|
||||
// Search intentionally does not join against `/ps/plugins/installed`, so these
|
||||
// summaries always report `installed: false`.
|
||||
.map(|plugin| build_remote_plugin_summary(plugin, /*installed_plugin*/ None))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(RemotePluginSearchPage {
|
||||
plugins,
|
||||
next_page_token: response.pagination.next_page_token,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "search_tests.rs"]
|
||||
mod tests;
|
||||
490
codex-rs/core-plugins/src/remote/search_tests.rs
Normal file
490
codex-rs/core-plugins/src/remote/search_tests.rs
Normal file
@@ -0,0 +1,490 @@
|
||||
use super::*;
|
||||
use crate::remote::REMOTE_CREATED_BY_ME_MARKETPLACE_NAME;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME;
|
||||
use crate::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use crate::remote::RemotePluginShareDiscoverability;
|
||||
use crate::test_support::recorded_http_client_urls;
|
||||
use crate::test_support::recording_remote_plugin_service_config;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginDisabledReason;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_app_server_protocol::PluginInstallPolicySource;
|
||||
use codex_app_server_protocol::PluginInterface;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::header_exists;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
use wiremock::matchers::query_param_is_missing;
|
||||
|
||||
fn remote_plugin_json(remote_plugin_id: &str, plugin_name: &str, scope: &str) -> serde_json::Value {
|
||||
let discoverability = (scope == "WORKSPACE").then_some("LISTED");
|
||||
json!({
|
||||
"id": remote_plugin_id,
|
||||
"name": plugin_name,
|
||||
"scope": scope,
|
||||
"discoverability": discoverability,
|
||||
"installation_policy": "AVAILABLE",
|
||||
"authentication_policy": "ON_USE",
|
||||
"release": {
|
||||
"display_name": plugin_name,
|
||||
"description": format!("{plugin_name} description"),
|
||||
"interface": {},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_forwards_parameters_and_converts_results() {
|
||||
let server = MockServer::start().await;
|
||||
let remote_plugin = json!({
|
||||
"id": "plugins~Plugin_linear",
|
||||
"name": "linear",
|
||||
"scope": "GLOBAL",
|
||||
"installation_policy": "NOT_AVAILABLE",
|
||||
"installation_policy_source": "WORKSPACE_SETTING",
|
||||
"must_show_installation_interstitial": true,
|
||||
"authentication_policy": "ON_INSTALL",
|
||||
"status": "DISABLED_BY_ADMIN",
|
||||
"disabled_reason": "plan_not_eligible",
|
||||
"eligible_plan_types": ["pro"],
|
||||
"release": {
|
||||
"version": "1.2.3",
|
||||
"display_name": "Linear",
|
||||
"description": "Track issues",
|
||||
"keywords": ["issues"],
|
||||
"interface": {
|
||||
"short_description": "Issue tracking",
|
||||
"category": "Productivity",
|
||||
"capabilities": ["Create issues"],
|
||||
"logo_url": "https://example.com/linear.png",
|
||||
},
|
||||
},
|
||||
});
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.and(query_param("q", "linear & docs/+"))
|
||||
.and(query_param("scope", "GLOBAL"))
|
||||
.and(query_param("limit", "16"))
|
||||
.and(query_param("pageToken", "next page/+"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.and(header("oai-product-sku", "codex"))
|
||||
.and(header_exists("user-agent"))
|
||||
.and(header_exists("originator"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [remote_plugin],
|
||||
"pagination": {"next_page_token": "later page/+"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, selected_urls) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api/", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "linear & docs/+",
|
||||
scope: Some(RemotePluginScope::Global),
|
||||
limit: 16,
|
||||
page_token: Some("next page/+"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("plugin search should succeed");
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
RemotePluginSearchPage {
|
||||
plugins: vec![RemotePluginSummary {
|
||||
id: format!("linear@{REMOTE_GLOBAL_MARKETPLACE_NAME}"),
|
||||
remote_plugin_id: "plugins~Plugin_linear".to_string(),
|
||||
version: Some("1.2.3".to_string()),
|
||||
local_version: None,
|
||||
name: "linear".to_string(),
|
||||
share_context: None,
|
||||
installed: false,
|
||||
installed_at: None,
|
||||
enabled: false,
|
||||
install_policy: PluginInstallPolicy::NotAvailable,
|
||||
install_policy_source: Some(PluginInstallPolicySource::WorkspaceSetting),
|
||||
must_show_installation_interstitial: Some(true),
|
||||
auth_policy: PluginAuthPolicy::OnInstall,
|
||||
availability: PluginAvailability::DisabledByAdmin,
|
||||
disabled_reason: Some(PluginDisabledReason::PlanNotEligible),
|
||||
eligible_plan_types: Some(vec!["pro".to_string()]),
|
||||
interface: Some(PluginInterface {
|
||||
display_name: Some("Linear".to_string()),
|
||||
short_description: Some("Issue tracking".to_string()),
|
||||
long_description: None,
|
||||
developer_name: None,
|
||||
category: Some("Productivity".to_string()),
|
||||
capabilities: vec!["Create issues".to_string()],
|
||||
website_url: None,
|
||||
privacy_policy_url: None,
|
||||
terms_of_service_url: None,
|
||||
default_prompt: None,
|
||||
brand_color: None,
|
||||
composer_icon: None,
|
||||
composer_icon_url: None,
|
||||
logo: None,
|
||||
logo_dark: None,
|
||||
logo_url: Some("https://example.com/linear.png".to_string()),
|
||||
logo_url_dark: None,
|
||||
screenshots: Vec::new(),
|
||||
screenshot_urls: Vec::new(),
|
||||
}),
|
||||
keywords: vec!["issues".to_string()],
|
||||
}],
|
||||
next_page_token: Some("later page/+".to_string()),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
recorded_http_client_urls(&selected_urls),
|
||||
vec![format!(
|
||||
"{}/backend-api/ps/plugins/search?q=linear+%26+docs%2F%2B&scope=GLOBAL&limit=16&pageToken=next+page%2F%2B",
|
||||
server.uri()
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_omits_optional_scope_and_page_token() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.and(query_param("q", "calendar"))
|
||||
.and(query_param("limit", "25"))
|
||||
.and(query_param_is_missing("scope"))
|
||||
.and(query_param_is_missing("pageToken"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
for _ in 0..2 {
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "calendar",
|
||||
scope: None,
|
||||
limit: 25,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("unscoped plugin search should succeed");
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
RemotePluginSearchPage {
|
||||
plugins: Vec::new(),
|
||||
next_page_token: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_forwards_each_supported_scope() {
|
||||
let server = MockServer::start().await;
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
for (scope, expected_scope) in [
|
||||
(RemotePluginScope::Global, "GLOBAL"),
|
||||
(RemotePluginScope::User, "USER"),
|
||||
(RemotePluginScope::Workspace, "WORKSPACE"),
|
||||
] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.and(query_param("scope", expected_scope))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "calendar",
|
||||
scope: Some(scope),
|
||||
limit: 16,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("scoped plugin search should succeed");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_preserves_order_and_canonical_marketplaces() {
|
||||
let server = MockServer::start().await;
|
||||
let mut shared_plugin = remote_plugin_json("plugin-shared", "shared", "WORKSPACE");
|
||||
shared_plugin["discoverability"] = json!("PRIVATE");
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [
|
||||
remote_plugin_json("plugin-user", "personal", "USER"),
|
||||
remote_plugin_json("plugin-global", "global", "GLOBAL"),
|
||||
remote_plugin_json("plugin-workspace", "workspace", "WORKSPACE"),
|
||||
shared_plugin,
|
||||
],
|
||||
"pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "plugin",
|
||||
scope: None,
|
||||
limit: 16,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("mixed-scope plugin search should succeed");
|
||||
|
||||
let identities = result
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| {
|
||||
(
|
||||
plugin.id,
|
||||
plugin.remote_plugin_id,
|
||||
plugin.share_context.map(|context| context.discoverability),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
identities,
|
||||
vec![
|
||||
(
|
||||
format!("personal@{REMOTE_CREATED_BY_ME_MARKETPLACE_NAME}"),
|
||||
"plugin-user".to_string(),
|
||||
None,
|
||||
),
|
||||
(
|
||||
format!("global@{REMOTE_GLOBAL_MARKETPLACE_NAME}"),
|
||||
"plugin-global".to_string(),
|
||||
None,
|
||||
),
|
||||
(
|
||||
format!("workspace@{REMOTE_WORKSPACE_MARKETPLACE_NAME}"),
|
||||
"plugin-workspace".to_string(),
|
||||
Some(RemotePluginShareDiscoverability::Listed),
|
||||
),
|
||||
(
|
||||
format!("shared@{REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME}"),
|
||||
"plugin-shared".to_string(),
|
||||
Some(RemotePluginShareDiscoverability::Private),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_requires_chatgpt_authentication() {
|
||||
let (config, selected_urls) =
|
||||
recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string());
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
/*auth*/ None,
|
||||
RemotePluginSearchRequest {
|
||||
query: "calendar",
|
||||
scope: None,
|
||||
limit: 16,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RemotePluginCatalogError::AuthRequired)
|
||||
));
|
||||
assert_eq!(
|
||||
recorded_http_client_urls(&selected_urls),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_rejects_api_key_authentication() {
|
||||
let (config, selected_urls) =
|
||||
recording_remote_plugin_service_config("https://chatgpt.example/backend-api".to_string());
|
||||
let auth = CodexAuth::from_api_key("test-api-key");
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "calendar",
|
||||
scope: Some(RemotePluginScope::Global),
|
||||
limit: 16,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RemotePluginCatalogError::UnsupportedAuthMode)
|
||||
));
|
||||
assert_eq!(
|
||||
recorded_http_client_urls(&selected_urls),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_redacts_sensitive_parameters_from_transport_errors() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.expect("test listener should bind to a local port");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("test listener should have a local address");
|
||||
let connection = std::thread::spawn(move || {
|
||||
let (stream, _) = listener
|
||||
.accept()
|
||||
.expect("test listener should accept the plugin search request");
|
||||
drop(stream);
|
||||
});
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("http://{address}/backend-api"));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let error = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "sensitive search term",
|
||||
scope: Some(RemotePluginScope::Global),
|
||||
limit: 16,
|
||||
page_token: Some("sensitive pagination token"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("closed connection should fail the plugin search request");
|
||||
connection
|
||||
.join()
|
||||
.expect("test listener should close the accepted connection");
|
||||
|
||||
let error_message = error.to_string();
|
||||
assert!(!error_message.contains("sensitive search term"));
|
||||
assert!(!error_message.contains("sensitive pagination token"));
|
||||
let RemotePluginCatalogError::Request { url, source } = error else {
|
||||
panic!("expected transport request error");
|
||||
};
|
||||
assert_eq!(
|
||||
url,
|
||||
format!("http://{address}/backend-api/ps/plugins/search")
|
||||
);
|
||||
assert!(!source.to_string().contains("sensitive"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_preserves_upstream_http_errors() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.respond_with(ResponseTemplate::new(503).set_body_string("plugin search unavailable"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "sensitive search term",
|
||||
scope: Some(RemotePluginScope::Global),
|
||||
limit: 16,
|
||||
page_token: Some("sensitive pagination token"),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let error = result.expect_err("upstream HTTP status should fail");
|
||||
let error_message = error.to_string();
|
||||
assert!(!error_message.contains("sensitive search term"));
|
||||
assert!(!error_message.contains("sensitive pagination token"));
|
||||
let RemotePluginCatalogError::UnexpectedStatus { url, status, body } = error else {
|
||||
panic!("expected upstream HTTP status error");
|
||||
};
|
||||
assert_eq!(
|
||||
(url, status, body),
|
||||
(
|
||||
format!("{}/backend-api/ps/plugins/search", server.uri()),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"plugin search unavailable".to_string(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_remote_plugins_preserves_response_decode_errors() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/search"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_string("not-json"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (config, _) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
|
||||
let result = search_remote_plugins(
|
||||
&config,
|
||||
Some(&auth),
|
||||
RemotePluginSearchRequest {
|
||||
query: "calendar",
|
||||
scope: None,
|
||||
limit: 16,
|
||||
page_token: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RemotePluginCatalogError::Decode { .. })
|
||||
));
|
||||
}
|
||||
536
codex-rs/core-plugins/src/remote/share.rs
Normal file
536
codex-rs/core-plugins/src/remote/share.rs
Normal file
@@ -0,0 +1,536 @@
|
||||
use super::*;
|
||||
use crate::plugin_bundle_archive::PluginBundlePackError;
|
||||
use crate::plugin_bundle_archive::pack_plugin_bundle_tar_gz;
|
||||
use codex_http_client::RequestBuilder;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use http::Method;
|
||||
use http::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use tracing::warn;
|
||||
use url::Url;
|
||||
|
||||
mod checkout;
|
||||
mod local_paths;
|
||||
|
||||
const REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES: usize = 50 * 1024 * 1024;
|
||||
|
||||
pub use checkout::checkout_remote_plugin_share;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginShareSaveResult {
|
||||
pub remote_plugin_id: String,
|
||||
pub share_url: Option<String>,
|
||||
pub can_publish_to_workspace: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct RemotePluginShareAccessPolicy {
|
||||
pub discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
pub share_targets: Option<Vec<RemotePluginShareTarget>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RemotePluginShareDiscoverability {
|
||||
Listed,
|
||||
Unlisted,
|
||||
Private,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum RemotePluginShareUpdateDiscoverability {
|
||||
Listed,
|
||||
Unlisted,
|
||||
Private,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RemotePluginSharePrincipalType {
|
||||
User,
|
||||
Group,
|
||||
Workspace,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
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)]
|
||||
struct RemoteWorkspacePluginUploadUrlRequest<'a> {
|
||||
filename: &'a str,
|
||||
mime_type: &'a str,
|
||||
size_bytes: usize,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
plugin_id: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
struct RemoteWorkspacePluginUploadUrlResponse {
|
||||
file_id: String,
|
||||
upload_url: String,
|
||||
etag: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
struct RemoteWorkspacePluginCreateRequest {
|
||||
file_id: String,
|
||||
etag: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
discoverability: Option<RemotePluginShareDiscoverability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
share_targets: Option<Vec<RemotePluginShareTarget>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
struct RemoteWorkspacePluginCreateResponse {
|
||||
plugin_id: String,
|
||||
share_url: Option<String>,
|
||||
#[serde(default)]
|
||||
can_publish_to_workspace: Option<bool>,
|
||||
}
|
||||
|
||||
#[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(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_home: &Path,
|
||||
plugin_path: &AbsolutePathBuf,
|
||||
remote_plugin_id: Option<&str>,
|
||||
access_policy: RemotePluginShareAccessPolicy,
|
||||
) -> Result<RemotePluginShareSaveResult, RemotePluginCatalogError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let config = &config.for_current_account();
|
||||
let plugin_path_for_archive = plugin_path.as_path().to_path_buf();
|
||||
let (filename, archive_bytes) = tokio::task::spawn_blocking(move || {
|
||||
let filename = archive_filename(&plugin_path_for_archive)?;
|
||||
let archive_bytes = archive_plugin_for_upload(&plugin_path_for_archive)?;
|
||||
Ok::<_, RemotePluginCatalogError>((filename, archive_bytes))
|
||||
})
|
||||
.await
|
||||
.map_err(RemotePluginCatalogError::ArchiveJoin)??;
|
||||
let upload = create_workspace_plugin_upload(
|
||||
config,
|
||||
auth,
|
||||
&filename,
|
||||
archive_bytes.len(),
|
||||
remote_plugin_id,
|
||||
)
|
||||
.await?;
|
||||
let etag = upload
|
||||
.etag
|
||||
.ok_or(RemotePluginCatalogError::MissingUploadEtag)?;
|
||||
put_workspace_plugin_upload(config, &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,
|
||||
remote_plugin_id,
|
||||
RemoteWorkspacePluginCreateRequest {
|
||||
file_id: upload.file_id,
|
||||
etag,
|
||||
discoverability: access_policy.discoverability,
|
||||
share_targets,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if response.plugin_id.is_empty() {
|
||||
return Err(RemotePluginCatalogError::UnexpectedResponse(
|
||||
"workspace plugin create response did not include a plugin id".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(err) = local_paths::record_plugin_share_local_path(
|
||||
codex_home,
|
||||
&response.plugin_id,
|
||||
plugin_path.clone(),
|
||||
) {
|
||||
warn!(
|
||||
remote_plugin_id = %response.plugin_id,
|
||||
"failed to record plugin share local path mapping: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(RemotePluginShareSaveResult {
|
||||
remote_plugin_id: response.plugin_id,
|
||||
share_url: response.share_url,
|
||||
can_publish_to_workspace: response.can_publish_to_workspace,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn list_remote_plugin_shares(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_home: &Path,
|
||||
) -> Result<Vec<RemotePluginShareSummary>, RemotePluginCatalogError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let created_plugins = fetch_created_workspace_plugins(config, auth).await?;
|
||||
if created_plugins.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let installed_by_id =
|
||||
fetch_installed_plugins_for_scope(config, auth, RemotePluginScope::Workspace)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|plugin| (plugin.plugin.id.clone(), plugin))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let local_plugin_paths =
|
||||
local_paths::load_plugin_share_local_paths(codex_home).map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to load plugin share local path mapping: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
created_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| {
|
||||
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()
|
||||
}
|
||||
|
||||
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)?;
|
||||
local_paths
|
||||
.into_iter()
|
||||
.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(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<(), RemotePluginCatalogError> {
|
||||
let auth = ensure_chatgpt_auth(auth)?;
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let url = format!("{base_url}/public/plugins/workspace/{remote_plugin_id}");
|
||||
let request = authenticated_request(config, Method::DELETE, &url, auth).await?;
|
||||
send_and_expect_status(request, &url, &[StatusCode::NO_CONTENT]).await?;
|
||||
if let Err(err) = local_paths::remove_plugin_share_local_path(codex_home, remote_plugin_id) {
|
||||
warn!(
|
||||
remote_plugin_id = %remote_plugin_id,
|
||||
"failed to remove plugin share local path mapping: {err}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_remote_plugin_share_targets(
|
||||
config: &RemotePluginServiceConfig,
|
||||
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::Listed => RemotePluginShareDiscoverability::Listed,
|
||||
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}/ps/plugins/{remote_plugin_id}/shares");
|
||||
let request = authenticated_request(config, Method::PUT, &url, auth)
|
||||
.await?
|
||||
.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,
|
||||
) -> Result<Vec<RemotePluginDirectoryItem>, RemotePluginCatalogError> {
|
||||
let mut plugins = Vec::new();
|
||||
let mut page_token = None;
|
||||
loop {
|
||||
let response =
|
||||
get_created_workspace_plugins_page(config, auth, page_token.as_deref()).await?;
|
||||
plugins.extend(response.plugins);
|
||||
let Some(next_page_token) = response.pagination.next_page_token else {
|
||||
break;
|
||||
};
|
||||
page_token = Some(next_page_token);
|
||||
}
|
||||
Ok(plugins)
|
||||
}
|
||||
|
||||
async fn get_created_workspace_plugins_page(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
page_token: Option<&str>,
|
||||
) -> Result<RemotePluginListResponse, RemotePluginCatalogError> {
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let mut url = Url::parse(&format!("{base_url}/ps/plugins/workspace/created"))
|
||||
.map_err(RemotePluginCatalogError::InvalidBaseUrl)?;
|
||||
url.query_pairs_mut()
|
||||
.append_pair("limit", &REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string());
|
||||
if let Some(page_token) = page_token {
|
||||
url.query_pairs_mut().append_pair("pageToken", page_token);
|
||||
}
|
||||
let url = url.to_string();
|
||||
let request = authenticated_request(config, Method::GET, &url, auth).await?;
|
||||
send_and_decode(request, &url).await
|
||||
}
|
||||
|
||||
async fn create_workspace_plugin_upload(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
filename: &str,
|
||||
size_bytes: usize,
|
||||
remote_plugin_id: Option<&str>,
|
||||
) -> Result<RemoteWorkspacePluginUploadUrlResponse, RemotePluginCatalogError> {
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let url = format!("{base_url}/public/plugins/workspace/upload-url");
|
||||
let request = authenticated_request(config, Method::POST, &url, auth)
|
||||
.await?
|
||||
.json(&RemoteWorkspacePluginUploadUrlRequest {
|
||||
filename,
|
||||
mime_type: "application/gzip",
|
||||
size_bytes,
|
||||
plugin_id: remote_plugin_id,
|
||||
});
|
||||
send_and_decode(request, &url).await
|
||||
}
|
||||
|
||||
async fn put_workspace_plugin_upload(
|
||||
config: &RemotePluginServiceConfig,
|
||||
upload_url: &str,
|
||||
archive_bytes: Vec<u8>,
|
||||
) -> Result<(), RemotePluginCatalogError> {
|
||||
let request = config
|
||||
.http_request(Method::PUT, upload_url)
|
||||
.timeout(REMOTE_PLUGIN_CATALOG_TIMEOUT)
|
||||
.header("x-ms-blob-type", "BlockBlob")
|
||||
.header("Content-Type", "application/gzip")
|
||||
.body(archive_bytes);
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|source| RemotePluginCatalogError::Request {
|
||||
url: "workspace plugin upload URL".to_string(),
|
||||
source,
|
||||
})?;
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|source| RemotePluginCatalogError::Request {
|
||||
url: "workspace plugin upload URL".to_string(),
|
||||
source,
|
||||
})?;
|
||||
if ![StatusCode::OK, StatusCode::CREATED].contains(&status) {
|
||||
return Err(RemotePluginCatalogError::UnexpectedStatus {
|
||||
url: "workspace plugin upload URL".to_string(),
|
||||
status,
|
||||
body,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finalize_workspace_plugin_upload(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: &CodexAuth,
|
||||
remote_plugin_id: Option<&str>,
|
||||
body: RemoteWorkspacePluginCreateRequest,
|
||||
) -> Result<RemoteWorkspacePluginCreateResponse, RemotePluginCatalogError> {
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let url = if let Some(remote_plugin_id) = remote_plugin_id {
|
||||
format!("{base_url}/public/plugins/workspace/{remote_plugin_id}")
|
||||
} else {
|
||||
format!("{base_url}/public/plugins/workspace")
|
||||
};
|
||||
let request = authenticated_request(config, Method::POST, &url, auth)
|
||||
.await?
|
||||
.json(&body);
|
||||
send_and_decode(request, &url).await
|
||||
}
|
||||
|
||||
fn archive_filename(plugin_path: &Path) -> Result<String, RemotePluginCatalogError> {
|
||||
let plugin_name = plugin_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: plugin_path.to_path_buf(),
|
||||
reason: "plugin path must end in a valid UTF-8 directory name".to_string(),
|
||||
})?;
|
||||
Ok(format!("{plugin_name}.tar.gz"))
|
||||
}
|
||||
|
||||
fn archive_plugin_for_upload(plugin_path: &Path) -> Result<Vec<u8>, RemotePluginCatalogError> {
|
||||
archive_plugin_for_upload_with_limit(plugin_path, REMOTE_PLUGIN_SHARE_MAX_ARCHIVE_BYTES)
|
||||
}
|
||||
|
||||
fn archive_plugin_for_upload_with_limit(
|
||||
plugin_path: &Path,
|
||||
max_bytes: usize,
|
||||
) -> Result<Vec<u8>, RemotePluginCatalogError> {
|
||||
pack_plugin_bundle_tar_gz(plugin_path, max_bytes).map_err(|err| match err {
|
||||
PluginBundlePackError::InvalidPluginPath { path, reason } => {
|
||||
RemotePluginCatalogError::InvalidPluginPath { path, reason }
|
||||
}
|
||||
PluginBundlePackError::ArchiveTooLarge { bytes, max_bytes } => {
|
||||
RemotePluginCatalogError::ArchiveTooLarge { bytes, max_bytes }
|
||||
}
|
||||
PluginBundlePackError::Io { source } => RemotePluginCatalogError::Archive {
|
||||
path: plugin_path.to_path_buf(),
|
||||
source,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_and_expect_status(
|
||||
request: RequestBuilder,
|
||||
url_for_error: &str,
|
||||
expected_statuses: &[StatusCode],
|
||||
) -> Result<(), RemotePluginCatalogError> {
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|source| RemotePluginCatalogError::Request {
|
||||
url: url_for_error.to_string(),
|
||||
source,
|
||||
})?;
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|source| RemotePluginCatalogError::Request {
|
||||
url: url_for_error.to_string(),
|
||||
source,
|
||||
})?;
|
||||
if !expected_statuses.contains(&status) {
|
||||
return Err(RemotePluginCatalogError::UnexpectedStatus {
|
||||
url: url_for_error.to_string(),
|
||||
status,
|
||||
body,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
472
codex-rs/core-plugins/src/remote/share/checkout.rs
Normal file
472
codex-rs/core-plugins/src/remote/share/checkout.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
|
||||
use super::super::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
|
||||
use super::super::RemotePluginCatalogError;
|
||||
use super::super::RemotePluginServiceConfig;
|
||||
use super::local_paths;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
|
||||
const PERSONAL_MARKETPLACE_NAME: &str = "codex-curated";
|
||||
const PERSONAL_MARKETPLACE_DISPLAY_NAME: &str = "Personal";
|
||||
const PERSONAL_MARKETPLACE_RELATIVE_PATH: &str = ".agents/plugins/marketplace.json";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemotePluginShareCheckoutResult {
|
||||
pub remote_plugin_id: String,
|
||||
pub plugin_id: String,
|
||||
pub plugin_name: String,
|
||||
pub plugin_path: AbsolutePathBuf,
|
||||
pub marketplace_name: String,
|
||||
pub marketplace_path: AbsolutePathBuf,
|
||||
pub remote_version: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn checkout_remote_plugin_share(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<RemotePluginShareCheckoutResult, RemotePluginCatalogError> {
|
||||
let config = &config.for_current_account();
|
||||
let detail = super::super::fetch_remote_plugin_detail_with_download_urls(
|
||||
config,
|
||||
auth,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME,
|
||||
remote_plugin_id,
|
||||
)
|
||||
.await?;
|
||||
let plugin_name = detail.summary.name.clone();
|
||||
let remote_version = detail.release_version.clone();
|
||||
validate_plugin_segment(&plugin_name, "plugin name").map_err(|reason| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"remote plugin `{remote_plugin_id}` returned invalid plugin name: {reason}"
|
||||
))
|
||||
})?;
|
||||
if !is_checkout_supported_share_marketplace(&detail.marketplace_name)
|
||||
|| detail.summary.share_context.is_none()
|
||||
{
|
||||
return Err(RemotePluginCatalogError::PluginShareCheckoutNotAvailable {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let home = crate::marketplace::home_dir().ok_or_else(|| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(
|
||||
"could not determine home directory for personal plugin marketplace".to_string(),
|
||||
)
|
||||
})?;
|
||||
let home = AbsolutePathBuf::try_from(home).map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to resolve home directory for personal plugin marketplace: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let local_paths = load_share_local_paths_for_checkout(codex_home)?;
|
||||
let (local_plugin_path, already_checked_out) =
|
||||
editable_plugin_path_for_checkout(&home, &plugin_name, remote_plugin_id, &local_paths)?;
|
||||
|
||||
let mut created_checkout_path = false;
|
||||
if !already_checked_out {
|
||||
let bundle = crate::remote_bundle::validate_remote_plugin_bundle(
|
||||
remote_plugin_id,
|
||||
&detail.marketplace_name,
|
||||
&plugin_name,
|
||||
detail.release_version.as_deref(),
|
||||
detail.bundle_download_url.as_deref(),
|
||||
/*app_manifest*/ None,
|
||||
)
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to prepare remote plugin bundle checkout: {err}"
|
||||
))
|
||||
})?;
|
||||
crate::remote_bundle::download_and_extract_remote_plugin_bundle_to_path(
|
||||
config,
|
||||
bundle,
|
||||
local_plugin_path.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to check out remote plugin bundle: {err}"
|
||||
))
|
||||
})?;
|
||||
created_checkout_path = true;
|
||||
}
|
||||
|
||||
let marketplace = match update_personal_marketplace(
|
||||
&home,
|
||||
&plugin_name,
|
||||
&local_plugin_path,
|
||||
detail.summary.install_policy,
|
||||
detail.summary.auth_policy,
|
||||
detail
|
||||
.summary
|
||||
.interface
|
||||
.as_ref()
|
||||
.and_then(|interface| interface.category.clone()),
|
||||
) {
|
||||
Ok(marketplace) => marketplace,
|
||||
Err(err) => {
|
||||
return Err(clean_up_created_checkout_path(
|
||||
created_checkout_path,
|
||||
&local_plugin_path,
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = local_paths::record_plugin_share_local_path(
|
||||
codex_home,
|
||||
remote_plugin_id,
|
||||
local_plugin_path.clone(),
|
||||
) {
|
||||
let err = RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to record plugin share local path mapping: {err}"
|
||||
));
|
||||
return Err(clean_up_created_checkout_path(
|
||||
created_checkout_path,
|
||||
&local_plugin_path,
|
||||
err,
|
||||
));
|
||||
}
|
||||
|
||||
let plugin_id = PluginId::new(plugin_name.clone(), marketplace.name.clone())
|
||||
.map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to build checked out plugin id: {err}"
|
||||
))
|
||||
})?
|
||||
.as_key();
|
||||
|
||||
Ok(RemotePluginShareCheckoutResult {
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
plugin_id,
|
||||
plugin_name,
|
||||
plugin_path: local_plugin_path,
|
||||
marketplace_name: marketplace.name,
|
||||
marketplace_path: marketplace.path,
|
||||
remote_version,
|
||||
})
|
||||
}
|
||||
|
||||
fn is_checkout_supported_share_marketplace(marketplace_name: &str) -> bool {
|
||||
matches!(
|
||||
marketplace_name,
|
||||
REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME
|
||||
| REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME
|
||||
)
|
||||
}
|
||||
|
||||
fn load_share_local_paths_for_checkout(
|
||||
codex_home: &Path,
|
||||
) -> Result<BTreeMap<String, AbsolutePathBuf>, RemotePluginCatalogError> {
|
||||
match local_paths::load_plugin_share_local_paths(codex_home) {
|
||||
Ok(paths) => Ok(paths),
|
||||
Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()),
|
||||
Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to load plugin share local path mapping: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn editable_plugin_path_for_checkout(
|
||||
home: &AbsolutePathBuf,
|
||||
plugin_name: &str,
|
||||
remote_plugin_id: &str,
|
||||
local_paths: &BTreeMap<String, AbsolutePathBuf>,
|
||||
) -> Result<(AbsolutePathBuf, bool), RemotePluginCatalogError> {
|
||||
if let Some(existing_path) = local_paths.get(remote_plugin_id)
|
||||
&& existing_path.as_path().exists()
|
||||
{
|
||||
ensure_path_can_be_listed_in_personal_marketplace(home, existing_path)?;
|
||||
return Ok((existing_path.clone(), true));
|
||||
}
|
||||
|
||||
let local_plugin_path = local_paths
|
||||
.get(remote_plugin_id)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| home.join("plugins").join(plugin_name));
|
||||
ensure_path_can_be_listed_in_personal_marketplace(home, &local_plugin_path)?;
|
||||
|
||||
if local_plugin_path.as_path().exists() {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: format!(
|
||||
"cannot check out remote plugin `{remote_plugin_id}` because the local plugin path already exists"
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
Ok((local_plugin_path, false))
|
||||
}
|
||||
|
||||
fn clean_up_created_checkout_path(
|
||||
created_checkout_path: bool,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
original_err: RemotePluginCatalogError,
|
||||
) -> RemotePluginCatalogError {
|
||||
if !created_checkout_path {
|
||||
return original_err;
|
||||
}
|
||||
|
||||
match remove_created_checkout_path(local_plugin_path) {
|
||||
Ok(()) => original_err,
|
||||
Err(cleanup_err) => RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"{original_err}; additionally failed to clean up checked out plugin path `{}`: {cleanup_err}",
|
||||
local_plugin_path.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_created_checkout_path(local_plugin_path: &AbsolutePathBuf) -> io::Result<()> {
|
||||
if local_plugin_path.as_path().is_dir() {
|
||||
fs::remove_dir_all(local_plugin_path.as_path())
|
||||
} else {
|
||||
fs::remove_file(local_plugin_path.as_path())
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_path_can_be_listed_in_personal_marketplace(
|
||||
home: &AbsolutePathBuf,
|
||||
path: &AbsolutePathBuf,
|
||||
) -> Result<(), RemotePluginCatalogError> {
|
||||
personal_marketplace_relative_plugin_path(home, path).map(|_| ())
|
||||
}
|
||||
|
||||
struct PersonalMarketplaceUpdate {
|
||||
name: String,
|
||||
path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
fn update_personal_marketplace(
|
||||
home: &AbsolutePathBuf,
|
||||
plugin_name: &str,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
install_policy: PluginInstallPolicy,
|
||||
auth_policy: PluginAuthPolicy,
|
||||
category: Option<String>,
|
||||
) -> Result<PersonalMarketplaceUpdate, RemotePluginCatalogError> {
|
||||
let marketplace_path = home.join(PERSONAL_MARKETPLACE_RELATIVE_PATH);
|
||||
let relative_plugin_path = personal_marketplace_relative_plugin_path(home, local_plugin_path)?;
|
||||
let mut marketplace = read_or_create_personal_marketplace(marketplace_path.as_path())?;
|
||||
let Some(marketplace_object) = marketplace.as_object_mut() else {
|
||||
return Err(invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"personal marketplace file must contain a JSON object",
|
||||
));
|
||||
};
|
||||
let marketplace_name = marketplace_object
|
||||
.entry("name")
|
||||
.or_insert_with(|| json!(PERSONAL_MARKETPLACE_NAME))
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"marketplace name must be a string",
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
validate_plugin_segment(&marketplace_name, "marketplace name").map_err(|reason| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
&format!("marketplace name is invalid: {reason}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
let plugins = marketplace_object
|
||||
.entry("plugins")
|
||||
.or_insert_with(|| json!([]))
|
||||
.as_array_mut()
|
||||
.ok_or_else(|| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
"marketplace plugins must be an array",
|
||||
)
|
||||
})?;
|
||||
|
||||
let new_entry = personal_marketplace_plugin_entry(
|
||||
plugin_name,
|
||||
&relative_plugin_path,
|
||||
install_policy,
|
||||
auth_policy,
|
||||
category,
|
||||
);
|
||||
|
||||
if let Some(existing_entry) = plugins
|
||||
.iter_mut()
|
||||
.find(|entry| entry.get("name").and_then(JsonValue::as_str) == Some(plugin_name))
|
||||
{
|
||||
let existing_path = existing_entry
|
||||
.get("source")
|
||||
.and_then(|source| source.get("path"))
|
||||
.and_then(JsonValue::as_str);
|
||||
if existing_path != Some(relative_plugin_path.as_str()) {
|
||||
return Err(invalid_marketplace_file(
|
||||
marketplace_path.as_path(),
|
||||
&format!(
|
||||
"marketplace already contains plugin `{plugin_name}` with a different source path"
|
||||
),
|
||||
));
|
||||
}
|
||||
*existing_entry = new_entry;
|
||||
} else {
|
||||
plugins.push(new_entry);
|
||||
}
|
||||
|
||||
let contents = serde_json::to_string_pretty(&marketplace)
|
||||
.map_err(|err| RemotePluginCatalogError::UnexpectedResponse(err.to_string()))?;
|
||||
write_json_atomically(marketplace_path.as_path(), &format!("{contents}\n")).map_err(|err| {
|
||||
RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to update personal plugin marketplace: {err}"
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(PersonalMarketplaceUpdate {
|
||||
name: marketplace_name,
|
||||
path: marketplace_path,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_or_create_personal_marketplace(
|
||||
marketplace_path: &Path,
|
||||
) -> Result<JsonValue, RemotePluginCatalogError> {
|
||||
match std::fs::read_to_string(marketplace_path) {
|
||||
Ok(contents) => serde_json::from_str(&contents).map_err(|err| {
|
||||
invalid_marketplace_file(
|
||||
marketplace_path,
|
||||
&format!("failed to parse personal marketplace file: {err}"),
|
||||
)
|
||||
}),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(json!({
|
||||
"name": PERSONAL_MARKETPLACE_NAME,
|
||||
"interface": {
|
||||
"displayName": PERSONAL_MARKETPLACE_DISPLAY_NAME,
|
||||
},
|
||||
"plugins": [],
|
||||
})),
|
||||
Err(err) => Err(RemotePluginCatalogError::UnexpectedResponse(format!(
|
||||
"failed to read personal plugin marketplace: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn personal_marketplace_plugin_entry(
|
||||
plugin_name: &str,
|
||||
relative_plugin_path: &str,
|
||||
install_policy: PluginInstallPolicy,
|
||||
auth_policy: PluginAuthPolicy,
|
||||
category: Option<String>,
|
||||
) -> JsonValue {
|
||||
let mut entry = json!({
|
||||
"name": plugin_name,
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": relative_plugin_path,
|
||||
},
|
||||
"policy": {
|
||||
"installation": plugin_install_policy_value(install_policy),
|
||||
"authentication": plugin_auth_policy_value(auth_policy),
|
||||
},
|
||||
});
|
||||
if let Some(category) = category
|
||||
&& !category.trim().is_empty()
|
||||
&& let Some(object) = entry.as_object_mut()
|
||||
{
|
||||
object.insert("category".to_string(), json!(category));
|
||||
}
|
||||
entry
|
||||
}
|
||||
|
||||
fn plugin_install_policy_value(policy: PluginInstallPolicy) -> &'static str {
|
||||
match policy {
|
||||
PluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
|
||||
PluginInstallPolicy::Available => "AVAILABLE",
|
||||
PluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_auth_policy_value(policy: PluginAuthPolicy) -> &'static str {
|
||||
match policy {
|
||||
PluginAuthPolicy::OnInstall => "ON_INSTALL",
|
||||
PluginAuthPolicy::OnUse => "ON_USE",
|
||||
}
|
||||
}
|
||||
|
||||
fn personal_marketplace_relative_plugin_path(
|
||||
home: &AbsolutePathBuf,
|
||||
local_plugin_path: &AbsolutePathBuf,
|
||||
) -> Result<String, RemotePluginCatalogError> {
|
||||
let relative = local_plugin_path
|
||||
.as_path()
|
||||
.strip_prefix(home.as_path())
|
||||
.map_err(|_| RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path must be inside the home directory to be listed in the personal marketplace".to_string(),
|
||||
})?;
|
||||
let mut segments = Vec::new();
|
||||
for component in relative.components() {
|
||||
match component {
|
||||
Component::Normal(segment) => {
|
||||
let segment = segment.to_str().ok_or_else(|| {
|
||||
RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path contains non-UTF-8 segments".to_string(),
|
||||
}
|
||||
})?;
|
||||
segments.push(segment.to_string());
|
||||
}
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason:
|
||||
"local plugin path cannot be represented as a personal marketplace path"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if segments.is_empty() {
|
||||
return Err(RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: local_plugin_path.to_path_buf(),
|
||||
reason: "local plugin path must not be the home directory".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(format!("./{}", segments.join("/")))
|
||||
}
|
||||
|
||||
fn invalid_marketplace_file(path: &Path, message: &str) -> RemotePluginCatalogError {
|
||||
RemotePluginCatalogError::InvalidPluginPath {
|
||||
path: path.to_path_buf(),
|
||||
reason: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_json_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
|
||||
let parent = write_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path {} has no parent directory", write_path.display()),
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(contents.as_bytes())?;
|
||||
tmp.persist(write_path).map_err(|err| err.error)?;
|
||||
Ok(())
|
||||
}
|
||||
124
codex-rs/core-plugins/src/remote/share/local_paths.rs
Normal file
124
codex-rs/core-plugins/src/remote/share/local_paths.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const PLUGIN_SHARE_LOCAL_PATHS_FILE: &str = ".tmp/plugin-share-local-paths-v1.json";
|
||||
static PLUGIN_SHARE_LOCAL_PATHS_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PluginShareLocalPaths {
|
||||
#[serde(default)]
|
||||
local_plugin_paths_by_remote_plugin_id: BTreeMap<String, AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) fn load_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
read_plugin_share_local_paths(codex_home)
|
||||
}
|
||||
|
||||
pub(crate) fn record_plugin_share_local_path(
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
plugin_path: AbsolutePathBuf,
|
||||
) -> io::Result<()> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?;
|
||||
mapping.insert(remote_plugin_id.to_string(), plugin_path);
|
||||
write_plugin_share_local_paths(codex_home, mapping)
|
||||
}
|
||||
|
||||
pub(crate) fn remove_plugin_share_local_path(
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> io::Result<()> {
|
||||
let _guard = lock_plugin_share_local_paths()?;
|
||||
let mut mapping = read_plugin_share_local_paths_for_update(codex_home)?;
|
||||
mapping.remove(remote_plugin_id);
|
||||
write_plugin_share_local_paths(codex_home, mapping)
|
||||
}
|
||||
|
||||
fn lock_plugin_share_local_paths() -> io::Result<std::sync::MutexGuard<'static, ()>> {
|
||||
PLUGIN_SHARE_LOCAL_PATHS_LOCK
|
||||
.lock()
|
||||
.map_err(|err| io::Error::other(format!("plugin share local path lock poisoned: {err}")))
|
||||
}
|
||||
|
||||
fn read_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
let path = plugin_share_local_paths_path(codex_home);
|
||||
let contents = match std::fs::read_to_string(&path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let mapping = serde_json::from_str::<PluginShareLocalPaths>(&contents).map_err(|err| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"failed to parse plugin share local path mapping {}: {err}",
|
||||
path.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(mapping.local_plugin_paths_by_remote_plugin_id)
|
||||
}
|
||||
|
||||
fn read_plugin_share_local_paths_for_update(
|
||||
codex_home: &Path,
|
||||
) -> io::Result<BTreeMap<String, AbsolutePathBuf>> {
|
||||
match read_plugin_share_local_paths(codex_home) {
|
||||
Ok(mapping) => Ok(mapping),
|
||||
// This is a best-effort cache under .tmp, so malformed state should not
|
||||
// permanently block future share saves or deletes.
|
||||
Err(err) if err.kind() == io::ErrorKind::InvalidData => Ok(BTreeMap::new()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_plugin_share_local_paths(
|
||||
codex_home: &Path,
|
||||
mapping: BTreeMap<String, AbsolutePathBuf>,
|
||||
) -> io::Result<()> {
|
||||
let path = plugin_share_local_paths_path(codex_home);
|
||||
if mapping.is_empty() {
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
let contents = serde_json::to_string_pretty(&PluginShareLocalPaths {
|
||||
local_plugin_paths_by_remote_plugin_id: mapping,
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
write_atomically(&path, &format!("{contents}\n"))
|
||||
}
|
||||
|
||||
fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
|
||||
let parent = write_path.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path {} has no parent directory", write_path.display()),
|
||||
)
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
|
||||
tmp.write_all(contents.as_bytes())?;
|
||||
tmp.persist(write_path).map_err(|err| err.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plugin_share_local_paths_path(codex_home: &Path) -> std::path::PathBuf {
|
||||
codex_home.join(PLUGIN_SHARE_LOCAL_PATHS_FILE)
|
||||
}
|
||||
824
codex-rs/core-plugins/src/remote/share/tests.rs
Normal file
824
codex-rs/core-plugins/src/remote/share/tests.rs
Normal file
@@ -0,0 +1,824 @@
|
||||
use super::*;
|
||||
use crate::test_support::recorded_http_client_urls;
|
||||
use crate::test_support::recording_remote_plugin_service_config;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_app_server_protocol::PluginInterface;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_json;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
use wiremock::matchers::query_param_is_missing;
|
||||
|
||||
fn test_config(server: &MockServer) -> RemotePluginServiceConfig {
|
||||
RemotePluginServiceConfig::new(
|
||||
format!("{}/backend-api", server.uri()),
|
||||
crate::test_support::test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn test_auth() -> CodexAuth {
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing()
|
||||
}
|
||||
|
||||
fn write_file(path: &Path, contents: &str) {
|
||||
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
|
||||
fs::write(path, contents).unwrap();
|
||||
}
|
||||
|
||||
fn write_test_plugin(root: &Path, plugin_name: &str) -> PathBuf {
|
||||
let plugin_path = root.join(plugin_name);
|
||||
write_file(
|
||||
&plugin_path.join(".codex-plugin/plugin.json"),
|
||||
&format!(r#"{{"name":"{plugin_name}"}}"#),
|
||||
);
|
||||
write_file(
|
||||
&plugin_path.join("skills/example/SKILL.md"),
|
||||
"# Example\n\nA test skill.\n",
|
||||
);
|
||||
plugin_path
|
||||
}
|
||||
|
||||
fn write_plugin_share_local_path_mapping(
|
||||
codex_home: &Path,
|
||||
remote_plugin_id: &str,
|
||||
plugin_path: &AbsolutePathBuf,
|
||||
) {
|
||||
write_file(
|
||||
&codex_home.join(".tmp/plugin-share-local-paths-v1.json"),
|
||||
&format!(
|
||||
"{}\n",
|
||||
serde_json::to_string_pretty(&json!({
|
||||
"localPluginPathsByRemotePluginId": {
|
||||
remote_plugin_id: plugin_path,
|
||||
},
|
||||
}))
|
||||
.unwrap()
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn archive_file_entries(archive_bytes: &[u8]) -> BTreeMap<String, Vec<u8>> {
|
||||
let decoder = flate2::read::GzDecoder::new(archive_bytes);
|
||||
let mut archive = tar::Archive::new(decoder);
|
||||
archive
|
||||
.entries()
|
||||
.unwrap()
|
||||
.filter_map(|entry| {
|
||||
let mut entry = entry.unwrap();
|
||||
if !entry.header().entry_type().is_file() {
|
||||
return None;
|
||||
}
|
||||
let path = entry.path().unwrap().to_string_lossy().into_owned();
|
||||
let mut contents = Vec::new();
|
||||
entry.read_to_end(&mut contents).unwrap();
|
||||
Some((path, contents))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn remote_plugin_json(plugin_id: &str) -> serde_json::Value {
|
||||
json!({
|
||||
"id": plugin_id,
|
||||
"name": "demo-plugin",
|
||||
"scope": "WORKSPACE",
|
||||
"discoverability": "PRIVATE",
|
||||
"installation_policy": "AVAILABLE",
|
||||
"authentication_policy": "ON_USE",
|
||||
"release": {
|
||||
"version": "0.1.0",
|
||||
"display_name": "Demo Plugin",
|
||||
"description": "Demo plugin description",
|
||||
"interface": {
|
||||
"short_description": "A demo plugin",
|
||||
"capabilities": ["Read", "Write"]
|
||||
},
|
||||
"skills": []
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn remote_plugin_json_with_share_url_and_principals(
|
||||
plugin_id: &str,
|
||||
share_url: Option<&str>,
|
||||
share_principals: serde_json::Value,
|
||||
) -> serde_json::Value {
|
||||
let mut plugin = remote_plugin_json(plugin_id);
|
||||
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
|
||||
}
|
||||
|
||||
fn installed_remote_plugin_json(plugin_id: &str) -> serde_json::Value {
|
||||
let mut plugin = remote_plugin_json(plugin_id);
|
||||
let serde_json::Value::Object(fields) = &mut plugin else {
|
||||
unreachable!("plugin json should be an object");
|
||||
};
|
||||
fields.insert("enabled".to_string(), json!(true));
|
||||
fields.insert("disabled_skill_names".to_string(), json!([]));
|
||||
plugin
|
||||
}
|
||||
|
||||
fn empty_pagination_json() -> serde_json::Value {
|
||||
json!({
|
||||
"next_page_token": null
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_plugin_interface() -> PluginInterface {
|
||||
PluginInterface {
|
||||
display_name: Some("Demo Plugin".to_string()),
|
||||
short_description: Some("A demo plugin".to_string()),
|
||||
long_description: None,
|
||||
developer_name: None,
|
||||
category: None,
|
||||
capabilities: vec!["Read".to_string(), "Write".to_string()],
|
||||
website_url: None,
|
||||
privacy_policy_url: None,
|
||||
terms_of_service_url: None,
|
||||
default_prompt: None,
|
||||
brand_color: None,
|
||||
composer_icon: None,
|
||||
composer_icon_url: None,
|
||||
logo: None,
|
||||
logo_dark: None,
|
||||
logo_url: None,
|
||||
logo_url_dark: None,
|
||||
screenshots: Vec::new(),
|
||||
screenshot_urls: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_remote_plugin_share_creates_workspace_plugin() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let plugin_path =
|
||||
AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap();
|
||||
let archive_size = archive_plugin_for_upload(plugin_path.as_path())
|
||||
.unwrap()
|
||||
.len();
|
||||
let server = MockServer::start().await;
|
||||
let (config, selected_urls) =
|
||||
recording_remote_plugin_service_config(format!("{}/backend-api", server.uri()));
|
||||
let auth = test_auth();
|
||||
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace/upload-url"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.and(body_json(json!({
|
||||
"filename": "demo-plugin.tar.gz",
|
||||
"mime_type": "application/gzip",
|
||||
"size_bytes": archive_size,
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
|
||||
"file_id": "file_123",
|
||||
"upload_url": format!("{}/upload/file_123", server.uri()),
|
||||
"etag": "\"upload_etag_123\"",
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("PUT"))
|
||||
.and(path("/upload/file_123"))
|
||||
.and(header("x-ms-blob-type", "BlockBlob"))
|
||||
.and(header("content-type", "application/gzip"))
|
||||
.respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_123\""))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.and(body_json(json!({
|
||||
"file_id": "file_123",
|
||||
"etag": "\"upload_etag_123\"",
|
||||
"discoverability": "UNLISTED",
|
||||
"share_targets": [
|
||||
{
|
||||
"principal_type": "user",
|
||||
"principal_id": "user-1",
|
||||
"role": "reader",
|
||||
},
|
||||
{
|
||||
"principal_type": "workspace",
|
||||
"principal_id": "account_id",
|
||||
"role": "reader",
|
||||
},
|
||||
],
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
|
||||
"plugin_id": "plugins_123",
|
||||
"share_url": "https://chatgpt.example/plugins/share/share-key-1",
|
||||
"can_publish_to_workspace": true,
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let result = save_remote_plugin_share(
|
||||
&config,
|
||||
Some(&auth),
|
||||
codex_home.path(),
|
||||
&plugin_path,
|
||||
/*remote_plugin_id*/ None,
|
||||
RemotePluginShareAccessPolicy {
|
||||
discoverability: Some(RemotePluginShareDiscoverability::Unlisted),
|
||||
share_targets: Some(vec![RemotePluginShareTarget {
|
||||
principal_type: RemotePluginSharePrincipalType::User,
|
||||
principal_id: "user-1".to_string(),
|
||||
role: RemotePluginShareTargetRole::Reader,
|
||||
}]),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
RemotePluginShareSaveResult {
|
||||
remote_plugin_id: "plugins_123".to_string(),
|
||||
share_url: Some("https://chatgpt.example/plugins/share/share-key-1".to_string()),
|
||||
can_publish_to_workspace: Some(true),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(),
|
||||
BTreeMap::from([("plugins_123".to_string(), plugin_path)])
|
||||
);
|
||||
assert_eq!(
|
||||
recorded_http_client_urls(&selected_urls),
|
||||
vec![
|
||||
format!(
|
||||
"{}/backend-api/public/plugins/workspace/upload-url",
|
||||
server.uri()
|
||||
),
|
||||
format!("{}/upload/file_123", server.uri()),
|
||||
format!("{}/backend-api/public/plugins/workspace", server.uri()),
|
||||
]
|
||||
);
|
||||
|
||||
let requests = server.received_requests().await.unwrap_or_default();
|
||||
let upload_request = requests
|
||||
.iter()
|
||||
.find(|request| request.method == "PUT" && request.url.path() == "/upload/file_123")
|
||||
.unwrap();
|
||||
let archive_files = archive_file_entries(&upload_request.body);
|
||||
assert_eq!(
|
||||
archive_files
|
||||
.get(".codex-plugin/plugin.json")
|
||||
.map(Vec::as_slice),
|
||||
Some(br#"{"name":"demo-plugin"}"#.as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
archive_files
|
||||
.get("skills/example/SKILL.md")
|
||||
.map(Vec::as_slice),
|
||||
Some(b"# Example\n\nA test skill.\n".as_slice())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_plugin_for_upload_rejects_archives_over_limit() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
|
||||
write_file(
|
||||
&plugin_path.join("large.txt"),
|
||||
&"0123456789abcdef".repeat(1024),
|
||||
);
|
||||
|
||||
let err = archive_plugin_for_upload_with_limit(&plugin_path, /*max_bytes*/ 16)
|
||||
.expect_err("oversized plugin archive should fail");
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
RemotePluginCatalogError::ArchiveTooLarge { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_plugin_for_upload_places_manifest_at_archive_root() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
|
||||
|
||||
let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap();
|
||||
let archive_files = archive_file_entries(&archive_bytes);
|
||||
|
||||
assert_eq!(
|
||||
archive_files.keys().cloned().collect::<Vec<_>>(),
|
||||
vec![
|
||||
".codex-plugin/plugin.json".to_string(),
|
||||
"skills/example/SKILL.md".to_string()
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
archive_files
|
||||
.get(".codex-plugin/plugin.json")
|
||||
.map(Vec::as_slice),
|
||||
Some(br#"{"name":"demo-plugin"}"#.as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
archive_files
|
||||
.get("skills/example/SKILL.md")
|
||||
.map(Vec::as_slice),
|
||||
Some(b"# Example\n\nA test skill.\n".as_slice())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_plugin_for_upload_round_trips_through_plugin_bundle_archive_with_long_paths() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let plugin_path = write_test_plugin(temp_dir.path(), "demo-plugin");
|
||||
let long_skill_path = Path::new("skills")
|
||||
.join(["segment"; 40].join("/"))
|
||||
.join("SKILL.md");
|
||||
write_file(&plugin_path.join(&long_skill_path), "# Long path skill\n");
|
||||
|
||||
let archive_bytes = archive_plugin_for_upload(&plugin_path).unwrap();
|
||||
let destination = TempDir::new().unwrap();
|
||||
crate::plugin_bundle_archive::unpack_plugin_bundle_tar_gz(
|
||||
&archive_bytes,
|
||||
destination.path(),
|
||||
/*max_total_bytes*/ 1024 * 1024,
|
||||
)
|
||||
.expect("extract shared plugin archive");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(destination.path().join(".codex-plugin/plugin.json")).unwrap(),
|
||||
r#"{"name":"demo-plugin"}"#
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(destination.path().join(long_skill_path)).unwrap(),
|
||||
"# Long path skill\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn save_remote_plugin_share_updates_existing_workspace_plugin() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let plugin_path =
|
||||
AbsolutePathBuf::try_from(write_test_plugin(temp_dir.path(), "demo-plugin")).unwrap();
|
||||
let archive_size = archive_plugin_for_upload(plugin_path.as_path())
|
||||
.unwrap()
|
||||
.len();
|
||||
let server = MockServer::start().await;
|
||||
let config = test_config(&server);
|
||||
let auth = test_auth();
|
||||
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace/upload-url"))
|
||||
.and(body_json(json!({
|
||||
"filename": "demo-plugin.tar.gz",
|
||||
"mime_type": "application/gzip",
|
||||
"size_bytes": archive_size,
|
||||
"plugin_id": "plugins_123",
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
|
||||
"file_id": "file_456",
|
||||
"upload_url": format!("{}/upload/file_456", server.uri()),
|
||||
"etag": "\"upload_etag_456\"",
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("PUT"))
|
||||
.and(path("/upload/file_456"))
|
||||
.respond_with(ResponseTemplate::new(201).insert_header("etag", "\"blob_etag_456\""))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace/plugins_123"))
|
||||
.and(body_json(json!({
|
||||
"file_id": "file_456",
|
||||
"etag": "\"upload_etag_456\"",
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugin_id": "plugins_123",
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let result = save_remote_plugin_share(
|
||||
&config,
|
||||
Some(&auth),
|
||||
codex_home.path(),
|
||||
&plugin_path,
|
||||
Some("plugins_123"),
|
||||
RemotePluginShareAccessPolicy::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
RemotePluginShareSaveResult {
|
||||
remote_plugin_id: "plugins_123".to_string(),
|
||||
share_url: None,
|
||||
can_publish_to_workspace: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_remote_plugin_share_targets_updates_targets() {
|
||||
let server = MockServer::start().await;
|
||||
let config = test_config(&server);
|
||||
let auth = test_auth();
|
||||
|
||||
Mock::given(method("PUT"))
|
||||
.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",
|
||||
},
|
||||
],
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"principals": [
|
||||
{
|
||||
"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)
|
||||
.await;
|
||||
|
||||
let result = update_remote_plugin_share_targets(
|
||||
&config,
|
||||
Some(&auth),
|
||||
"plugins_123",
|
||||
vec![
|
||||
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();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
RemotePluginShareUpdateTargetsResult {
|
||||
principals: vec![
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_remote_plugin_shares_fetches_created_workspace_plugins() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let local_plugin_path =
|
||||
AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap();
|
||||
write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path);
|
||||
let server = MockServer::start().await;
|
||||
let config = test_config(&server);
|
||||
let auth = test_auth();
|
||||
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/workspace/created"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.and(query_param(
|
||||
"limit",
|
||||
REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(),
|
||||
))
|
||||
.and(query_param_is_missing("pageToken"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [remote_plugin_json_with_share_url_and_principals(
|
||||
"plugins_123",
|
||||
Some("https://chatgpt.example/plugins/share/share-key-1"),
|
||||
json!([
|
||||
{
|
||||
"principal_type": "user",
|
||||
"principal_id": "user-owner",
|
||||
"role": "owner",
|
||||
"name": "Owner",
|
||||
},
|
||||
{
|
||||
"principal_type": "user",
|
||||
"principal_id": "user-reader",
|
||||
"role": "reader",
|
||||
"name": "Reader",
|
||||
},
|
||||
]),
|
||||
)],
|
||||
"pagination": {
|
||||
"next_page_token": "page-2"
|
||||
},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/workspace/created"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.and(query_param(
|
||||
"limit",
|
||||
REMOTE_PLUGIN_LIST_PAGE_LIMIT.to_string(),
|
||||
))
|
||||
.and(query_param("pageToken", "page-2"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [remote_plugin_json_with_share_url_and_principals(
|
||||
"plugins_456",
|
||||
/*share_url*/ None,
|
||||
json!([
|
||||
{
|
||||
"principal_type": "user",
|
||||
"principal_id": "user-owner",
|
||||
"role": "owner",
|
||||
"name": "Owner",
|
||||
},
|
||||
{
|
||||
"principal_type": "user",
|
||||
"principal_id": "user-editor",
|
||||
"role": "editor",
|
||||
"name": "Editor",
|
||||
},
|
||||
]),
|
||||
)],
|
||||
"pagination": empty_pagination_json(),
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.and(query_param("scope", "WORKSPACE"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [installed_remote_plugin_json("plugins_456")],
|
||||
"pagination": empty_pagination_json(),
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let result = list_remote_plugin_shares(&config, Some(&auth), codex_home.path())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
vec![
|
||||
RemotePluginShareSummary {
|
||||
summary: RemotePluginSummary {
|
||||
id: "demo-plugin@workspace-shared-with-me".to_string(),
|
||||
remote_plugin_id: "plugins_123".to_string(),
|
||||
version: Some("0.1.0".to_string()),
|
||||
local_version: None,
|
||||
name: "demo-plugin".to_string(),
|
||||
share_context: Some(RemotePluginShareContext {
|
||||
remote_plugin_id: "plugins_123".to_string(),
|
||||
remote_version: Some("0.1.0".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_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(),
|
||||
},
|
||||
]),
|
||||
can_publish_to_workspace: None,
|
||||
}),
|
||||
installed: false,
|
||||
installed_at: None,
|
||||
enabled: false,
|
||||
install_policy: PluginInstallPolicy::Available,
|
||||
install_policy_source: None,
|
||||
must_show_installation_interstitial: None,
|
||||
auth_policy: PluginAuthPolicy::OnUse,
|
||||
availability: PluginAvailability::Available,
|
||||
disabled_reason: None,
|
||||
eligible_plan_types: None,
|
||||
interface: Some(expected_plugin_interface()),
|
||||
keywords: Vec::new(),
|
||||
},
|
||||
local_plugin_path: Some(local_plugin_path),
|
||||
},
|
||||
RemotePluginShareSummary {
|
||||
summary: RemotePluginSummary {
|
||||
id: "demo-plugin@workspace-shared-with-me".to_string(),
|
||||
remote_plugin_id: "plugins_456".to_string(),
|
||||
version: Some("0.1.0".to_string()),
|
||||
local_version: Some("0.1.0".to_string()),
|
||||
name: "demo-plugin".to_string(),
|
||||
share_context: Some(RemotePluginShareContext {
|
||||
remote_plugin_id: "plugins_456".to_string(),
|
||||
remote_version: Some("0.1.0".to_string()),
|
||||
discoverability: RemotePluginShareDiscoverability::Private,
|
||||
share_url: None,
|
||||
creator_account_user_id: None,
|
||||
creator_name: None,
|
||||
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(),
|
||||
},
|
||||
]),
|
||||
can_publish_to_workspace: None,
|
||||
}),
|
||||
installed: true,
|
||||
installed_at: None,
|
||||
enabled: true,
|
||||
install_policy: PluginInstallPolicy::Available,
|
||||
install_policy_source: None,
|
||||
must_show_installation_interstitial: None,
|
||||
auth_policy: PluginAuthPolicy::OnUse,
|
||||
availability: PluginAvailability::Available,
|
||||
disabled_reason: None,
|
||||
eligible_plan_types: None,
|
||||
interface: Some(expected_plugin_interface()),
|
||||
keywords: Vec::new(),
|
||||
},
|
||||
local_plugin_path: None,
|
||||
}
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_remote_plugin_share_deletes_workspace_plugin() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let local_plugin_path =
|
||||
AbsolutePathBuf::try_from(codex_home.path().join("local-plugin")).unwrap();
|
||||
write_plugin_share_local_path_mapping(codex_home.path(), "plugins_123", &local_plugin_path);
|
||||
let server = MockServer::start().await;
|
||||
let config = test_config(&server);
|
||||
let auth = test_auth();
|
||||
|
||||
Mock::given(method("DELETE"))
|
||||
.and(path("/backend-api/public/plugins/workspace/plugins_123"))
|
||||
.and(header("authorization", "Bearer Access Token"))
|
||||
.and(header("chatgpt-account-id", "account_id"))
|
||||
.respond_with(ResponseTemplate::new(204))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
delete_remote_plugin_share(&config, Some(&auth), codex_home.path(), "plugins_123")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
local_paths::load_plugin_share_local_paths(codex_home.path()).unwrap(),
|
||||
BTreeMap::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoked_success_body_is_a_request_error() {
|
||||
for method in [Method::PUT, Method::POST] {
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}/upload", listener.local_addr().unwrap());
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Unrestricted,
|
||||
);
|
||||
let config = RemotePluginServiceConfig::new(
|
||||
url.clone(),
|
||||
crate::test_support::test_http_client_factory().with_network_policy(policy),
|
||||
/*product_sku*/ None,
|
||||
);
|
||||
let server = async {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(socket.read_u8().await.unwrap());
|
||||
}
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\na")
|
||||
.await
|
||||
.unwrap();
|
||||
// Let the client consume the successful headers and wait for the remaining body.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 50)).await;
|
||||
controller.publish(
|
||||
controller.policy().revision(),
|
||||
codex_http_client::DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
);
|
||||
};
|
||||
let operation = async {
|
||||
if method == Method::PUT {
|
||||
put_workspace_plugin_upload(&config, &url, Vec::new()).await
|
||||
} else {
|
||||
send_and_expect_status(config.http_request(method, &url), &url, &[StatusCode::OK])
|
||||
.await
|
||||
}
|
||||
};
|
||||
let (result, ()) =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), async {
|
||||
tokio::join!(operation, server)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(RemotePluginCatalogError::Request {
|
||||
source: codex_http_client::RouteAwareRequestError::Policy(
|
||||
codex_http_client::NetworkPolicyDenied::Revoked
|
||||
),
|
||||
..
|
||||
})
|
||||
),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
1154
codex-rs/core-plugins/src/remote_bundle.rs
Normal file
1154
codex-rs/core-plugins/src/remote_bundle.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
||||
//! Runtime-authenticated catalogs keep presigned bundle transfers unauthenticated.
|
||||
|
||||
use super::*;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_bundle_download_follows_redirect_without_actor_auth() {
|
||||
let origin = MockServer::start().await;
|
||||
let destination = MockServer::start().await;
|
||||
let final_url = format!("{}/bundle", destination.uri());
|
||||
Mock::given(path("/bundle"))
|
||||
.respond_with(ResponseTemplate::new(307).insert_header("location", &final_url))
|
||||
.expect(1)
|
||||
.mount(&origin)
|
||||
.await;
|
||||
Mock::given(path("/bundle"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"bundle"))
|
||||
.expect(1)
|
||||
.mount(&destination)
|
||||
.await;
|
||||
let config = RemotePluginServiceConfig::new_with_selected_runtime_auth(
|
||||
origin.uri(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
/*product_sku*/ None,
|
||||
(Default::default(), RuntimeAuthMode::AssertionOnly),
|
||||
);
|
||||
let error = download_remote_plugin_bundle_with_limit(
|
||||
&config,
|
||||
&format!("{}/bundle", origin.uri()),
|
||||
/*max_bytes*/ 64,
|
||||
)
|
||||
.await
|
||||
.expect_err("HTTP final URLs remain unsupported after following redirects");
|
||||
assert!(
|
||||
matches!(
|
||||
&error,
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }
|
||||
),
|
||||
"expected rejection of the HTTP redirect destination: {error}"
|
||||
);
|
||||
let mut requests = origin.received_requests().await.unwrap();
|
||||
requests.extend(destination.received_requests().await.unwrap());
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in requests {
|
||||
assert!(!request.headers.contains_key("authorization"));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
265
codex-rs/core-plugins/src/remote_legacy.rs
Normal file
265
codex-rs/core-plugins/src/remote_legacy.rs
Normal file
@@ -0,0 +1,265 @@
|
||||
use crate::error_subtype::http_status_sub_error_type;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use codex_http_client::RouteAwareRequestError;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::protocol::Product;
|
||||
use http::Method;
|
||||
use http::StatusCode;
|
||||
use serde::Deserialize;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
const REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const REMOTE_PLUGIN_MUTATION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RemotePluginMutationResponse {
|
||||
pub id: String,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginMutationError {
|
||||
#[error("chatgpt authentication required for remote plugin mutation")]
|
||||
AuthRequired,
|
||||
|
||||
#[error(
|
||||
"chatgpt authentication required for remote plugin mutation; api key auth is not supported"
|
||||
)]
|
||||
UnsupportedAuthMode,
|
||||
|
||||
#[error("failed to read auth token for remote plugin mutation: {0}")]
|
||||
AuthToken(#[source] std::io::Error),
|
||||
|
||||
#[error("invalid chatgpt base url for remote plugin mutation: {0}")]
|
||||
InvalidBaseUrl(#[source] url::ParseError),
|
||||
|
||||
#[error("chatgpt base url cannot be used for plugin mutation")]
|
||||
InvalidBaseUrlPath,
|
||||
|
||||
#[error("failed to send remote plugin mutation request to {url}: {source}")]
|
||||
Request {
|
||||
url: String,
|
||||
#[source]
|
||||
source: RouteAwareRequestError,
|
||||
},
|
||||
|
||||
#[error("remote plugin mutation failed with status {status} from {url}: {body}")]
|
||||
UnexpectedStatus {
|
||||
url: String,
|
||||
status: StatusCode,
|
||||
body: String,
|
||||
},
|
||||
|
||||
#[error("failed to parse remote plugin mutation response from {url}: {source}")]
|
||||
Decode {
|
||||
url: String,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"remote plugin mutation returned unexpected plugin id: expected `{expected}`, got `{actual}`"
|
||||
)]
|
||||
UnexpectedPluginId { expected: String, actual: String },
|
||||
|
||||
#[error(
|
||||
"remote plugin mutation returned unexpected enabled state for `{plugin_id}`: expected {expected_enabled}, got {actual_enabled}"
|
||||
)]
|
||||
UnexpectedEnabledState {
|
||||
plugin_id: String,
|
||||
expected_enabled: bool,
|
||||
actual_enabled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl RemotePluginMutationError {
|
||||
pub(crate) fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::UnexpectedStatus { status, .. } => {
|
||||
Some(http_status_sub_error_type(*status).to_string())
|
||||
}
|
||||
Self::AuthRequired
|
||||
| Self::UnsupportedAuthMode
|
||||
| Self::AuthToken(_)
|
||||
| Self::InvalidBaseUrl(_)
|
||||
| Self::InvalidBaseUrlPath
|
||||
| Self::Request { .. }
|
||||
| Self::Decode { .. }
|
||||
| Self::UnexpectedPluginId { .. }
|
||||
| Self::UnexpectedEnabledState { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginFetchError {
|
||||
#[error("failed to authenticate remote featured plugin request: {0}")]
|
||||
AuthToken(#[source] std::io::Error),
|
||||
#[error("invalid chatgpt base url for remote featured plugin request: {0}")]
|
||||
InvalidBaseUrl(#[source] url::ParseError),
|
||||
|
||||
#[error("failed to send remote featured plugin request to {url}: {source}")]
|
||||
Request {
|
||||
url: String,
|
||||
#[source]
|
||||
source: RouteAwareRequestError,
|
||||
},
|
||||
|
||||
#[error("remote featured plugin request to {url} failed with status {status}: {body}")]
|
||||
UnexpectedStatus {
|
||||
url: String,
|
||||
status: StatusCode,
|
||||
body: String,
|
||||
},
|
||||
|
||||
#[error("failed to parse remote featured plugin response from {url}: {source}")]
|
||||
Decode {
|
||||
url: String,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn fetch_remote_featured_plugin_ids(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
product: Option<Product>,
|
||||
) -> Result<Vec<String>, RemotePluginFetchError> {
|
||||
let base_url = config.chatgpt_base_url.trim_end_matches('/');
|
||||
let mut url = Url::parse(&format!("{base_url}/plugins/featured"))
|
||||
.map_err(RemotePluginFetchError::InvalidBaseUrl)?;
|
||||
url.query_pairs_mut().append_pair(
|
||||
"platform",
|
||||
product.unwrap_or(Product::Codex).to_app_platform(),
|
||||
);
|
||||
let url = url.to_string();
|
||||
let request = match auth.filter(|auth| auth.uses_codex_backend()) {
|
||||
Some(auth) => config
|
||||
.authenticated_request(Method::GET, &url, auth)
|
||||
.await
|
||||
.map_err(std::io::Error::other)
|
||||
.map_err(RemotePluginFetchError::AuthToken)?,
|
||||
None => config.http_request(Method::GET, &url),
|
||||
}
|
||||
.timeout(REMOTE_FEATURED_PLUGIN_FETCH_TIMEOUT);
|
||||
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|source| RemotePluginFetchError::Request {
|
||||
url: url.clone(),
|
||||
source,
|
||||
})?;
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
if !status.is_success() {
|
||||
return Err(RemotePluginFetchError::UnexpectedStatus { url, status, body });
|
||||
}
|
||||
|
||||
serde_json::from_str(&body).map_err(|source| RemotePluginFetchError::Decode {
|
||||
url: url.clone(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn enable_remote_plugin(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
) -> Result<(), RemotePluginMutationError> {
|
||||
post_remote_plugin_mutation(config, auth, plugin_id, "enable").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn uninstall_remote_plugin(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
) -> Result<(), RemotePluginMutationError> {
|
||||
post_remote_plugin_mutation(config, auth, plugin_id, "uninstall").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_codex_backend_auth(
|
||||
auth: Option<&CodexAuth>,
|
||||
) -> Result<&CodexAuth, RemotePluginMutationError> {
|
||||
let Some(auth) = auth else {
|
||||
return Err(RemotePluginMutationError::AuthRequired);
|
||||
};
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(RemotePluginMutationError::UnsupportedAuthMode);
|
||||
}
|
||||
Ok(auth)
|
||||
}
|
||||
|
||||
async fn post_remote_plugin_mutation(
|
||||
config: &RemotePluginServiceConfig,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
action: &str,
|
||||
) -> Result<RemotePluginMutationResponse, RemotePluginMutationError> {
|
||||
let auth = ensure_codex_backend_auth(auth)?;
|
||||
let url = remote_plugin_mutation_url(config, plugin_id, action)?;
|
||||
let request = config
|
||||
.authenticated_request(Method::POST, &url, auth)
|
||||
.await
|
||||
.map_err(std::io::Error::other)
|
||||
.map_err(RemotePluginMutationError::AuthToken)?
|
||||
.timeout(REMOTE_PLUGIN_MUTATION_TIMEOUT);
|
||||
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|source| RemotePluginMutationError::Request {
|
||||
url: url.clone(),
|
||||
source,
|
||||
})?;
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
if !status.is_success() {
|
||||
return Err(RemotePluginMutationError::UnexpectedStatus { url, status, body });
|
||||
}
|
||||
|
||||
let parsed: RemotePluginMutationResponse =
|
||||
serde_json::from_str(&body).map_err(|source| RemotePluginMutationError::Decode {
|
||||
url: url.clone(),
|
||||
source,
|
||||
})?;
|
||||
let expected_enabled = action == "enable";
|
||||
if parsed.id != plugin_id {
|
||||
return Err(RemotePluginMutationError::UnexpectedPluginId {
|
||||
expected: plugin_id.to_string(),
|
||||
actual: parsed.id,
|
||||
});
|
||||
}
|
||||
if parsed.enabled != expected_enabled {
|
||||
return Err(RemotePluginMutationError::UnexpectedEnabledState {
|
||||
plugin_id: plugin_id.to_string(),
|
||||
expected_enabled,
|
||||
actual_enabled: parsed.enabled,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
fn remote_plugin_mutation_url(
|
||||
config: &RemotePluginServiceConfig,
|
||||
plugin_id: &str,
|
||||
action: &str,
|
||||
) -> Result<String, RemotePluginMutationError> {
|
||||
let mut url = Url::parse(config.chatgpt_base_url.trim_end_matches('/'))
|
||||
.map_err(RemotePluginMutationError::InvalidBaseUrl)?;
|
||||
{
|
||||
let mut segments = url
|
||||
.path_segments_mut()
|
||||
.map_err(|()| RemotePluginMutationError::InvalidBaseUrlPath)?;
|
||||
segments.pop_if_empty();
|
||||
segments.push("plugins");
|
||||
segments.push(plugin_id);
|
||||
segments.push(action);
|
||||
}
|
||||
Ok(url.to_string())
|
||||
}
|
||||
77
codex-rs/core-plugins/src/remote_metadata.rs
Normal file
77
codex-rs/core-plugins/src/remote_metadata.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
//! Compares the metadata that determines installed-plugin behavior.
|
||||
//!
|
||||
//! Display metadata (including image URLs and store capability badges) is excluded. Callers must
|
||||
//! still publish the unmodified payload so display consumers receive fresh metadata.
|
||||
|
||||
use crate::remote::RemoteInstalledPlugin;
|
||||
use crate::remote::RemoteMarketplace;
|
||||
|
||||
pub(crate) fn installed_plugin_metadata_eq(
|
||||
previous: &[RemoteInstalledPlugin],
|
||||
current: &[RemoteInstalledPlugin],
|
||||
) -> bool {
|
||||
previous.len() == current.len()
|
||||
&& previous.iter().zip(current).all(|(previous, current)| {
|
||||
previous.marketplace_name == current.marketplace_name
|
||||
&& previous.id == current.id
|
||||
&& previous.name == current.name
|
||||
&& previous.canonical_app_id == current.canonical_app_id
|
||||
&& previous.version == current.version
|
||||
&& previous.installed_at == current.installed_at
|
||||
&& previous.enabled == current.enabled
|
||||
&& previous.install_policy == current.install_policy
|
||||
&& previous.install_policy_source == current.install_policy_source
|
||||
&& previous.must_show_installation_interstitial
|
||||
== current.must_show_installation_interstitial
|
||||
&& previous.auth_policy == current.auth_policy
|
||||
&& previous.availability == current.availability
|
||||
&& previous.disabled_reason == current.disabled_reason
|
||||
&& previous.eligible_plan_types == current.eligible_plan_types
|
||||
})
|
||||
}
|
||||
|
||||
/// Compare installed catalog identity, versions, enablement, policy and availability.
|
||||
///
|
||||
/// Plugin display order is ignored. Marketplace ordering remains significant.
|
||||
/// Callers must still store the unmodified current catalog for display consumers.
|
||||
pub fn remote_catalog_metadata_eq(
|
||||
previous: &[RemoteMarketplace],
|
||||
current: &[RemoteMarketplace],
|
||||
) -> bool {
|
||||
previous.len() == current.len()
|
||||
&& previous.iter().zip(current).all(|(previous, current)| {
|
||||
if previous.name != current.name || previous.plugins.len() != current.plugins.len() {
|
||||
return false;
|
||||
}
|
||||
// Core sorts this view by display name, which can change independently of behavior.
|
||||
let mut previous = previous.plugins.iter().collect::<Vec<_>>();
|
||||
let mut current = current.plugins.iter().collect::<Vec<_>>();
|
||||
previous.sort_unstable_by(|a, b| a.remote_plugin_id.cmp(&b.remote_plugin_id));
|
||||
current.sort_unstable_by(|a, b| a.remote_plugin_id.cmp(&b.remote_plugin_id));
|
||||
previous
|
||||
.into_iter()
|
||||
.zip(current)
|
||||
.all(|(previous, current)| {
|
||||
previous.id == current.id
|
||||
&& previous.remote_plugin_id == current.remote_plugin_id
|
||||
&& previous.name == current.name
|
||||
&& previous.version == current.version
|
||||
&& previous.local_version == current.local_version
|
||||
&& previous.installed == current.installed
|
||||
&& previous.installed_at == current.installed_at
|
||||
&& previous.enabled == current.enabled
|
||||
&& previous.install_policy == current.install_policy
|
||||
&& previous.install_policy_source == current.install_policy_source
|
||||
&& previous.must_show_installation_interstitial
|
||||
== current.must_show_installation_interstitial
|
||||
&& previous.auth_policy == current.auth_policy
|
||||
&& previous.availability == current.availability
|
||||
&& previous.disabled_reason == current.disabled_reason
|
||||
&& previous.eligible_plan_types == current.eligible_plan_types
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "remote_metadata_tests.rs"]
|
||||
mod tests;
|
||||
135
codex-rs/core-plugins/src/remote_metadata_cache_tests.rs
Normal file
135
codex-rs/core-plugins/src/remote_metadata_cache_tests.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
//! Metadata publication must preserve derived caches until runtime inputs change.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_refresh_preserves_loaded_skills_and_tool_suggestions() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let marketplace_root = codex_home
|
||||
.path()
|
||||
.join("plugins/cache/openai-curated-remote");
|
||||
write_plugin(&marketplace_root, "sample/local", "sample");
|
||||
let plugin_root = marketplace_root.join("sample/local");
|
||||
write_file(
|
||||
&codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"[features]
|
||||
plugins = true
|
||||
remote_plugin = true
|
||||
|
||||
[plugins."sample@openai-curated-remote"]
|
||||
enabled = true
|
||||
"#,
|
||||
);
|
||||
let config = load_config(codex_home.path(), codex_home.path()).await;
|
||||
let manager = test_plugins_manager_with_options(
|
||||
codex_home.path().to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
Some(AuthMode::Chatgpt),
|
||||
);
|
||||
let mut remote = remote_installed_plugin("sample");
|
||||
remote.interface = Some(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"capabilities": [], "screenshots": [], "screenshotUrls": [],
|
||||
"logoUrl": "https://files.openai.com/logo.png?sig=old"
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(manager.write_remote_installed_plugins_cache(vec![remote.clone()]));
|
||||
|
||||
let loaded = manager.plugins_for_config(&config).await;
|
||||
let snapshots = manager.plugin_skill_snapshots_for_config(&config).unwrap();
|
||||
let roots = loaded.effective_plugin_skill_roots();
|
||||
assert_eq!(roots.len(), 1);
|
||||
assert_eq!(snapshots.get(&roots[0]).unwrap().skills.len(), 1);
|
||||
let loaded_generation = manager.loaded_plugins_cache_generation();
|
||||
let plugin = ConfiguredMarketplacePlugin {
|
||||
id: "sample@openai-curated-remote".to_string(),
|
||||
name: "sample".to_string(),
|
||||
local_version: None,
|
||||
installed_version: None,
|
||||
source: MarketplacePluginSource::Local {
|
||||
path: plugin_root.abs(),
|
||||
},
|
||||
policy: MarketplacePluginPolicy {
|
||||
installation: MarketplacePluginInstallPolicy::Available,
|
||||
authentication: MarketplacePluginAuthPolicy::OnUse,
|
||||
products: None,
|
||||
},
|
||||
interface: None,
|
||||
keywords: Vec::new(),
|
||||
manifest_fallback: None,
|
||||
installed: true,
|
||||
enabled: true,
|
||||
};
|
||||
let suggestions = manager
|
||||
.tool_suggest_metadata_cache
|
||||
.metadata_for_plugin(
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
&plugin,
|
||||
manager.restriction_product,
|
||||
manager.skill_root_loader.as_ref(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
suggestions
|
||||
.project(&SkillConfigRules::default(), manager.auth_mode())
|
||||
.has_skills
|
||||
);
|
||||
|
||||
let interface = remote.interface.as_mut().unwrap();
|
||||
interface.logo_url = Some("https://files.openai.com/logo.png?sig=new".to_string());
|
||||
interface.display_name = Some("Updated display name".to_string());
|
||||
interface.capabilities = vec!["Updated store badge".to_string()];
|
||||
assert!(!manager.write_remote_installed_plugins_cache(vec![remote.clone()]));
|
||||
assert_eq!(
|
||||
manager
|
||||
.remote_installed_plugins_cache
|
||||
.read()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
Some(vec![remote.clone()])
|
||||
);
|
||||
assert_eq!(manager.loaded_plugins_cache_generation(), loaded_generation);
|
||||
assert_eq!(
|
||||
manager.plugin_skill_snapshots_for_config(&config),
|
||||
Some(snapshots.clone())
|
||||
);
|
||||
assert_eq!(manager.plugins_for_config(&config).await, loaded);
|
||||
let refreshed_suggestions = manager
|
||||
.tool_suggest_metadata_cache
|
||||
.metadata_for_plugin(
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
&plugin,
|
||||
manager.restriction_product,
|
||||
manager.skill_root_loader.as_ref(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(Arc::ptr_eq(&suggestions, &refreshed_suggestions));
|
||||
|
||||
remote.version = Some("2.0.0".to_string());
|
||||
assert!(manager.write_remote_installed_plugins_cache(vec![remote]));
|
||||
assert_eq!(
|
||||
manager.loaded_plugins_cache_generation(),
|
||||
loaded_generation + 1
|
||||
);
|
||||
assert_eq!(manager.plugin_skill_snapshots_for_config(&config), None);
|
||||
manager.plugins_for_config(&config).await;
|
||||
assert_ne!(
|
||||
manager.plugin_skill_snapshots_for_config(&config),
|
||||
Some(snapshots)
|
||||
);
|
||||
let changed_suggestions = manager
|
||||
.tool_suggest_metadata_cache
|
||||
.metadata_for_plugin(
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME,
|
||||
&plugin,
|
||||
manager.restriction_product,
|
||||
manager.skill_root_loader.as_ref(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!Arc::ptr_eq(&suggestions, &changed_suggestions));
|
||||
}
|
||||
181
codex-rs/core-plugins/src/remote_metadata_tests.rs
Normal file
181
codex-rs/core-plugins/src/remote_metadata_tests.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
//! Regression coverage for the fields that affect plugin behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::remote::group_remote_installed_plugins_by_marketplaces;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use serde_json::json;
|
||||
|
||||
fn image_url(renewal: &str) -> String {
|
||||
format!("https://files.openai.com/plugins/icon.png?sig={renewal}")
|
||||
}
|
||||
|
||||
fn plugin(renewal: &str) -> RemoteInstalledPlugin {
|
||||
RemoteInstalledPlugin {
|
||||
marketplace_name: REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
id: "plugin-test".to_string(),
|
||||
version: Some("1.0.0".to_string()),
|
||||
name: "test".to_string(),
|
||||
canonical_app_id: None,
|
||||
installed_at: None,
|
||||
enabled: true,
|
||||
install_policy: PluginInstallPolicy::Available,
|
||||
install_policy_source: None,
|
||||
must_show_installation_interstitial: None,
|
||||
auth_policy: PluginAuthPolicy::OnUse,
|
||||
availability: PluginAvailability::Available,
|
||||
disabled_reason: None,
|
||||
eligible_plan_types: None,
|
||||
interface: Some(
|
||||
serde_json::from_value(json!({
|
||||
"capabilities": [], "screenshots": [],
|
||||
"logoUrl": image_url(renewal), "logoUrlDark": image_url(renewal),
|
||||
"composerIconUrl": image_url(renewal), "screenshotUrls": [image_url(renewal)]
|
||||
}))
|
||||
.unwrap(),
|
||||
),
|
||||
keywords: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn catalog(plugins: &[RemoteInstalledPlugin]) -> Vec<RemoteMarketplace> {
|
||||
group_remote_installed_plugins_by_marketplaces(plugins, &[REMOTE_GLOBAL_MARKETPLACE_NAME])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behavioral_metadata_changes_still_invalidate() {
|
||||
let changes: &[fn(&mut RemoteInstalledPlugin)] = &[
|
||||
|plugin| plugin.id.push_str("-other"),
|
||||
|plugin| plugin.name.push_str("-other"),
|
||||
|plugin| plugin.version = Some("2.0.0".to_string()),
|
||||
|plugin| {
|
||||
plugin.installed_at =
|
||||
chrono::DateTime::from_timestamp(/*secs*/ 1, /*nsecs*/ 0)
|
||||
},
|
||||
|plugin| plugin.enabled = false,
|
||||
|plugin| plugin.install_policy = PluginInstallPolicy::NotAvailable,
|
||||
|plugin| {
|
||||
plugin.install_policy_source =
|
||||
Some(codex_app_server_protocol::PluginInstallPolicySource::WorkspaceSetting)
|
||||
},
|
||||
|plugin| plugin.must_show_installation_interstitial = Some(true),
|
||||
|plugin| plugin.auth_policy = PluginAuthPolicy::OnInstall,
|
||||
|plugin| plugin.availability = PluginAvailability::DisabledByAdmin,
|
||||
|plugin| plugin.eligible_plan_types = Some(vec!["enterprise".to_string()]),
|
||||
];
|
||||
for change in changes {
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
change(&mut current[0]);
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
current[0].canonical_app_id = Some("new-app".to_string());
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(!installed_plugin_metadata_eq(&previous, &[]));
|
||||
assert!(!remote_catalog_metadata_eq(&catalog(&previous), &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_metadata_does_not_invalidate() {
|
||||
let previous = [plugin("old")];
|
||||
let mut current = [plugin("new")];
|
||||
current[0].keywords.push("new keyword".to_string());
|
||||
let interface = current[0].interface.as_mut().unwrap();
|
||||
interface.logo_url = Some("https://another-host.test/different-image.svg".to_string());
|
||||
interface.display_name = Some("New display name".to_string());
|
||||
interface.short_description = Some("New description".to_string());
|
||||
interface.brand_color = Some("#123456".to_string());
|
||||
interface.default_prompt = Some(vec!["New starter prompt".to_string()]);
|
||||
interface.website_url = Some("https://another-host.test".to_string());
|
||||
assert_ne!(previous, current);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
let mut current_catalog = catalog(¤t);
|
||||
current_catalog[0].display_name = "New marketplace title".to_string();
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
¤t_catalog
|
||||
));
|
||||
|
||||
current[0].interface = None;
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_ordering_remains_significant() {
|
||||
let mut other = plugin("old");
|
||||
other.id.push_str("-other");
|
||||
other.name.push_str("-other");
|
||||
let previous = [plugin("old"), other];
|
||||
let mut current = previous.clone();
|
||||
current.reverse();
|
||||
assert!(!installed_plugin_metadata_eq(&previous, ¤t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_badge_changes_do_not_invalidate() {
|
||||
let mut previous = [plugin("old")];
|
||||
previous[0].interface.as_mut().unwrap().capabilities =
|
||||
vec!["tools".to_string(), "skills".to_string()];
|
||||
for badges in [vec!["skills", "tools"], vec!["updated badge"], vec![]] {
|
||||
let mut current = previous.clone();
|
||||
current[0].interface.as_mut().unwrap().capabilities =
|
||||
badges.into_iter().map(str::to_string).collect();
|
||||
assert_ne!(previous, current);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&catalog(&previous),
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_display_reordering_does_not_invalidate() {
|
||||
let mut first = plugin("old");
|
||||
first.interface.as_mut().unwrap().display_name = Some("Alpha".to_string());
|
||||
let mut second = plugin("old");
|
||||
second.id.push_str("-second");
|
||||
second.name.push_str("-second");
|
||||
second.interface.as_mut().unwrap().display_name = Some("Beta".to_string());
|
||||
let previous = [first, second];
|
||||
let mut current = previous.clone();
|
||||
current[0].interface.as_mut().unwrap().display_name = Some("Zulu".to_string());
|
||||
let previous_catalog = catalog(&previous);
|
||||
let current_catalog = catalog(¤t);
|
||||
assert_ne!(
|
||||
previous_catalog[0].plugins[0].id,
|
||||
current_catalog[0].plugins[0].id
|
||||
);
|
||||
assert!(installed_plugin_metadata_eq(&previous, ¤t));
|
||||
assert!(remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
¤t_catalog
|
||||
));
|
||||
|
||||
current[0].version = Some("2.0.0".to_string());
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t)
|
||||
));
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t[1..])
|
||||
));
|
||||
current[0] = current[1].clone();
|
||||
assert!(!remote_catalog_metadata_eq(
|
||||
&previous_catalog,
|
||||
&catalog(¤t)
|
||||
));
|
||||
}
|
||||
300
codex-rs/core-plugins/src/remote_mutations.rs
Normal file
300
codex-rs/core-plugins/src/remote_mutations.rs
Normal file
@@ -0,0 +1,300 @@
|
||||
//! Shared remote plugin mutations for the CLI and app-server.
|
||||
//! The sync gate covers cache/backend changes and refresh scheduling. An install outcome keeps
|
||||
//! its bundle protected from pruning until the caller finishes downstream setup and drops it.
|
||||
|
||||
use super::EffectivePluginsChangedCallback;
|
||||
use super::PluginInstallOutcome;
|
||||
use super::PluginsConfigInput;
|
||||
use super::PluginsManager;
|
||||
use crate::marketplace::MarketplacePluginAuthPolicy;
|
||||
use crate::remote;
|
||||
use crate::remote::RemoteInstalledPluginBundleSyncError;
|
||||
use crate::remote::RemotePluginCacheMutationGuard;
|
||||
use crate::remote::RemotePluginCatalogError;
|
||||
use crate::remote::RemotePluginDetail;
|
||||
use crate::remote_bundle;
|
||||
use crate::remote_bundle::RemotePluginBundleInstallError;
|
||||
use codex_app_server_protocol::PluginAuthPolicy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginTelemetryMetadata;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "remote_mutations_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub struct RemotePluginInstallRequest {
|
||||
pub marketplace_name: String,
|
||||
pub remote_plugin_id: String,
|
||||
pub install_attempt_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Keep this outcome alive throughout post-install setup to protect the installed bundle.
|
||||
#[must_use]
|
||||
pub struct RemotePluginInstallOutcome {
|
||||
pub installed: PluginInstallOutcome,
|
||||
pub detail: RemotePluginDetail,
|
||||
pub app_ids_needing_auth: Option<Vec<String>>,
|
||||
_cache_mutation: RemotePluginCacheMutationGuard,
|
||||
}
|
||||
|
||||
pub struct RemotePluginUninstallOutcome {
|
||||
pub telemetry: PluginTelemetryMetadata,
|
||||
pub effective_plugins_changed: bool,
|
||||
/// The backend uninstall succeeded even when removing the local cache failed.
|
||||
pub cache_removal_error: Option<RemotePluginCatalogError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{kind}")]
|
||||
pub struct RemotePluginOperationError {
|
||||
pub plugin_id: Option<PluginId>,
|
||||
#[source]
|
||||
pub kind: Box<RemotePluginOperationErrorKind>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RemotePluginOperationErrorKind {
|
||||
#[error("{context}: {source}")]
|
||||
Catalog {
|
||||
context: &'static str,
|
||||
source: RemotePluginCatalogError,
|
||||
},
|
||||
#[error("install remote plugin bundle: {0}")]
|
||||
Bundle(#[source] RemotePluginBundleInstallError),
|
||||
#[error("{context}: {source}")]
|
||||
Sync {
|
||||
context: &'static str,
|
||||
source: RemoteInstalledPluginBundleSyncError,
|
||||
},
|
||||
#[error("remote plugin {0} is disabled by admin")]
|
||||
DisabledByAdmin(String),
|
||||
#[error("remote plugin {0} is not available for install")]
|
||||
NotAvailable(String),
|
||||
#[error("{0}")]
|
||||
InvalidRequest(String),
|
||||
#[error("{0}")]
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl PluginsManager {
|
||||
/// Resolve, validate, materialize, and install a remote plugin as one coordinated mutation.
|
||||
pub async fn install_remote_plugin(
|
||||
self: &Arc<Self>,
|
||||
config: &PluginsConfigInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
request: RemotePluginInstallRequest,
|
||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
||||
) -> Result<RemotePluginInstallOutcome, RemotePluginOperationError> {
|
||||
use RemotePluginOperationErrorKind as Error;
|
||||
let unresolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: None,
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
let RemotePluginInstallRequest {
|
||||
marketplace_name,
|
||||
remote_plugin_id,
|
||||
install_attempt_id,
|
||||
} = request;
|
||||
if !config.plugins_enabled {
|
||||
return Err(unresolved(Error::InvalidRequest(format!(
|
||||
"remote plugin install is not enabled for marketplace {marketplace_name}"
|
||||
))));
|
||||
}
|
||||
remote::validate_remote_plugin_id(&remote_plugin_id)
|
||||
.map_err(|err| unresolved(Error::InvalidRequest(err.message)))?;
|
||||
let service = self
|
||||
.remote_plugin_service_config(config)
|
||||
.for_current_account();
|
||||
let detail = remote::fetch_remote_plugin_detail_with_download_urls(
|
||||
&service,
|
||||
auth,
|
||||
&marketplace_name,
|
||||
&remote_plugin_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
unresolved(Error::Catalog {
|
||||
context: "read remote plugin details before install",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let plugin_id = PluginId::parse(&detail.summary.id).map_err(|err| {
|
||||
unresolved(Error::Internal(format!(
|
||||
"invalid resolved plugin id `{}`: {err}",
|
||||
detail.summary.id
|
||||
)))
|
||||
})?;
|
||||
let resolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: Some(plugin_id.clone()),
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
if detail.summary.availability == PluginAvailability::DisabledByAdmin {
|
||||
return Err(resolved(Error::DisabledByAdmin(remote_plugin_id)));
|
||||
}
|
||||
if detail.summary.install_policy == PluginInstallPolicy::NotAvailable {
|
||||
return Err(resolved(Error::NotAvailable(remote_plugin_id)));
|
||||
}
|
||||
let bundle = remote_bundle::validate_remote_plugin_bundle(
|
||||
&remote_plugin_id,
|
||||
&detail.marketplace_name,
|
||||
&detail.summary.name,
|
||||
detail.release_version.as_deref(),
|
||||
detail.bundle_download_url.as_deref(),
|
||||
detail.app_manifest.clone(),
|
||||
)
|
||||
.map_err(|err| resolved(Error::Bundle(err)))?;
|
||||
let _sync_guard = self
|
||||
.acquire_remote_installed_plugin_sync_guard()
|
||||
.await
|
||||
.map_err(|source| {
|
||||
resolved(Error::Sync {
|
||||
context: "failed to coordinate remote plugin install",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let cache_mutation = remote::mark_remote_plugin_cache_mutation_in_flight(
|
||||
&self.codex_home,
|
||||
&detail.marketplace_name,
|
||||
&detail.summary.name,
|
||||
);
|
||||
// Materialize first: a failed download must never leave a backend installation behind.
|
||||
let installed = remote_bundle::download_and_install_remote_plugin_bundle(
|
||||
&service,
|
||||
self.codex_home.clone(),
|
||||
bundle,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| resolved(Error::Bundle(err)))?;
|
||||
let install_result = if let Some(install_attempt_id) = install_attempt_id.as_deref() {
|
||||
remote::install_remote_plugin_with_install_attempt_id(
|
||||
&service,
|
||||
auth,
|
||||
&detail.marketplace_name,
|
||||
&remote_plugin_id,
|
||||
install_attempt_id,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
remote::install_remote_plugin(
|
||||
&service,
|
||||
auth,
|
||||
&detail.marketplace_name,
|
||||
&remote_plugin_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| {
|
||||
resolved(Error::Catalog {
|
||||
context: "install remote plugin",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
self.maybe_start_remote_installed_plugins_cache_refresh_after_mutation(
|
||||
config,
|
||||
auth.cloned(),
|
||||
on_effective_plugins_changed,
|
||||
);
|
||||
Ok(RemotePluginInstallOutcome {
|
||||
installed: PluginInstallOutcome {
|
||||
plugin_id: installed.plugin_id,
|
||||
plugin_version: installed.plugin_version,
|
||||
installed_path: installed.installed_path,
|
||||
auth_policy: match detail.summary.auth_policy {
|
||||
PluginAuthPolicy::OnInstall => MarketplacePluginAuthPolicy::OnInstall,
|
||||
PluginAuthPolicy::OnUse => MarketplacePluginAuthPolicy::OnUse,
|
||||
},
|
||||
},
|
||||
detail,
|
||||
app_ids_needing_auth: install_result.app_ids_needing_auth,
|
||||
_cache_mutation: cache_mutation,
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove the backend installation and local cache, then schedule an installed-state refresh.
|
||||
pub async fn uninstall_remote_plugin(
|
||||
self: &Arc<Self>,
|
||||
config: &PluginsConfigInput,
|
||||
auth: Option<&CodexAuth>,
|
||||
remote_plugin_id: &str,
|
||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
||||
) -> Result<RemotePluginUninstallOutcome, RemotePluginOperationError> {
|
||||
use RemotePluginOperationErrorKind as Error;
|
||||
let unresolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: None,
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
if !config.plugins_enabled {
|
||||
return Err(unresolved(Error::InvalidRequest(
|
||||
"remote plugin uninstall is not enabled".to_string(),
|
||||
)));
|
||||
}
|
||||
remote::validate_remote_plugin_id(remote_plugin_id)
|
||||
.map_err(|err| unresolved(Error::InvalidRequest(err.message)))?;
|
||||
let service = self.remote_plugin_service_config(config);
|
||||
let target =
|
||||
remote::resolve_remote_plugin_uninstall_target(&service, auth, remote_plugin_id)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
unresolved(Error::Catalog {
|
||||
context: "resolve remote plugin before uninstall",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let mut telemetry = self
|
||||
.telemetry_metadata_for_installed_plugin_with_remote_id(
|
||||
&target.plugin_id,
|
||||
remote_plugin_id,
|
||||
)
|
||||
.await;
|
||||
if telemetry.capability_summary.is_none() {
|
||||
telemetry.capability_summary = Some(target.fallback_capability_summary.clone());
|
||||
}
|
||||
let plugin_id = target.plugin_id.clone();
|
||||
let resolved = |kind| RemotePluginOperationError {
|
||||
plugin_id: Some(plugin_id.clone()),
|
||||
kind: Box::new(kind),
|
||||
};
|
||||
let _sync_guard = self
|
||||
.acquire_remote_installed_plugin_sync_guard()
|
||||
.await
|
||||
.map_err(|source| {
|
||||
resolved(Error::Sync {
|
||||
context: "failed to coordinate remote plugin uninstall",
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
let _cache_mutation = remote::mark_remote_plugin_cache_mutation_in_flight(
|
||||
&self.codex_home,
|
||||
&plugin_id.marketplace_name,
|
||||
&plugin_id.plugin_name,
|
||||
);
|
||||
let cache_removal_error =
|
||||
match remote::uninstall_remote_plugin(&service, auth, self.codex_home.clone(), target)
|
||||
.await
|
||||
{
|
||||
Ok(()) => None,
|
||||
Err(err @ RemotePluginCatalogError::CacheRemove(_)) => Some(err),
|
||||
Err(source) => {
|
||||
return Err(resolved(Error::Catalog {
|
||||
context: "uninstall remote plugin",
|
||||
source,
|
||||
}));
|
||||
}
|
||||
};
|
||||
let effective_plugins_changed = self.clear_remote_installed_plugins_cache();
|
||||
self.maybe_start_remote_installed_plugins_cache_refresh_after_mutation(
|
||||
config,
|
||||
auth.cloned(),
|
||||
on_effective_plugins_changed,
|
||||
);
|
||||
Ok(RemotePluginUninstallOutcome {
|
||||
telemetry,
|
||||
effective_plugins_changed,
|
||||
cache_removal_error,
|
||||
})
|
||||
}
|
||||
}
|
||||
473
codex-rs/core-plugins/src/remote_mutations_tests.rs
Normal file
473
codex-rs/core-plugins/src/remote_mutations_tests.rs
Normal file
@@ -0,0 +1,473 @@
|
||||
//! Regression coverage for remote mutations and account-bound storage transfers.
|
||||
|
||||
use super::*;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::test_support::load_plugins_config;
|
||||
use crate::test_support::test_auth_manager;
|
||||
use crate::test_support::test_plugins_manager_with_auth_manager;
|
||||
use crate::test_support::write_file;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Notify;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn uninstall_serializes_backend_mutations_and_preserves_cache_on_failure() {
|
||||
for uninstall_fails in [false, true] {
|
||||
let home = TempDir::new().unwrap();
|
||||
let server = MockServer::start().await;
|
||||
let mut config = load_plugins_config(home.path(), home.path()).await;
|
||||
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
|
||||
let auth_manager = test_auth_manager(Some(AuthMode::Chatgpt));
|
||||
let auth = auth_manager.auth().await;
|
||||
let manager = Arc::new(test_plugins_manager_with_auth_manager(
|
||||
home.path().to_path_buf(),
|
||||
/*restriction_product*/ None,
|
||||
auth_manager,
|
||||
));
|
||||
let remote_id = "b1234567-89ab-4cde-8f01-234567890abc";
|
||||
let plugin_id = PluginId::new(
|
||||
"sample".to_string(),
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let cache = manager.store.plugin_base_root(&plugin_id);
|
||||
write_file(
|
||||
cache.join("1.0.0/.codex-plugin/plugin.json").as_path(),
|
||||
r#"{"name":"sample","version":"1.0.0"}"#,
|
||||
);
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/backend-api/ps/plugins/{remote_id}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"id": remote_id, "name": "sample", "scope": "GLOBAL",
|
||||
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
|
||||
"release": {"display_name": "Sample", "description": "Sample plugin", "interface": {}}
|
||||
}))).mount(&server).await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"plugins": [], "pagination": {"next_page_token": null}})),
|
||||
)
|
||||
.expect(if uninstall_fails { 0 } else { 1 })
|
||||
.mount(&server)
|
||||
.await;
|
||||
let gate_held = Arc::new(AtomicBool::new(false));
|
||||
let gate_held_at_post = Arc::clone(&gate_held);
|
||||
let manager_at_post = Arc::clone(&manager);
|
||||
Mock::given(method("POST"))
|
||||
.and(path(format!(
|
||||
"/backend-api/ps/plugins/{remote_id}/uninstall"
|
||||
)))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
gate_held_at_post.store(
|
||||
manager_at_post
|
||||
.remote_installed_plugin_bundle_sync_gate
|
||||
.available_permits()
|
||||
== 0,
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
ResponseTemplate::new(if uninstall_fails { 400 } else { 200 })
|
||||
.set_body_json(json!({"id": remote_id, "enabled": false}))
|
||||
})
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let refreshed = Arc::new(Notify::new());
|
||||
let refreshed_callback = Arc::clone(&refreshed);
|
||||
let outcome = manager
|
||||
.uninstall_remote_plugin(
|
||||
&config,
|
||||
auth.as_ref(),
|
||||
remote_id,
|
||||
Some(Arc::new(move |_| refreshed_callback.notify_one())),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(
|
||||
gate_held.load(Ordering::SeqCst),
|
||||
manager
|
||||
.remote_installed_plugin_bundle_sync_gate
|
||||
.available_permits(),
|
||||
cache.as_path().exists(),
|
||||
outcome.is_err()
|
||||
),
|
||||
(true, 1, uninstall_fails, uninstall_fails),
|
||||
);
|
||||
if !uninstall_fails {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), refreshed.notified())
|
||||
.await
|
||||
.expect("successful uninstall should refresh installed state");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch only after metadata has been read, immediately before constructing the storage request.
|
||||
/// Metadata-body cancellation would not exercise the separate request these tests protect.
|
||||
#[derive(Clone)]
|
||||
struct TransferHttpClients {
|
||||
delegate: codex_http_client::RouteAwareClientPool,
|
||||
controller: codex_http_client::NetworkPolicyController,
|
||||
switch_before_storage: Arc<AtomicBool>,
|
||||
api_origin: String,
|
||||
storage_origin: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TransferHttpClients {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TransferHttpClients")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::http_client_selector::HttpClientSelector for TransferHttpClients {
|
||||
fn for_current_account(&self) -> Arc<dyn crate::http_client_selector::HttpClientSelector> {
|
||||
Arc::new(Self {
|
||||
delegate: self.delegate.for_current_account(),
|
||||
..self.clone()
|
||||
})
|
||||
}
|
||||
|
||||
fn request(&self, method: http::Method, url: &str) -> codex_http_client::RequestBuilder {
|
||||
if url.starts_with("https://storage.example/")
|
||||
&& self.switch_before_storage.swap(false, Ordering::SeqCst)
|
||||
{
|
||||
let policy = self.controller.policy();
|
||||
policy.invalidate();
|
||||
assert!(self.controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Unrestricted,
|
||||
));
|
||||
}
|
||||
self.delegate.request(
|
||||
method,
|
||||
url.replace("https://storage.example", &self.storage_origin)
|
||||
.replace("https://chatgpt.com", &self.api_origin),
|
||||
)
|
||||
}
|
||||
|
||||
fn request_for_account(
|
||||
&self,
|
||||
method: http::Method,
|
||||
url: &str,
|
||||
binding: &codex_http_client::NetworkPolicy,
|
||||
) -> Option<codex_http_client::RequestBuilder> {
|
||||
Some(
|
||||
self.delegate
|
||||
.with_account_binding(binding)?
|
||||
.request(method, url.replace("https://chatgpt.com", &self.api_origin)),
|
||||
)
|
||||
}
|
||||
|
||||
fn outbound_proxy_policy(&self) -> codex_http_client::OutboundProxyPolicy {
|
||||
self.delegate.outbound_proxy_policy()
|
||||
}
|
||||
}
|
||||
|
||||
struct PluginTransferTest {
|
||||
api: MockServer,
|
||||
storage: MockServer,
|
||||
config: PluginsConfigInput,
|
||||
manager: Arc<PluginsManager>,
|
||||
auth: CodexAuth,
|
||||
switch_before_storage: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl PluginTransferTest {
|
||||
async fn new(
|
||||
home: &std::path::Path,
|
||||
mode: codex_features::RuntimeAuthMode,
|
||||
switch: bool,
|
||||
) -> Self {
|
||||
use base64::Engine;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
|
||||
let api = MockServer::start().await;
|
||||
let storage = MockServer::start().await;
|
||||
Mock::given(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&api)
|
||||
.await;
|
||||
let claims = json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": "login-a",
|
||||
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"},
|
||||
});
|
||||
let token = format!(
|
||||
"header.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string()),
|
||||
);
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let credentials = codex_login::AuthManager::from_auth_for_testing(auth.clone());
|
||||
let slot = RuntimeAuthSlot::default();
|
||||
slot.set(Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", api.uri()).parse().unwrap(),
|
||||
)))
|
||||
.unwrap();
|
||||
let controller = NetworkPolicyController::default();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy())
|
||||
.with_sensitive_header_protection();
|
||||
let switch_before_storage = Arc::new(AtomicBool::new(switch));
|
||||
let clients = Arc::new(TransferHttpClients {
|
||||
delegate: RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
|
||||
factory.clone(),
|
||||
ClientRouteClass::Api,
|
||||
),
|
||||
controller,
|
||||
switch_before_storage: Arc::clone(&switch_before_storage),
|
||||
api_origin: api.uri(),
|
||||
storage_origin: storage.uri(),
|
||||
});
|
||||
let config = PluginsConfigInput::new(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
"openai".into(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ true,
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
factory,
|
||||
/*product_sku*/ None,
|
||||
)
|
||||
.with_runtime_auth_mode(Some(mode));
|
||||
config.runtime_http_clients.set(clients).unwrap();
|
||||
let manager = Arc::new(crate::PluginsManager::new_with_options(
|
||||
home.to_path_buf(),
|
||||
/*restriction_product*/ None,
|
||||
credentials,
|
||||
slot,
|
||||
crate::test_support::test_skill_root_loader(),
|
||||
));
|
||||
Self {
|
||||
api,
|
||||
storage,
|
||||
config,
|
||||
manager,
|
||||
auth,
|
||||
switch_before_storage,
|
||||
}
|
||||
}
|
||||
|
||||
async fn verify(&self, account_changed: bool, mode: codex_features::RuntimeAuthMode) {
|
||||
assert!(!self.switch_before_storage.load(Ordering::SeqCst));
|
||||
self.api.verify().await;
|
||||
let storage_requests = self.storage.received_requests().await.unwrap();
|
||||
assert_eq!(storage_requests.len(), usize::from(!account_changed));
|
||||
for request in storage_requests {
|
||||
for name in [
|
||||
"authorization",
|
||||
"x-openai-agent-assertion",
|
||||
"chatgpt-account-id",
|
||||
] {
|
||||
assert!(!request.headers.contains_key(name));
|
||||
}
|
||||
}
|
||||
for request in self.api.received_requests().await.unwrap() {
|
||||
if request.url.path() == "/agent/register" {
|
||||
continue;
|
||||
}
|
||||
let authorization = request.headers["authorization"].to_str().unwrap();
|
||||
match mode {
|
||||
codex_features::RuntimeAuthMode::DualHeader => {
|
||||
assert!(authorization.starts_with("Bearer "));
|
||||
assert!(request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
codex_features::RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(authorization.starts_with("AgentAssertion "));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_share_keeps_account_binding_through_storage_upload() {
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_http_client::RouteAwareRequestError;
|
||||
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for account_changed in [false, true] {
|
||||
let home = TempDir::new().unwrap();
|
||||
let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await;
|
||||
let plugin_path = home.path().join("sample");
|
||||
write_file(
|
||||
&plugin_path.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample"}"#,
|
||||
);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace/upload-url"))
|
||||
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
|
||||
"file_id": "file_123", "upload_url": "https://storage.example/upload",
|
||||
"etag": "\"metadata-etag\"",
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&fixture.api)
|
||||
.await;
|
||||
Mock::given(method("PUT"))
|
||||
.and(path("/upload"))
|
||||
.respond_with(ResponseTemplate::new(201))
|
||||
.mount(&fixture.storage)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/backend-api/public/plugins/workspace"))
|
||||
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
|
||||
"plugin_id": "plugins_123", "share_url": null,
|
||||
})))
|
||||
.expect(u64::from(!account_changed))
|
||||
.mount(&fixture.api)
|
||||
.await;
|
||||
let result = remote::save_remote_plugin_share(
|
||||
&fixture
|
||||
.manager
|
||||
.remote_plugin_service_config(&fixture.config),
|
||||
Some(&fixture.auth),
|
||||
home.path(),
|
||||
&AbsolutePathBuf::try_from(plugin_path).unwrap(),
|
||||
/*remote_plugin_id*/ None,
|
||||
remote::RemotePluginShareAccessPolicy::default(),
|
||||
)
|
||||
.await;
|
||||
if account_changed {
|
||||
assert!(
|
||||
matches!(
|
||||
result,
|
||||
Err(RemotePluginCatalogError::Request {
|
||||
source: RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked),
|
||||
..
|
||||
})
|
||||
),
|
||||
"{result:?}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(result.unwrap().remote_plugin_id, "plugins_123");
|
||||
}
|
||||
fixture.verify(account_changed, mode).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_install_keeps_account_binding_through_storage_download() {
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_http_client::RouteAwareRequestError;
|
||||
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for account_changed in [false, true] {
|
||||
let home = TempDir::new().unwrap();
|
||||
let fixture = PluginTransferTest::new(home.path(), mode, account_changed).await;
|
||||
let remote_id = "b1234567-89ab-4cde-8f01-234567890abc";
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/backend-api/ps/plugins/{remote_id}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"id": remote_id, "name": "sample", "scope": "GLOBAL",
|
||||
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE",
|
||||
"release": {
|
||||
"version": "1.0.0", "display_name": "Sample",
|
||||
"description": "Sample plugin", "interface": {},
|
||||
"bundle_download_url": "https://storage.example/bundle",
|
||||
}
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&fixture.api)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/backend-api/ps/plugins/installed"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [], "pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&fixture.api)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/bundle"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_string("bundle"))
|
||||
.mount(&fixture.storage)
|
||||
.await;
|
||||
let result = fixture
|
||||
.manager
|
||||
.install_remote_plugin(
|
||||
&fixture.config,
|
||||
Some(&fixture.auth),
|
||||
RemotePluginInstallRequest {
|
||||
marketplace_name: REMOTE_GLOBAL_MARKETPLACE_NAME.to_string(),
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
install_attempt_id: None,
|
||||
},
|
||||
/*on_effective_plugins_changed*/ None,
|
||||
)
|
||||
.await;
|
||||
let error = result.err().expect("test transfer should fail");
|
||||
if account_changed {
|
||||
assert!(
|
||||
matches!(
|
||||
*error.kind,
|
||||
RemotePluginOperationErrorKind::Bundle(
|
||||
RemotePluginBundleInstallError::DownloadRequest {
|
||||
source: RouteAwareRequestError::Policy(
|
||||
NetworkPolicyDenied::Revoked
|
||||
),
|
||||
..
|
||||
}
|
||||
)
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
} else {
|
||||
// The local HTTP control reaches storage, then fails the final-URL HTTPS check.
|
||||
assert!(
|
||||
matches!(
|
||||
*error.kind,
|
||||
RemotePluginOperationErrorKind::Bundle(
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. }
|
||||
)
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
}
|
||||
fixture.verify(account_changed, mode).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
65
codex-rs/core-plugins/src/remote_plugin_id_resolver.rs
Normal file
65
codex-rs/core-plugins/src/remote_plugin_id_resolver.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use crate::remote::RemoteInstalledPlugin;
|
||||
use crate::remote::RemotePluginScope;
|
||||
use crate::store::ActivePluginInstallation;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_plugin::PluginId;
|
||||
use std::collections::HashMap;
|
||||
use tracing::warn;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RemoteInstalledPluginsSnapshot {
|
||||
pub(crate) configs: HashMap<String, PluginConfig>,
|
||||
pub(crate) remote_plugin_id_resolver: RemotePluginIdResolver,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RemotePluginIdResolver {
|
||||
snapshot_ids: Option<HashMap<PluginId, String>>,
|
||||
}
|
||||
|
||||
impl RemotePluginIdResolver {
|
||||
pub(crate) fn new(plugins: &[RemoteInstalledPlugin]) -> Self {
|
||||
let mut snapshot_ids = HashMap::with_capacity(plugins.len());
|
||||
for plugin in plugins {
|
||||
let Ok(plugin_id) = PluginId::new(plugin.name.clone(), plugin.marketplace_name.clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
snapshot_ids
|
||||
.entry(plugin_id)
|
||||
.or_insert_with(|| plugin.id.clone());
|
||||
}
|
||||
Self {
|
||||
snapshot_ids: Some(snapshot_ids),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remote_plugin_id_for_installation(
|
||||
&self,
|
||||
installation: &ActivePluginInstallation,
|
||||
) -> Option<String> {
|
||||
if let Some(snapshot_ids) = &self.snapshot_ids {
|
||||
return snapshot_ids.get(&installation.plugin_id).cloned();
|
||||
}
|
||||
|
||||
persisted_remote_plugin_id_for_installation(installation)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn persisted_remote_plugin_id_for_installation(
|
||||
installation: &ActivePluginInstallation,
|
||||
) -> Option<String> {
|
||||
RemotePluginScope::from_marketplace_name(&installation.plugin_id.marketplace_name)?;
|
||||
|
||||
match installation.persisted_remote_plugin_id() {
|
||||
Ok(remote_plugin_id) => remote_plugin_id,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
plugin_id = %installation.plugin_id.as_key(),
|
||||
error = %err,
|
||||
"failed to read persisted remote plugin identity"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
307
codex-rs/core-plugins/src/remote_runtime_auth_tests.rs
Normal file
307
codex-rs/core-plugins/src/remote_runtime_auth_tests.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
//! Exercise modern and legacy plugin requests with a shared, late-initialized runtime.
|
||||
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthRouteConfig;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_runtime_auth_shares_registration_and_strips_cross_origin_auth() {
|
||||
for (mode, pooled) in [
|
||||
(RuntimeAuthMode::DualHeader, false),
|
||||
(RuntimeAuthMode::AssertionOnly, false),
|
||||
(RuntimeAuthMode::DualHeader, true),
|
||||
(RuntimeAuthMode::AssertionOnly, true),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let destination = MockServer::start().await;
|
||||
Mock::given(path("/"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"enabled": true, "plugins": [],
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&destination)
|
||||
.await;
|
||||
Mock::given(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-plugins", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "account-a"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/backend-api/ps/plugins/list"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"plugins": [], "pagination": {"next_page_token": null},
|
||||
})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/backend-api/plugins/featured"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/backend-api/ps/plugins/suggested/codex"))
|
||||
.respond_with(ResponseTemplate::new(307).insert_header("location", destination.uri()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let claims = json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": "login-a",
|
||||
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "account-a"},
|
||||
});
|
||||
let token = format!(
|
||||
"header.{}.signature",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string())
|
||||
);
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let slot = RuntimeAuthSlot::default();
|
||||
let controller = NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(policy.clone());
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
home.path(),
|
||||
&token,
|
||||
"account-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let credentials = Arc::new(
|
||||
AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
AuthRouteConfig::from_http_client_factory(factory.clone()),
|
||||
)
|
||||
.await,
|
||||
);
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
let mut config = if pooled {
|
||||
crate::manager::PluginsConfigInput::new(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
"openai".into(),
|
||||
/*plugins_enabled*/ true,
|
||||
/*remote_plugin_enabled*/ true,
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
factory,
|
||||
/*product_sku*/ None,
|
||||
)
|
||||
.remote_plugin_service_config(Some((Arc::clone(&slot), mode)))
|
||||
} else {
|
||||
RemotePluginServiceConfig::new_with_selected_runtime_auth(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
factory,
|
||||
/*product_sku*/ None,
|
||||
(Arc::clone(&slot), mode),
|
||||
)
|
||||
};
|
||||
config.chatgpt_base_url = format!("{}/backend-api", server.uri());
|
||||
// Enabled requests cannot silently fall back before the harness initializes the slot.
|
||||
assert!(
|
||||
fetch_recommended_plugins(&config, Some(&auth))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
slot.set(Arc::new(RuntimeAuthManager::new(
|
||||
credentials,
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse().unwrap(),
|
||||
)))
|
||||
.unwrap();
|
||||
get_remote_plugin_list_page(
|
||||
&config,
|
||||
&auth,
|
||||
RemotePluginScope::Global,
|
||||
/*page_token*/ None,
|
||||
/*collection*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::remote_legacy::fetch_remote_featured_plugin_ids(
|
||||
&config,
|
||||
Some(&auth),
|
||||
/*product*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
fetch_recommended_plugins(&config, Some(&auth))
|
||||
.await
|
||||
.unwrap();
|
||||
let redirected = destination.received_requests().await.unwrap();
|
||||
assert_eq!(redirected.len(), 1);
|
||||
assert!(!redirected[0].headers.contains_key("authorization"));
|
||||
assert!(
|
||||
!redirected[0]
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
destination.verify().await;
|
||||
let url = format!("{}/backend-api/ps/plugins/list", server.uri());
|
||||
let pending = config
|
||||
.authenticated_request(Method::GET, &url, &auth)
|
||||
.await
|
||||
.unwrap();
|
||||
policy.invalidate();
|
||||
assert!(controller.publish(policy.revision(), DestinationPolicy::Unrestricted));
|
||||
assert!(matches!(
|
||||
pending.send().await,
|
||||
Err(RouteAwareRequestError::Policy(NetworkPolicyDenied::Revoked))
|
||||
));
|
||||
let response = config
|
||||
.authenticated_request(Method::GET, &url, &auth)
|
||||
.await
|
||||
.unwrap()
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let mut proof_ids = HashSet::new();
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() != "/agent/register")
|
||||
{
|
||||
let authorization = request.headers["authorization"].to_str().unwrap();
|
||||
let proof = match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
request.headers["x-openai-agent-assertion"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
authorization.strip_prefix("AgentAssertion ").unwrap()
|
||||
}
|
||||
};
|
||||
assert_eq!(request.headers["chatgpt-account-id"], "account-a");
|
||||
let payload: JsonValue = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(2).unwrap())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-plugins");
|
||||
assert!(proof_ids.insert(payload["id"].as_str().unwrap().to_string()));
|
||||
}
|
||||
assert_eq!(proof_ids.len(), 4);
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_plugin_backend_keeps_legacy_auth_with_runtime_enabled() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/backend-api/plugins/featured"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!([])))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let config = RemotePluginServiceConfig::new_with_runtime_auth(
|
||||
format!("{}/backend-api", server.uri()),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
/*product_sku*/ None,
|
||||
(RuntimeAuthSlot::default(), mode),
|
||||
);
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
crate::remote_legacy::fetch_remote_featured_plugin_ids(
|
||||
&config,
|
||||
Some(&auth),
|
||||
/*product*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(
|
||||
requests[0].headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("Bearer ")
|
||||
);
|
||||
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_openai_plugin_backend_fails_before_registration() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let auth = CodexAuth::from_api_key("key-a");
|
||||
let runtime = (
|
||||
Arc::new(std::sync::OnceLock::from(Arc::new(
|
||||
RuntimeAuthManager::new(
|
||||
AuthManager::from_auth_for_testing(auth.clone()),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", server.uri()).parse().unwrap(),
|
||||
),
|
||||
))),
|
||||
mode,
|
||||
);
|
||||
let config = RemotePluginServiceConfig::new_with_runtime_auth(
|
||||
"https://future.openai.com/backend-api".to_string(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
/*product_sku*/ None,
|
||||
runtime,
|
||||
);
|
||||
assert!(
|
||||
config
|
||||
.authenticated_request(
|
||||
Method::GET,
|
||||
"https://future.openai.com/backend-api/plugins/featured",
|
||||
&auth,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
1009
codex-rs/core-plugins/src/remote_tests.rs
Normal file
1009
codex-rs/core-plugins/src/remote_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
700
codex-rs/core-plugins/src/script_attribution.rs
Normal file
700
codex-rs/core-plugins/src/script_attribution.rs
Normal file
@@ -0,0 +1,700 @@
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME;
|
||||
use crate::PluginLoadOutcome;
|
||||
use crate::loader::curated_plugin_cache_version;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
use crate::marketplace::find_marketplace_plugin;
|
||||
use crate::marketplace_policy::primary_runtime_marketplace_root;
|
||||
use crate::plugin_metrics::PluginMetricsOperation;
|
||||
use crate::plugin_metrics::ResolvedPluginMetricsOperation;
|
||||
use crate::plugin_metrics::load_plugin_metrics_operations;
|
||||
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||
use crate::startup_sync::curated_plugins_repo_path;
|
||||
use crate::startup_sync::read_curated_plugins_sha;
|
||||
use crate::store::DEFAULT_PLUGIN_VERSION;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::plugin_version_for_source;
|
||||
use crate::store::validate_plugin_version_segment;
|
||||
use codex_exec_server::ExecutorFileSystem;
|
||||
use codex_exec_server::GetMetadataOptions;
|
||||
use codex_exec_server::ReadFileOptions;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::items::is_safe_plugin_relative_path;
|
||||
use codex_shell_command::bash::extract_bash_command;
|
||||
use codex_shell_command::bash::parse_shell_lc_plain_commands;
|
||||
use codex_shell_command::parse_command::is_pathish;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct TrustedPluginRoot {
|
||||
plugin_id: PluginId,
|
||||
version: String,
|
||||
root: AbsolutePathBuf,
|
||||
metrics_operations_by_path: BTreeMap<String, PluginMetricsOperation>,
|
||||
}
|
||||
|
||||
/// Trusted plugin command attribution safe to carry into command analytics.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginCommandAttribution {
|
||||
pub plugin_id: PluginId,
|
||||
pub normalized_relative_path: String,
|
||||
}
|
||||
|
||||
impl PluginCommandAttribution {
|
||||
/// Returns the paired fields used at command protocol boundaries.
|
||||
pub fn serialized_fields(&self) -> (String, String) {
|
||||
(
|
||||
self.plugin_id.as_key(),
|
||||
self.normalized_relative_path.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Active first-party roots eligible for command attribution.
|
||||
/// Trusted means OpenAI-shipped synced or bundled runtime code, or a
|
||||
/// server-installed global remote plugin cache entry, not a local override.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TrustedPluginRoots {
|
||||
roots: Vec<TrustedPluginRoot>,
|
||||
}
|
||||
|
||||
/// An untrusted hint from a canonical executor script path, never authorization.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PluginMeasurementTarget {
|
||||
pub(crate) plugin_id: PluginId,
|
||||
pub(crate) version: String,
|
||||
pub(crate) path_convention: PathConvention,
|
||||
}
|
||||
|
||||
impl PluginMeasurementTarget {
|
||||
/// Selects one remote plugin using the same command parser as attribution.
|
||||
/// Skip paths outside the remote plugin cache before consulting the executor.
|
||||
pub async fn from_command(
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Option<Self> {
|
||||
let command = single_plain_command(command)?;
|
||||
let invocation = script_invocation(&command)?;
|
||||
let script = cwd.join(invocation.script).ok()?;
|
||||
Self::from_script_path(&script)?;
|
||||
let script = file_system
|
||||
.canonicalize(&script, /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
Self::from_script_path(&script)
|
||||
}
|
||||
|
||||
fn from_script_path(script: &PathUri) -> Option<Self> {
|
||||
let path_convention = script.infer_path_convention()?;
|
||||
let native_path = script.inferred_native_path_string();
|
||||
// Normalize only the hint so equivalent Windows paths share preparation.
|
||||
// Store identities must retain the authenticated catalog's spelling.
|
||||
let native_path = match path_convention {
|
||||
PathConvention::Windows => native_path.to_ascii_lowercase(),
|
||||
PathConvention::Posix => native_path,
|
||||
};
|
||||
let components = path_convention
|
||||
.path_segments(&native_path)
|
||||
.collect::<Vec<_>>();
|
||||
let mut candidates = components.windows(6).filter_map(|parts| {
|
||||
if parts[..3] != ["plugins", "cache", REMOTE_GLOBAL_MARKETPLACE_NAME]
|
||||
|| parts[4] == DEFAULT_PLUGIN_VERSION
|
||||
{
|
||||
return None;
|
||||
}
|
||||
validate_plugin_version_segment(parts[4]).ok()?;
|
||||
Some(Self {
|
||||
plugin_id: PluginId::new(parts[3].to_owned(), parts[2].to_owned()).ok()?,
|
||||
version: parts[4].to_owned(),
|
||||
path_convention,
|
||||
})
|
||||
});
|
||||
let target = candidates.next()?;
|
||||
candidates.next().is_none().then_some(target)
|
||||
}
|
||||
}
|
||||
|
||||
impl TrustedPluginRoots {
|
||||
/// Called only after the authenticated remote bundle installer has prepared
|
||||
/// an isolated store. Read declarations without loading plugin capabilities.
|
||||
pub(crate) fn from_measurement_reference(
|
||||
codex_home: &Path,
|
||||
plugin_id: &PluginId,
|
||||
version: &str,
|
||||
remote_id: &str,
|
||||
) -> Option<Self> {
|
||||
let store = PluginStore::try_new(codex_home.to_owned()).ok()?;
|
||||
if store.active_plugin_version(plugin_id).as_deref() != Some(version)
|
||||
|| store.remote_plugin_id(plugin_id).ok()?.as_deref() != Some(remote_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let root = store.plugin_root(plugin_id, version).canonicalize().ok()?;
|
||||
let metrics_operations_by_path = load_plugin_metrics_operations(&root).unwrap_or_default();
|
||||
Some(Self {
|
||||
roots: vec![TrustedPluginRoot {
|
||||
plugin_id: plugin_id.clone(),
|
||||
version: version.to_owned(),
|
||||
root,
|
||||
metrics_operations_by_path,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds already-trusted roots, preserving the existing root for each plugin and version.
|
||||
/// Distinct versions remain eligible for exact executor-version matching.
|
||||
pub fn extend(&mut self, other: &Self) {
|
||||
let mut seen = self
|
||||
.roots
|
||||
.iter()
|
||||
.map(|root| (root.plugin_id.as_key(), root.version.clone()))
|
||||
.collect::<HashSet<_>>();
|
||||
self.roots.extend(
|
||||
other
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|root| seen.insert((root.plugin_id.as_key(), root.version.clone())))
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn from_plugin_load_outcome(loaded_plugins: &PluginLoadOutcome, codex_home: &Path) -> Self {
|
||||
let primary_runtime_marketplace_root = primary_runtime_marketplace_root();
|
||||
let Ok(store) = PluginStore::try_new(codex_home.to_path_buf()) else {
|
||||
return Self::default();
|
||||
};
|
||||
let mut seen = HashSet::new();
|
||||
let roots = loaded_plugins
|
||||
.plugins()
|
||||
.iter()
|
||||
.filter(|plugin| plugin.is_active())
|
||||
.filter_map(|plugin| {
|
||||
let plugin_id = PluginId::parse(&plugin.config_name).ok()?;
|
||||
let expected_root = Self::expected_plugin_root(
|
||||
&store,
|
||||
codex_home,
|
||||
&plugin_id,
|
||||
primary_runtime_marketplace_root.as_deref(),
|
||||
)?;
|
||||
if plugin.root != expected_root || !expected_root.as_path().is_dir() {
|
||||
return None;
|
||||
}
|
||||
let version = expected_root.as_path().file_name()?.to_str()?.to_owned();
|
||||
let root = expected_root.canonicalize().ok()?;
|
||||
root.as_path().is_dir().then(|| TrustedPluginRoot {
|
||||
plugin_id,
|
||||
version,
|
||||
metrics_operations_by_path: load_plugin_metrics_operations(&root)
|
||||
.unwrap_or_default(),
|
||||
root,
|
||||
})
|
||||
})
|
||||
.filter(|root| seen.insert((root.plugin_id.as_key(), root.root.clone())))
|
||||
.collect();
|
||||
Self { roots }
|
||||
}
|
||||
|
||||
fn expected_plugin_root(
|
||||
store: &PluginStore,
|
||||
codex_home: &Path,
|
||||
plugin_id: &PluginId,
|
||||
primary_runtime_marketplace_root: Option<&Path>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
match plugin_id.marketplace_name.as_str() {
|
||||
REMOTE_GLOBAL_MARKETPLACE_NAME => {
|
||||
let active_version = store.active_plugin_version(plugin_id)?;
|
||||
if active_version == DEFAULT_PLUGIN_VERSION
|
||||
|| store.remote_plugin_id(plugin_id).ok().flatten().is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(store.plugin_root(plugin_id, &active_version))
|
||||
}
|
||||
OPENAI_CURATED_MARKETPLACE_NAME | OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
let curated_sha = read_curated_plugins_sha(codex_home)?;
|
||||
let expected_root =
|
||||
store.plugin_root(plugin_id, &curated_plugin_cache_version(&curated_sha));
|
||||
let marketplace_path = match plugin_id.marketplace_name.as_str() {
|
||||
OPENAI_CURATED_MARKETPLACE_NAME => curated_plugins_repo_path(codex_home)
|
||||
.join(".agents/plugins/marketplace.json"),
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME => {
|
||||
curated_plugins_api_marketplace_path(codex_home)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Self::marketplace_plugin(marketplace_path, plugin_id)?;
|
||||
Some(expected_root)
|
||||
}
|
||||
OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME => {
|
||||
let marketplace_root = primary_runtime_marketplace_root?;
|
||||
let expected_source_root = AbsolutePathBuf::from_absolute_path_checked(
|
||||
marketplace_root
|
||||
.join("plugins")
|
||||
.join(&plugin_id.plugin_name),
|
||||
)
|
||||
.ok()?;
|
||||
let marketplace_plugin = Self::marketplace_plugin(
|
||||
marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
plugin_id,
|
||||
)?;
|
||||
let MarketplacePluginSource::Local { path: source_root } =
|
||||
marketplace_plugin.source
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if source_root != expected_source_root {
|
||||
return None;
|
||||
}
|
||||
let plugin_version = plugin_version_for_source(source_root.as_path()).ok()?;
|
||||
Some(store.plugin_root(plugin_id, &plugin_version))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_plugin(
|
||||
marketplace_path: std::path::PathBuf,
|
||||
plugin_id: &PluginId,
|
||||
) -> Option<crate::marketplace::ResolvedMarketplacePlugin> {
|
||||
let marketplace_path =
|
||||
AbsolutePathBuf::from_absolute_path_checked(marketplace_path).ok()?;
|
||||
let plugin = find_marketplace_plugin(&marketplace_path, &plugin_id.plugin_name).ok()?;
|
||||
(plugin.plugin_id == *plugin_id).then_some(plugin)
|
||||
}
|
||||
|
||||
/// Resolves one exact command to one trusted plugin script.
|
||||
///
|
||||
/// Complex shell syntax, missing files, symlink escapes, and overlapping
|
||||
/// matches are all unattributed by design.
|
||||
pub fn resolve_attribution(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<PluginCommandAttribution> {
|
||||
self.local_candidate(command, cwd)
|
||||
.map(|candidate| candidate.attribution())
|
||||
}
|
||||
|
||||
/// Resolves one exact command to one trusted manifest-declared operation.
|
||||
pub fn resolve_metrics_operation(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<ResolvedPluginMetricsOperation> {
|
||||
self.local_candidate(command, cwd)?.metrics_operation()
|
||||
}
|
||||
|
||||
fn local_candidate(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<MatchedPluginScript<'_>> {
|
||||
let command = single_plain_command(command)?;
|
||||
let invocation = script_invocation(command.as_slice())?;
|
||||
let script = if Path::new(invocation.script).is_absolute() {
|
||||
AbsolutePathBuf::from_absolute_path_checked(invocation.script).ok()?
|
||||
} else {
|
||||
cwd.join(invocation.script)
|
||||
}
|
||||
.canonicalize()
|
||||
.ok()?;
|
||||
if !script.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut matches = self.roots.iter().filter_map(|root| {
|
||||
let relative_path = script
|
||||
.as_path()
|
||||
.strip_prefix(root.root.as_path())
|
||||
.ok()
|
||||
.filter(|relative_path| !relative_path.as_os_str().is_empty())?;
|
||||
Some(MatchedPluginScript {
|
||||
root,
|
||||
normalized_relative_path: normalized_relative_script_path(relative_path)?,
|
||||
})
|
||||
});
|
||||
let attribution = matches.next()?;
|
||||
matches.next().is_none().then_some(attribution)
|
||||
}
|
||||
|
||||
/// Resolves a trusted script on the selected executor filesystem.
|
||||
///
|
||||
/// Remote commands can use a path convention that the app-server host cannot
|
||||
/// canonicalize. Resolve aliases on that executor first, then match the
|
||||
/// canonical target to a trusted local plugin script with the same contents.
|
||||
/// Generic attribution accepts matching script bytes across plugin versions.
|
||||
pub async fn resolve_executor_attribution(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Option<PluginCommandAttribution> {
|
||||
self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Any)
|
||||
.await
|
||||
.map(|candidate| candidate.matched.attribution())
|
||||
}
|
||||
|
||||
/// Resolves one trusted executor script to one manifest-declared operation,
|
||||
/// requiring the executor's version to match the trusted declaration's version.
|
||||
pub async fn resolve_metrics_operation_in_filesystem(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
) -> Option<ResolvedPluginMetricsOperation> {
|
||||
self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Exact)
|
||||
.await?
|
||||
.matched
|
||||
.metrics_operation()
|
||||
}
|
||||
|
||||
async fn executor_candidate(
|
||||
&self,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
file_system: &dyn ExecutorFileSystem,
|
||||
version_match: PluginVersionMatch,
|
||||
) -> Option<ExecutorAttributionCandidate<'_>> {
|
||||
if self.roots.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let command = single_plain_command(command)?;
|
||||
let invocation = script_invocation(command.as_slice())?;
|
||||
let script = cwd.join(invocation.script).ok()?;
|
||||
// Preserve known script suffixes (including directory aliases), but avoid
|
||||
// an executor round trip for unrelated workspace scripts.
|
||||
let suffixes = normalized_script_suffixes(&script);
|
||||
if !self.roots.iter().any(|root| {
|
||||
suffixes.iter().any(|suffix| {
|
||||
executor_plugin_root_matches(&script, root, suffix, PluginVersionMatch::Any)
|
||||
|| root.root.join(suffix).as_path().is_file()
|
||||
})
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let script = file_system
|
||||
.canonicalize(&script, /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
let candidates = self.local_candidates_for_executor_script(&script, version_match);
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let metadata = file_system
|
||||
.get_metadata(
|
||||
&script,
|
||||
GetMetadataOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
if !metadata.is_file
|
||||
|| !candidates
|
||||
.iter()
|
||||
.any(|candidate| metadata.size == candidate.contents.len() as u64)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let contents = file_system
|
||||
.read_file(&script, ReadFileOptions::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
let mut matches = candidates
|
||||
.into_iter()
|
||||
.filter(|candidate| contents == candidate.contents);
|
||||
let candidate = matches.next()?;
|
||||
match version_match {
|
||||
PluginVersionMatch::Any => matches
|
||||
.all(|other| other.matched.attribution() == candidate.matched.attribution())
|
||||
.then_some(candidate),
|
||||
PluginVersionMatch::Exact => matches.next().is_none().then_some(candidate),
|
||||
}
|
||||
}
|
||||
|
||||
fn local_candidates_for_executor_script(
|
||||
&self,
|
||||
script: &PathUri,
|
||||
version_match: PluginVersionMatch,
|
||||
) -> Vec<ExecutorAttributionCandidate<'_>> {
|
||||
let suffixes = normalized_script_suffixes(script);
|
||||
self.roots
|
||||
.iter()
|
||||
.filter_map(|root| {
|
||||
let (script, normalized_relative_path) = suffixes.iter().find_map(|suffix| {
|
||||
if !executor_plugin_root_matches(script, root, suffix, version_match) {
|
||||
return None;
|
||||
}
|
||||
let script = root.root.join(suffix).canonicalize().ok()?;
|
||||
let relative_path = script.as_path().strip_prefix(root.root.as_path()).ok()?;
|
||||
if !script.as_path().is_file() {
|
||||
return None;
|
||||
}
|
||||
let normalized_relative_path = normalized_relative_script_path(relative_path)?;
|
||||
Some((script, normalized_relative_path))
|
||||
})?;
|
||||
Some(ExecutorAttributionCandidate {
|
||||
matched: MatchedPluginScript {
|
||||
root,
|
||||
normalized_relative_path,
|
||||
},
|
||||
contents: std::fs::read(script.as_path()).ok()?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
struct MatchedPluginScript<'a> {
|
||||
root: &'a TrustedPluginRoot,
|
||||
normalized_relative_path: String,
|
||||
}
|
||||
|
||||
impl MatchedPluginScript<'_> {
|
||||
fn attribution(&self) -> PluginCommandAttribution {
|
||||
PluginCommandAttribution {
|
||||
plugin_id: self.root.plugin_id.clone(),
|
||||
normalized_relative_path: self.normalized_relative_path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn metrics_operation(&self) -> Option<ResolvedPluginMetricsOperation> {
|
||||
Some(ResolvedPluginMetricsOperation {
|
||||
plugin_id: self.root.plugin_id.clone(),
|
||||
operation: self
|
||||
.root
|
||||
.metrics_operations_by_path
|
||||
.get(&self.normalized_relative_path)?
|
||||
.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ExecutorAttributionCandidate<'a> {
|
||||
matched: MatchedPluginScript<'a>,
|
||||
contents: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PluginVersionMatch {
|
||||
Any,
|
||||
Exact,
|
||||
}
|
||||
|
||||
fn normalized_script_suffixes(script: &PathUri) -> Vec<String> {
|
||||
let path = script.inferred_native_path_string().replace('\\', "/");
|
||||
let components = path
|
||||
.split('/')
|
||||
.filter(|component| !component.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
(0..components.len())
|
||||
.filter_map(|start| {
|
||||
let suffix = components[start..].join("/");
|
||||
is_safe_plugin_relative_path(&suffix).then_some(suffix)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn executor_plugin_root_matches(
|
||||
script: &PathUri,
|
||||
trusted: &TrustedPluginRoot,
|
||||
relative_path: &str,
|
||||
version_match: PluginVersionMatch,
|
||||
) -> bool {
|
||||
let relative_depth = relative_path.split('/').count();
|
||||
let Some(root) = script.ancestors().nth(relative_depth) else {
|
||||
return false;
|
||||
};
|
||||
let Some(cache_parent) = root.ancestors().nth(5) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(plugin_root) = cache_parent.join(&format!(
|
||||
"plugins/cache/{}/{}",
|
||||
trusted.plugin_id.marketplace_name, trusted.plugin_id.plugin_name
|
||||
)) else {
|
||||
return false;
|
||||
};
|
||||
match version_match {
|
||||
PluginVersionMatch::Any => root.parent().as_ref() == Some(&plugin_root),
|
||||
PluginVersionMatch::Exact => plugin_root
|
||||
.join(&trusted.version)
|
||||
.is_ok_and(|expected| expected == root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the structurally parsed arguments following a single script command.
|
||||
/// Callers must keep the values in-process and must not log or serialize them.
|
||||
pub fn command_script_arguments(command: &[String]) -> Option<Vec<String>> {
|
||||
let command = single_plain_command(command)?;
|
||||
Some(script_invocation(command.as_slice())?.arguments.to_vec())
|
||||
}
|
||||
|
||||
/// Converts a path already proven to be below a trusted plugin root into the
|
||||
/// only path shape that may leave the resolver: non-empty, relative, and
|
||||
/// slash-separated with no traversal or platform-specific prefixes.
|
||||
pub(crate) fn normalized_relative_script_path(relative_path: &Path) -> Option<String> {
|
||||
let normalized = relative_path
|
||||
.components()
|
||||
.map(|component| {
|
||||
let Component::Normal(component) = component else {
|
||||
return None;
|
||||
};
|
||||
component.to_str()
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?
|
||||
.join("/");
|
||||
|
||||
is_safe_plugin_relative_path(&normalized).then_some(normalized)
|
||||
}
|
||||
|
||||
fn single_plain_command(command: &[String]) -> Option<Vec<String>> {
|
||||
if let Some(commands) = parse_shell_lc_plain_commands(command) {
|
||||
let [command] = commands.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
return single_plain_command(command);
|
||||
}
|
||||
if let Some(script) = windows_shell_script(command) {
|
||||
let wrapper = ["sh".to_string(), "-lc".to_string(), script.to_string()];
|
||||
return single_plain_command(&wrapper);
|
||||
}
|
||||
if extract_bash_command(command).is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(command.to_vec())
|
||||
}
|
||||
|
||||
struct ScriptInvocation<'a> {
|
||||
script: &'a str,
|
||||
arguments: &'a [String],
|
||||
}
|
||||
|
||||
fn script_invocation(command: &[String]) -> Option<ScriptInvocation<'_>> {
|
||||
let [program, args @ ..] = command else {
|
||||
return None;
|
||||
};
|
||||
if let Some(interpreter) = interpreter_name(program) {
|
||||
return interpreter_script_invocation(&interpreter, args);
|
||||
}
|
||||
is_pathish(program).then_some(ScriptInvocation {
|
||||
script: program,
|
||||
arguments: args,
|
||||
})
|
||||
}
|
||||
|
||||
fn interpreter_name(program: &str) -> Option<String> {
|
||||
let basename = executable_basename(program)?;
|
||||
let basename = basename.to_ascii_lowercase();
|
||||
let basename = basename.strip_suffix(".exe").unwrap_or(&basename);
|
||||
matches!(
|
||||
basename,
|
||||
"bash"
|
||||
| "node"
|
||||
| "nodejs"
|
||||
| "perl"
|
||||
| "php"
|
||||
| "powershell"
|
||||
| "pwsh"
|
||||
| "python"
|
||||
| "python3"
|
||||
| "ruby"
|
||||
| "sh"
|
||||
| "zsh"
|
||||
)
|
||||
.then(|| basename.to_string())
|
||||
}
|
||||
|
||||
fn interpreter_script_invocation<'a>(
|
||||
interpreter: &str,
|
||||
args: &'a [String],
|
||||
) -> Option<ScriptInvocation<'a>> {
|
||||
if matches!(interpreter, "powershell" | "pwsh") {
|
||||
let [file_flag, script, arguments @ ..] = args else {
|
||||
return None;
|
||||
};
|
||||
return (file_flag.eq_ignore_ascii_case("-file") && !script.starts_with('-'))
|
||||
.then_some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
|
||||
let mut args = args;
|
||||
loop {
|
||||
match args {
|
||||
[separator, script, arguments @ ..]
|
||||
if separator == "--" && !script.starts_with('-') =>
|
||||
{
|
||||
return Some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
[flag, remaining @ ..] if safe_interpreter_flag(interpreter, flag) => {
|
||||
args = remaining;
|
||||
}
|
||||
[script, arguments @ ..] if !script.starts_with('-') => {
|
||||
return Some(ScriptInvocation { script, arguments });
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_interpreter_flag(interpreter: &str, flag: &str) -> bool {
|
||||
matches!(
|
||||
(interpreter, flag),
|
||||
("python" | "python3", "-u") | ("bash" | "sh" | "zsh", "-e")
|
||||
)
|
||||
}
|
||||
|
||||
fn executable_basename(program: &str) -> Option<&str> {
|
||||
program
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|basename| !basename.is_empty())
|
||||
}
|
||||
|
||||
fn windows_shell_script(command: &[String]) -> Option<&str> {
|
||||
let [program, args @ ..] = command else {
|
||||
return None;
|
||||
};
|
||||
let basename = executable_basename(program)?.to_ascii_lowercase();
|
||||
if matches!(basename.as_str(), "cmd" | "cmd.exe") {
|
||||
let [flag, script] = args else {
|
||||
return None;
|
||||
};
|
||||
return flag.eq_ignore_ascii_case("/c").then_some(script);
|
||||
}
|
||||
if !matches!(
|
||||
basename.as_str(),
|
||||
"powershell" | "powershell.exe" | "pwsh" | "pwsh.exe"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let [flags @ .., command_flag, script] = args else {
|
||||
return None;
|
||||
};
|
||||
if !matches!(
|
||||
command_flag.to_ascii_lowercase().as_str(),
|
||||
"-command" | "-c"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
flags
|
||||
.iter()
|
||||
.all(|flag| {
|
||||
matches!(
|
||||
flag.to_ascii_lowercase().as_str(),
|
||||
"-nologo" | "-noprofile" | "-noninteractive"
|
||||
)
|
||||
})
|
||||
.then_some(script)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "script_attribution_tests.rs"]
|
||||
mod tests;
|
||||
1179
codex-rs/core-plugins/src/script_attribution_tests.rs
Normal file
1179
codex-rs/core-plugins/src/script_attribution_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
34
codex-rs/core-plugins/src/skill_snapshots.rs
Normal file
34
codex-rs/core-plugins/src/skill_snapshots.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use codex_skills::LoadedSkillRoot;
|
||||
use codex_skills::SkillRootSnapshotCache;
|
||||
use codex_skills::SkillRootSnapshots;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
|
||||
#[derive(Default)]
|
||||
struct PluginSkillSnapshotCache {
|
||||
snapshots_by_root: Mutex<HashMap<PluginSkillRoot, LoadedSkillRoot>>,
|
||||
}
|
||||
|
||||
impl SkillRootSnapshotCache<PluginSkillRoot> for PluginSkillSnapshotCache {
|
||||
fn get(&self, root: &PluginSkillRoot) -> Option<LoadedSkillRoot> {
|
||||
self.snapshots_by_root
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(root)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn insert(&self, root: PluginSkillRoot, snapshot: LoadedSkillRoot) {
|
||||
self.snapshots_by_root
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(root, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new_plugin_skill_snapshots() -> SkillRootSnapshots<PluginSkillRoot> {
|
||||
SkillRootSnapshots::new(Arc::new(PluginSkillSnapshotCache::default()))
|
||||
}
|
||||
1125
codex-rs/core-plugins/src/startup_sync.rs
Normal file
1125
codex-rs/core-plugins/src/startup_sync.rs
Normal file
File diff suppressed because it is too large
Load Diff
37
codex-rs/core-plugins/src/startup_sync/http_client.rs
Normal file
37
codex-rs/core-plugins/src/startup_sync/http_client.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
//! HTTP transport for curated plugin startup sync.
|
||||
//!
|
||||
//! Both proxy modes retain the supplied application network policy. The default proxy mode also
|
||||
//! keeps the legacy fallback for invalid custom CA configuration; system-proxy mode fails closed.
|
||||
//! Startup-sync request helpers apply the standard Codex headers.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::http_client_selector::HttpClientSelector;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::RequestBuilder;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use http::Method;
|
||||
|
||||
pub(super) struct StartupSyncHttpClient(Arc<dyn HttpClientSelector>);
|
||||
|
||||
impl StartupSyncHttpClient {
|
||||
pub(super) fn new(http_client_factory: &HttpClientFactory) -> Self {
|
||||
let http_clients =
|
||||
RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
|
||||
http_client_factory.clone(),
|
||||
ClientRouteClass::Api,
|
||||
)
|
||||
.with_legacy_custom_ca_fallback();
|
||||
Self(Arc::new(http_clients))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn route_aware(http_clients: Arc<dyn HttpClientSelector>) -> Self {
|
||||
Self(http_clients)
|
||||
}
|
||||
|
||||
pub(super) fn request(&self, method: Method, url: &str) -> RequestBuilder {
|
||||
self.0.request(method, url)
|
||||
}
|
||||
}
|
||||
1487
codex-rs/core-plugins/src/startup_sync_tests.rs
Normal file
1487
codex-rs/core-plugins/src/startup_sync_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
764
codex-rs/core-plugins/src/store.rs
Normal file
764
codex-rs/core-plugins/src/store.rs
Normal file
@@ -0,0 +1,764 @@
|
||||
use crate::command_migration::migrate_plugin_commands;
|
||||
use crate::manifest::ManifestCache;
|
||||
use crate::manifest::PluginManifest;
|
||||
use crate::manifest::PluginManifestFormat;
|
||||
use crate::manifest::load_plugin_manifest;
|
||||
use crate::manifest::parse_plugin_manifest;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::validate_plugin_segment;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::AgentPluginSchemaStatus;
|
||||
use codex_utils_plugins::agent_plugin_schema_status;
|
||||
use codex_utils_plugins::find_plugin_manifest_path;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::cmp::Ordering;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use codex_core_plugin_common::installed::DEFAULT_PLUGIN_VERSION;
|
||||
pub use codex_core_plugin_common::installed::PLUGINS_CACHE_DIR;
|
||||
pub const PLUGINS_DATA_DIR: &str = "plugins/data";
|
||||
const AGENT_PLUGINS_DATA_DIR: &str = "agent-plugins";
|
||||
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_FILE;
|
||||
use codex_core_plugin_common::installed::REMOTE_PLUGIN_INSTALL_METADATA_SCHEMA_VERSION;
|
||||
const DEFAULT_AGENT_PLUGIN_VERSION: &str = "1.0.0";
|
||||
|
||||
use codex_core_plugin_common::installed::RemotePluginInstallMetadata;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginInstallResult {
|
||||
pub plugin_id: PluginId,
|
||||
pub plugin_version: String,
|
||||
pub installed_path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PluginStore {
|
||||
pub(crate) manifest_cache: Arc<ManifestCache>,
|
||||
codex_home: AbsolutePathBuf,
|
||||
root: AbsolutePathBuf,
|
||||
data_root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
pub(crate) struct ActivePluginInstallation {
|
||||
pub(crate) plugin_id: PluginId,
|
||||
pub(crate) root: AbsolutePathBuf,
|
||||
remote_plugin_install_metadata_path: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
impl ActivePluginInstallation {
|
||||
pub(crate) fn persisted_remote_plugin_id(&self) -> Result<Option<String>, PluginStoreError> {
|
||||
let contents = match fs::read_to_string(self.remote_plugin_install_metadata_path.as_path())
|
||||
{
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => {
|
||||
return Err(PluginStoreError::io(
|
||||
"failed to read remote plugin install metadata",
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
codex_core_plugin_common::installed::parse_remote_plugin_id(&contents)
|
||||
.map(Some)
|
||||
.map_err(PluginStoreError::Invalid)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum InstallManifest<'a> {
|
||||
OnDisk,
|
||||
Fallback(&'a str),
|
||||
}
|
||||
|
||||
impl PluginStore {
|
||||
pub fn new(codex_home: PathBuf) -> Self {
|
||||
Self::try_new(codex_home)
|
||||
.unwrap_or_else(|err| panic!("plugin cache root should be absolute: {err}"))
|
||||
}
|
||||
|
||||
pub fn try_new(codex_home: PathBuf) -> Result<Self, PluginStoreError> {
|
||||
let root = AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_CACHE_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin cache root", err))?;
|
||||
let data_root =
|
||||
AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_DATA_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin data root", err))?;
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path_checked(codex_home)
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve Codex home", err))?;
|
||||
|
||||
Ok(Self {
|
||||
manifest_cache: Arc::new(ManifestCache::default()),
|
||||
codex_home,
|
||||
root,
|
||||
data_root,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &AbsolutePathBuf {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn codex_home(&self) -> &AbsolutePathBuf {
|
||||
&self.codex_home
|
||||
}
|
||||
|
||||
pub fn plugin_base_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.root
|
||||
.join(&plugin_id.marketplace_name)
|
||||
.join(&plugin_id.plugin_name)
|
||||
}
|
||||
|
||||
pub fn plugin_root(&self, plugin_id: &PluginId, plugin_version: &str) -> AbsolutePathBuf {
|
||||
self.plugin_base_root(plugin_id).join(plugin_version)
|
||||
}
|
||||
|
||||
pub fn plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.data_root.join(format!(
|
||||
"{}-{}",
|
||||
plugin_id.plugin_name, plugin_id.marketplace_name
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn agent_plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(plugin_id.marketplace_name.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(plugin_id.plugin_name.as_bytes());
|
||||
self.data_root
|
||||
.join(AGENT_PLUGINS_DATA_DIR)
|
||||
.join(hex_prefix(&digest.finalize(), /*count*/ 32))
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_data_root(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
manifest_format: PluginManifestFormat,
|
||||
) -> AbsolutePathBuf {
|
||||
match manifest_format {
|
||||
PluginManifestFormat::AgentPlugin => self.agent_plugin_data_root(plugin_id),
|
||||
PluginManifestFormat::Legacy => self.plugin_data_root(plugin_id),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active_plugin_version(&self, plugin_id: &PluginId) -> Option<String> {
|
||||
codex_core_plugin_common::installed::active_plugin_version(
|
||||
&self.plugin_base_root(plugin_id),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn active_plugin_root(&self, plugin_id: &PluginId) -> Option<AbsolutePathBuf> {
|
||||
self.active_plugin_version(plugin_id)
|
||||
.map(|plugin_version| self.plugin_root(plugin_id, &plugin_version))
|
||||
}
|
||||
|
||||
pub(crate) fn active_plugin_installation(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Option<ActivePluginInstallation> {
|
||||
Some(ActivePluginInstallation {
|
||||
plugin_id: plugin_id.clone(),
|
||||
root: self.active_plugin_root(plugin_id)?,
|
||||
remote_plugin_install_metadata_path: self
|
||||
.remote_plugin_install_metadata_path(plugin_id),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_installed(&self, plugin_id: &PluginId) -> bool {
|
||||
self.active_plugin_version(plugin_id).is_some()
|
||||
}
|
||||
|
||||
pub fn remote_plugin_id(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Result<Option<String>, PluginStoreError> {
|
||||
let Some(installation) = self.active_plugin_installation(plugin_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
installation.persisted_remote_plugin_id()
|
||||
}
|
||||
|
||||
pub fn write_remote_plugin_id(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
if !self.is_installed(plugin_id) {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"cannot write remote identity for uninstalled plugin `{}`",
|
||||
plugin_id.as_key()
|
||||
)));
|
||||
}
|
||||
let remote_plugin_id = remote_plugin_id.trim();
|
||||
if remote_plugin_id.is_empty() {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid remote plugin install metadata: remote plugin id must not be blank"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
let path = self.remote_plugin_install_metadata_path(plugin_id);
|
||||
let parent = path.as_path().parent().ok_or_else(|| {
|
||||
PluginStoreError::Invalid(format!(
|
||||
"remote plugin install metadata path has no parent: {}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let mut contents = serde_json::to_vec_pretty(&RemotePluginInstallMetadata {
|
||||
schema_version: REMOTE_PLUGIN_INSTALL_METADATA_SCHEMA_VERSION,
|
||||
remote_plugin_id: remote_plugin_id.to_string(),
|
||||
})
|
||||
.map_err(|err| {
|
||||
PluginStoreError::Invalid(format!(
|
||||
"failed to serialize remote plugin install metadata: {err}"
|
||||
))
|
||||
})?;
|
||||
contents.push(b'\n');
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|err| {
|
||||
PluginStoreError::io(
|
||||
"failed to create temporary remote plugin install metadata",
|
||||
err,
|
||||
)
|
||||
})?;
|
||||
temporary.write_all(&contents).map_err(|err| {
|
||||
PluginStoreError::io("failed to write remote plugin install metadata", err)
|
||||
})?;
|
||||
temporary.as_file_mut().flush().map_err(|err| {
|
||||
PluginStoreError::io("failed to flush remote plugin install metadata", err)
|
||||
})?;
|
||||
temporary.persist(path.as_path()).map_err(|err| {
|
||||
PluginStoreError::io(
|
||||
"failed to persist remote plugin install metadata",
|
||||
err.error,
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_manifest(source_path, plugin_id, InstallManifest::OnDisk)
|
||||
}
|
||||
|
||||
pub(crate) fn install_with_fallback_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
manifest_contents: &str,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
InstallManifest::Fallback(manifest_contents),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn install_with_version(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_version_and_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
InstallManifest::OnDisk,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn install_with_version_and_fallback_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
manifest_contents: &str,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
self.install_with_version_and_manifest(
|
||||
source_path,
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
InstallManifest::Fallback(manifest_contents),
|
||||
)
|
||||
}
|
||||
|
||||
fn install_with_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
let manifest = resolve_install_manifest(source_path.as_path(), manifest);
|
||||
let plugin_version = plugin_version_for_install_manifest(source_path.as_path(), manifest)?;
|
||||
self.install_with_version_and_manifest(source_path, plugin_id, plugin_version, manifest)
|
||||
}
|
||||
|
||||
fn install_with_version_and_manifest(
|
||||
&self,
|
||||
source_path: AbsolutePathBuf,
|
||||
plugin_id: PluginId,
|
||||
plugin_version: String,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginInstallResult, PluginStoreError> {
|
||||
if !source_path.as_path().is_dir() {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin source path is not a directory: {}",
|
||||
source_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let manifest = resolve_install_manifest(source_path.as_path(), manifest);
|
||||
let plugin_name = plugin_name_for_source(source_path.as_path(), manifest)?;
|
||||
if plugin_name != plugin_id.plugin_name {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin.json name `{plugin_name}` does not match marketplace plugin name `{}`",
|
||||
plugin_id.plugin_name
|
||||
)));
|
||||
}
|
||||
validate_plugin_version_segment(&plugin_version).map_err(PluginStoreError::Invalid)?;
|
||||
let installed_path = self.plugin_root(&plugin_id, &plugin_version);
|
||||
replace_plugin_root_atomically(
|
||||
source_path.as_path(),
|
||||
self.plugin_base_root(&plugin_id).as_path(),
|
||||
&plugin_version,
|
||||
manifest,
|
||||
)?;
|
||||
self.remove_remote_plugin_install_metadata(&plugin_id)?;
|
||||
|
||||
Ok(PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
installed_path,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn uninstall(&self, plugin_id: &PluginId) -> Result<(), PluginStoreError> {
|
||||
remove_existing_target(self.plugin_base_root(plugin_id).as_path())
|
||||
}
|
||||
|
||||
fn remote_plugin_install_metadata_path(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.plugin_base_root(plugin_id)
|
||||
.join(REMOTE_PLUGIN_INSTALL_METADATA_FILE)
|
||||
}
|
||||
|
||||
fn remove_remote_plugin_install_metadata(
|
||||
&self,
|
||||
plugin_id: &PluginId,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let path = self.remote_plugin_install_metadata_path(plugin_id);
|
||||
match fs::remove_file(path.as_path()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(PluginStoreError::io(
|
||||
"failed to remove remote plugin install metadata",
|
||||
err,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PluginStoreError {
|
||||
#[error("{context}: {source}")]
|
||||
Io {
|
||||
context: &'static str,
|
||||
#[source]
|
||||
source: io::Error,
|
||||
},
|
||||
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl PluginStoreError {
|
||||
fn io(context: &'static str, source: io::Error) -> Self {
|
||||
Self::Io { context, source }
|
||||
}
|
||||
|
||||
pub(crate) fn sub_error_type(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Io { context, .. } => Some(error_context_sub_error_type(context)),
|
||||
Self::Invalid(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn error_context_sub_error_type(context: &str) -> String {
|
||||
context.to_ascii_lowercase().replace(' ', "_")
|
||||
}
|
||||
|
||||
pub fn plugin_version_for_source(source_path: &Path) -> Result<String, PluginStoreError> {
|
||||
plugin_version_for_install_manifest(source_path, InstallManifest::OnDisk)
|
||||
}
|
||||
|
||||
pub(crate) fn plugin_version_for_source_with_fallback_manifest(
|
||||
source_path: &Path,
|
||||
manifest_contents: &str,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let manifest =
|
||||
resolve_install_manifest(source_path, InstallManifest::Fallback(manifest_contents));
|
||||
plugin_version_for_install_manifest(source_path, manifest)
|
||||
}
|
||||
|
||||
fn resolve_install_manifest<'a>(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'a>,
|
||||
) -> InstallManifest<'a> {
|
||||
// A real plugin manifest always wins. The fallback only fills the gap for marketplace
|
||||
// sources that cannot be changed in place because they may be user-owned directories.
|
||||
match manifest {
|
||||
InstallManifest::Fallback(_) if find_plugin_manifest_path(source_path).is_some() => {
|
||||
InstallManifest::OnDisk
|
||||
}
|
||||
manifest => manifest,
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_version_for_install_manifest(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let (plugin_version, is_agent_plugin) =
|
||||
plugin_manifest_version_for_source(source_path, manifest)?;
|
||||
let plugin_version = plugin_version.unwrap_or_else(|| {
|
||||
if is_agent_plugin {
|
||||
DEFAULT_AGENT_PLUGIN_VERSION.to_string()
|
||||
} else {
|
||||
DEFAULT_PLUGIN_VERSION.to_string()
|
||||
}
|
||||
});
|
||||
match validate_plugin_version_segment(&plugin_version) {
|
||||
Ok(()) => Ok(plugin_version),
|
||||
Err(_) if is_agent_plugin => {
|
||||
let digest = Sha256::digest(plugin_version.as_bytes());
|
||||
Ok(format!(
|
||||
"agent-plugins-{}",
|
||||
hex_prefix(&digest, /*count*/ 12)
|
||||
))
|
||||
}
|
||||
Err(message) => Err(PluginStoreError::Invalid(message)),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_prefix(bytes: &[u8], count: usize) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut output = String::with_capacity(count.saturating_mul(2));
|
||||
for byte in bytes.iter().take(count) {
|
||||
output.push(HEX[usize::from(byte >> 4)] as char);
|
||||
output.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub fn validate_plugin_version_segment(plugin_version: &str) -> Result<(), String> {
|
||||
codex_core_plugin_common::installed::validate_plugin_version_segment(plugin_version)
|
||||
}
|
||||
|
||||
fn plugin_manifest_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<PluginManifest, PluginStoreError> {
|
||||
match manifest {
|
||||
InstallManifest::OnDisk => load_plugin_manifest(source_path)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing or invalid plugin.json".to_string())),
|
||||
InstallManifest::Fallback(contents) => parse_plugin_manifest(
|
||||
source_path,
|
||||
&source_path.join(".codex-plugin/plugin.json"),
|
||||
contents,
|
||||
)
|
||||
.map_err(|err| PluginStoreError::Invalid(format!("failed to parse plugin.json: {err}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RawPluginManifestVersion {
|
||||
#[serde(default)]
|
||||
version: Option<JsonValue>,
|
||||
}
|
||||
|
||||
fn plugin_manifest_version_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<(Option<String>, bool), PluginStoreError> {
|
||||
let contents = match manifest {
|
||||
InstallManifest::OnDisk => {
|
||||
let manifest_path = find_plugin_manifest_path(source_path)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing plugin.json".to_string()))?;
|
||||
fs::read_to_string(&manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin.json", err))?
|
||||
}
|
||||
InstallManifest::Fallback(contents) => contents.to_string(),
|
||||
};
|
||||
let is_agent_plugin =
|
||||
agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported;
|
||||
let manifest: RawPluginManifestVersion = serde_json::from_str(&contents)
|
||||
.map_err(|err| PluginStoreError::Invalid(format!("failed to parse plugin.json: {err}")))?;
|
||||
let Some(version) = manifest.version else {
|
||||
return Ok((None, is_agent_plugin));
|
||||
};
|
||||
let Some(version) = version.as_str() else {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid plugin version in plugin.json: expected string".to_string(),
|
||||
));
|
||||
};
|
||||
if is_agent_plugin {
|
||||
let version = version.trim();
|
||||
return Ok(((!version.is_empty()).then(|| version.to_string()), true));
|
||||
}
|
||||
let version = version.trim();
|
||||
if version.is_empty() {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"invalid plugin version in plugin.json: must not be blank".to_string(),
|
||||
));
|
||||
}
|
||||
Ok((Some(version.to_string()), false))
|
||||
}
|
||||
|
||||
fn plugin_name_for_source(
|
||||
source_path: &Path,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<String, PluginStoreError> {
|
||||
let manifest = plugin_manifest_for_source(source_path, manifest)?;
|
||||
|
||||
let plugin_name = manifest.name;
|
||||
validate_plugin_segment(&plugin_name, "plugin name")
|
||||
.map_err(PluginStoreError::Invalid)
|
||||
.map(|_| plugin_name)
|
||||
}
|
||||
|
||||
fn remove_existing_target(path: &Path) -> Result<(), PluginStoreError> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if path.is_dir() {
|
||||
fs::remove_dir_all(path).map_err(|err| {
|
||||
PluginStoreError::io("failed to remove existing plugin cache entry", err)
|
||||
})
|
||||
} else {
|
||||
fs::remove_file(path).map_err(|err| {
|
||||
PluginStoreError::io("failed to remove existing plugin cache entry", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_plugin_root_atomically(
|
||||
source: &Path,
|
||||
target_root: &Path,
|
||||
plugin_version: &str,
|
||||
manifest: InstallManifest<'_>,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let Some(parent) = target_root.parent() else {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin cache path has no parent: {}",
|
||||
target_root.display()
|
||||
)));
|
||||
};
|
||||
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|err| PluginStoreError::io("failed to create plugin cache directory", err))?;
|
||||
|
||||
let Some(plugin_dir_name) = target_root.file_name() else {
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"plugin cache path has no directory name: {}",
|
||||
target_root.display()
|
||||
)));
|
||||
};
|
||||
let staged_dir = tempfile::Builder::new()
|
||||
.prefix("plugin-install-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
PluginStoreError::io("failed to create temporary plugin cache directory", err)
|
||||
})?;
|
||||
let staged_root = staged_dir.path().join(plugin_dir_name);
|
||||
let staged_version_root = staged_root.join(plugin_version);
|
||||
let (source_manifest_relative_path, source_manifest_contents) = match manifest {
|
||||
InstallManifest::OnDisk => {
|
||||
let manifest_path = find_plugin_manifest_path(source)
|
||||
.ok_or_else(|| PluginStoreError::Invalid("missing plugin.json".to_string()))?;
|
||||
let relative_path = manifest_path
|
||||
.strip_prefix(source)
|
||||
.map_err(|_| {
|
||||
PluginStoreError::Invalid(
|
||||
"plugin manifest is outside the plugin source".to_string(),
|
||||
)
|
||||
})?
|
||||
.to_path_buf();
|
||||
let contents = fs::read(&manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin.json", err))?;
|
||||
(relative_path, contents)
|
||||
}
|
||||
InstallManifest::Fallback(contents) => (
|
||||
PathBuf::from(".codex-plugin/plugin.json"),
|
||||
contents.as_bytes().to_vec(),
|
||||
),
|
||||
};
|
||||
copy_dir_recursive(source, &staged_version_root)?;
|
||||
if let InstallManifest::Fallback(contents) = manifest {
|
||||
// Inject the generated manifest into Store's existing atomic copy so install does not
|
||||
// mutate the original source or require a second staging directory.
|
||||
let manifest_path = staged_version_root.join(".codex-plugin/plugin.json");
|
||||
let Some(manifest_parent) = manifest_path.parent() else {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest path has no parent".to_string(),
|
||||
));
|
||||
};
|
||||
fs::create_dir_all(manifest_parent).map_err(|err| {
|
||||
PluginStoreError::io("failed to create plugin manifest directory", err)
|
||||
})?;
|
||||
fs::write(&manifest_path, contents)
|
||||
.map_err(|err| PluginStoreError::io("failed to write fallback plugin manifest", err))?;
|
||||
}
|
||||
let staged_manifest_path =
|
||||
find_plugin_manifest_path(&staged_version_root).ok_or_else(|| {
|
||||
PluginStoreError::Invalid(
|
||||
"plugin manifest is missing after installation staging".to_string(),
|
||||
)
|
||||
})?;
|
||||
if staged_manifest_path != staged_version_root.join(&source_manifest_relative_path) {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest changed during installation staging".to_string(),
|
||||
));
|
||||
}
|
||||
let staged_manifest_contents = fs::read(&staged_manifest_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to read staged plugin.json", err))?;
|
||||
if staged_manifest_contents != source_manifest_contents {
|
||||
return Err(PluginStoreError::Invalid(
|
||||
"plugin manifest contents changed during installation staging".to_string(),
|
||||
));
|
||||
}
|
||||
let is_agent_plugin = fs::read_to_string(staged_version_root.join("plugin.json"))
|
||||
.ok()
|
||||
.is_some_and(|contents| {
|
||||
agent_plugin_schema_status(&contents) == AgentPluginSchemaStatus::Supported
|
||||
});
|
||||
if !is_agent_plugin && let Err(err) = migrate_plugin_commands(&staged_version_root) {
|
||||
tracing::warn!(%err, "failed to migrate plugin commands into skills");
|
||||
}
|
||||
|
||||
let target_version_root = target_root.join(plugin_version);
|
||||
if target_root.exists() && !target_version_root.exists() {
|
||||
fs::rename(&staged_version_root, &target_version_root).map_err(|err| {
|
||||
PluginStoreError::io("failed to activate updated plugin cache version", err)
|
||||
})?;
|
||||
remove_old_plugin_versions(target_root, plugin_version)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if target_root.exists() {
|
||||
let backup_dir = tempfile::Builder::new()
|
||||
.prefix("plugin-backup-")
|
||||
.tempdir_in(parent)
|
||||
.map_err(|err| {
|
||||
PluginStoreError::io("failed to create plugin cache backup directory", err)
|
||||
})?;
|
||||
let backup_root = backup_dir.path().join(plugin_dir_name);
|
||||
fs::rename(target_root, &backup_root)
|
||||
.map_err(|err| PluginStoreError::io("failed to back up plugin cache entry", err))?;
|
||||
|
||||
if let Err(err) = fs::rename(&staged_root, target_root) {
|
||||
let rollback_result = fs::rename(&backup_root, target_root);
|
||||
return match rollback_result {
|
||||
Ok(()) => Err(PluginStoreError::io(
|
||||
"failed to activate updated plugin cache entry",
|
||||
err,
|
||||
)),
|
||||
Err(rollback_err) => {
|
||||
let backup_path = backup_dir.keep().join(plugin_dir_name);
|
||||
Err(PluginStoreError::Invalid(format!(
|
||||
"failed to activate updated plugin cache entry at {}: {err}; failed to restore previous cache entry (left at {}): {rollback_err}",
|
||||
target_root.display(),
|
||||
backup_path.display()
|
||||
)))
|
||||
}
|
||||
};
|
||||
}
|
||||
} else {
|
||||
fs::rename(&staged_root, target_root)
|
||||
.map_err(|err| PluginStoreError::io("failed to activate plugin cache entry", err))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_old_plugin_versions(
|
||||
target_root: &Path,
|
||||
plugin_version: &str,
|
||||
) -> Result<(), PluginStoreError> {
|
||||
let Ok(entries) = fs::read_dir(target_root) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for entry in entries.filter_map(Result::ok) {
|
||||
let Ok(file_type) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if !file_type.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Ok(version) = entry.file_name().into_string() else {
|
||||
continue;
|
||||
};
|
||||
if version == plugin_version || validate_plugin_version_segment(&version).is_err() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if fs::remove_dir_all(entry.path()).is_err()
|
||||
&& old_plugin_version_would_stay_active(&version, plugin_version)
|
||||
{
|
||||
return Err(PluginStoreError::Invalid(format!(
|
||||
"failed to activate updated plugin cache version `{plugin_version}` while `{version}` remains active"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn old_plugin_version_would_stay_active(old_version: &str, new_version: &str) -> bool {
|
||||
old_version == DEFAULT_PLUGIN_VERSION
|
||||
|| compare_plugin_versions(old_version, new_version).is_gt()
|
||||
}
|
||||
|
||||
fn compare_plugin_versions(left: &str, right: &str) -> Ordering {
|
||||
codex_core_plugin_common::installed::compare_plugin_versions(left, right)
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(source: &Path, target: &Path) -> Result<(), PluginStoreError> {
|
||||
fs::create_dir_all(target)
|
||||
.map_err(|err| PluginStoreError::io("failed to create plugin target directory", err))?;
|
||||
|
||||
for entry in fs::read_dir(source)
|
||||
.map_err(|err| PluginStoreError::io("failed to read plugin source directory", err))?
|
||||
{
|
||||
let entry =
|
||||
entry.map_err(|err| PluginStoreError::io("failed to enumerate plugin source", err))?;
|
||||
let source_path = entry.path();
|
||||
let target_path = target.join(entry.file_name());
|
||||
let file_type = entry
|
||||
.file_type()
|
||||
.map_err(|err| PluginStoreError::io("failed to inspect plugin source entry", err))?;
|
||||
|
||||
if file_type.is_dir() {
|
||||
copy_dir_recursive(&source_path, &target_path)?;
|
||||
} else if file_type.is_file() {
|
||||
fs::copy(&source_path, &target_path)
|
||||
.map_err(|err| PluginStoreError::io("failed to copy plugin file", err))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "store_tests.rs"]
|
||||
mod tests;
|
||||
749
codex-rs/core-plugins/src/store_tests.rs
Normal file
749
codex-rs/core-plugins/src/store_tests.rs
Normal file
@@ -0,0 +1,749 @@
|
||||
use super::*;
|
||||
use codex_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_plugin_with_version(
|
||||
root: &Path,
|
||||
dir_name: &str,
|
||||
manifest_name: &str,
|
||||
manifest_version: Option<&str>,
|
||||
) {
|
||||
let plugin_root = root.join(dir_name);
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap();
|
||||
fs::create_dir_all(plugin_root.join("skills")).unwrap();
|
||||
let version = manifest_version
|
||||
.map(|manifest_version| format!(r#","version":"{manifest_version}""#))
|
||||
.unwrap_or_default();
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
format!(r#"{{"name":"{manifest_name}"{version}}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(plugin_root.join("skills/SKILL.md"), "skill").unwrap();
|
||||
fs::write(plugin_root.join(".mcp.json"), r#"{"mcpServers":{}}"#).unwrap();
|
||||
}
|
||||
|
||||
fn write_plugin(root: &Path, dir_name: &str, manifest_name: &str) {
|
||||
write_plugin_with_version(
|
||||
root,
|
||||
dir_name,
|
||||
manifest_name,
|
||||
/*manifest_version*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_new_rejects_relative_codex_home() {
|
||||
let err = PluginStore::try_new(PathBuf::from("relative"))
|
||||
.expect_err("relative codex home should fail");
|
||||
let err = err.to_string().replace('\\', "/");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"failed to resolve plugin cache root: path is not absolute: relative/plugins/cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_copies_plugin_into_default_marketplace() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join("plugins/cache/debug/sample-plugin/local");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "local".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
assert!(installed_path.join("skills/SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_accepts_manifest_mcp_server_objects() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("counter-sample");
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "counter-sample",
|
||||
"version": "1.1.1",
|
||||
"mcpServers": {
|
||||
"counter": {
|
||||
"type": "http",
|
||||
"url": "https://sample.example/counter/mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("counter-sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(plugin_root).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join("plugins/cache/debug/counter-sample/1.1.1");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "1.1.1".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_rejects_symlinked_manifest_that_hides_lower_precedence_mcp_server() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("manifest-switch");
|
||||
let codex_path = plugin_root.join(".codex-plugin/plugin.json");
|
||||
let claude_path = plugin_root.join(".claude-plugin/plugin.json");
|
||||
fs::create_dir_all(codex_path.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(claude_path.parent().unwrap()).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("benign.json"),
|
||||
r#"{"name":"manifest-switch","version":"1.2.3"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("../benign.json", &codex_path).unwrap();
|
||||
fs::write(
|
||||
&claude_path,
|
||||
r#"{"name":"manifest-switch","version":"1.2.3","mcpServers":{"hidden":{"command":"/bin/sh"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("manifest-switch".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect_err("a symlinked manifest must not conceal a different installed manifest");
|
||||
|
||||
assert_eq!(err.to_string(), "missing plugin.json");
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/manifest-switch")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_rejects_symlinked_manifest_directory() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("manifest-switch");
|
||||
let manifest_directory = tmp.path().join("manifest-directory");
|
||||
let claude_path = plugin_root.join(".claude-plugin/plugin.json");
|
||||
fs::create_dir_all(&manifest_directory).unwrap();
|
||||
fs::create_dir_all(claude_path.parent().unwrap()).unwrap();
|
||||
fs::write(
|
||||
manifest_directory.join("plugin.json"),
|
||||
r#"{"name":"manifest-switch"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(&claude_path, r#"{"name":"manifest-switch"}"#).unwrap();
|
||||
std::os::unix::fs::symlink(&manifest_directory, plugin_root.join(".codex-plugin")).unwrap();
|
||||
let plugin_id = PluginId::new("manifest-switch".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect_err("a symlinked manifest directory must not conceal a different manifest");
|
||||
|
||||
assert_eq!(err.to_string(), "missing plugin.json");
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/manifest-switch")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_uses_manifest_name_for_destination_and_key() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "manifest-name");
|
||||
let plugin_id = PluginId::new("manifest-name".to_string(), "market".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "local".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(
|
||||
tmp.path().join("plugins/cache/market/manifest-name/local"),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_root_derives_path_from_key_and_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.plugin_root(&plugin_id, "local").as_path(),
|
||||
tmp.path().join("plugins/cache/debug/sample/local")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_data_root_derives_path_from_key() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.plugin_data_root(&plugin_id).as_path(),
|
||||
tmp.path().join("plugins/data/sample-debug")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_data_root_is_stable_and_unambiguous() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let first = PluginId::new("a-b".to_string(), "c".to_string()).unwrap();
|
||||
let second = PluginId::new("a".to_string(), "b-c".to_string()).unwrap();
|
||||
|
||||
let first_root = store.agent_plugin_data_root(&first);
|
||||
let second_root = store.agent_plugin_data_root(&second);
|
||||
let expected_parent = tmp.path().join("plugins/data/agent-plugins");
|
||||
|
||||
assert_ne!(first_root, second_root);
|
||||
assert_eq!(
|
||||
first_root.as_path(),
|
||||
expected_parent.join("6920dd17774030852d11d1b94758fcaae4f894c7b2f36301ed174bc3b33e0743")
|
||||
);
|
||||
assert_eq!(
|
||||
second_root.as_path(),
|
||||
expected_parent.join("fa89b988ebbe54a68fdcbeb87fb913a5238d482084a3cee49a86288c2d45fa90")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_with_version_uses_requested_cache_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id =
|
||||
PluginId::new("sample-plugin".to_string(), "openai-curated".to_string()).unwrap();
|
||||
let plugin_version = "0123456789abcdef".to_string();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_version(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
plugin_version.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp.path().join(format!(
|
||||
"plugins/cache/openai-curated/sample-plugin/{plugin_version}"
|
||||
));
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version,
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_plugin_install_metadata_follows_installed_cache_lifecycle() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new(
|
||||
"sample-plugin".to_string(),
|
||||
"openai-curated-remote".to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let source = AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap();
|
||||
|
||||
store
|
||||
.install(source.clone(), plugin_id.clone())
|
||||
.expect("install plugin");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_sample")
|
||||
.expect("write remote identity");
|
||||
let metadata_path = store.remote_plugin_install_metadata_path(&plugin_id);
|
||||
assert_eq!(
|
||||
metadata_path.as_path().file_name(),
|
||||
Some(std::ffi::OsStr::new(".codex-remote-plugin-install.json"))
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&fs::read_to_string(metadata_path.as_path()).expect("read install metadata")
|
||||
)
|
||||
.expect("parse install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": "plugins~Plugin_sample",
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
store.remote_plugin_id(&plugin_id).unwrap(),
|
||||
Some("plugins~Plugin_sample".to_string())
|
||||
);
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_updated")
|
||||
.expect("replace remote identity");
|
||||
assert_eq!(
|
||||
store.remote_plugin_id(&plugin_id).unwrap(),
|
||||
Some("plugins~Plugin_updated".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
&fs::read_to_string(metadata_path.as_path()).expect("read updated install metadata")
|
||||
)
|
||||
.expect("parse updated install metadata"),
|
||||
json!({
|
||||
"schema_version": 1,
|
||||
"remote_plugin_id": "plugins~Plugin_updated",
|
||||
})
|
||||
);
|
||||
|
||||
store
|
||||
.install(source, plugin_id.clone())
|
||||
.expect("replace with local install");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
assert!(!metadata_path.as_path().exists());
|
||||
|
||||
store
|
||||
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_sample")
|
||||
.expect("restore remote identity");
|
||||
store.uninstall(&plugin_id).expect("uninstall plugin");
|
||||
assert_eq!(store.remote_plugin_id(&plugin_id).unwrap(), None);
|
||||
assert!(!metadata_path.as_path().exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_plugin_install_metadata_rejects_unsupported_schema_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "sample-plugin", "sample-plugin");
|
||||
let plugin_id = PluginId::new(
|
||||
"sample-plugin".to_string(),
|
||||
"openai-curated-remote".to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.expect("install plugin");
|
||||
fs::write(
|
||||
store
|
||||
.remote_plugin_install_metadata_path(&plugin_id)
|
||||
.as_path(),
|
||||
r#"{"schema_version":2,"remote_plugin_id":"plugins~Plugin_sample"}"#,
|
||||
)
|
||||
.expect("write unsupported install metadata");
|
||||
|
||||
let err = store
|
||||
.remote_plugin_id(&plugin_id)
|
||||
.expect_err("unsupported schema version should fail");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"unsupported remote plugin install metadata schema version: 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_prefers_on_disk_manifest_version_over_fallback() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin_with_version(
|
||||
tmp.path(),
|
||||
"sample-plugin",
|
||||
"sample-plugin",
|
||||
Some("1.2.3-beta+7"),
|
||||
);
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_fallback_manifest(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
r#"{"name":"sample-plugin","version":"9.9.9"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let installed_path = tmp
|
||||
.path()
|
||||
.join("plugins/cache/debug/sample-plugin/1.2.3-beta+7");
|
||||
assert_eq!(
|
||||
result,
|
||||
PluginInstallResult {
|
||||
plugin_id,
|
||||
plugin_version: "1.2.3-beta+7".to_string(),
|
||||
installed_path: AbsolutePathBuf::try_from(installed_path.clone()).unwrap(),
|
||||
}
|
||||
);
|
||||
assert!(installed_path.join(".codex-plugin/plugin.json").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_stages_fallback_manifest_when_source_has_no_manifest() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("fallback-plugin");
|
||||
fs::create_dir_all(plugin_root.join("skills")).unwrap();
|
||||
let manifest = r#"{"name":"fallback-plugin","version":"1.2.3"}"#;
|
||||
let plugin_id = PluginId::new("fallback-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install_with_fallback_manifest(
|
||||
AbsolutePathBuf::try_from(plugin_root).unwrap(),
|
||||
plugin_id,
|
||||
manifest,
|
||||
)
|
||||
.expect("install plugin with fallback manifest");
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(result.installed_path.join(".codex-plugin/plugin.json")).unwrap(),
|
||||
manifest,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_blank_manifest_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin_with_version(tmp.path(), "sample-plugin", "sample-plugin", Some(" "));
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("sample-plugin")).unwrap(),
|
||||
plugin_id,
|
||||
)
|
||||
.expect_err("blank manifest version should be rejected");
|
||||
let err = err.to_string().replace('\\', "/");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
"invalid plugin version in plugin.json: must not be blank"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_blank_version_uses_default_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
fs::create_dir_all(&plugin_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin","version":" "}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert_eq!(result.plugin_version, DEFAULT_AGENT_PLUGIN_VERSION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_plugin_install_does_not_migrate_commands() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
fs::create_dir_all(plugin_root.join("commands")).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin","commands":"./commands"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(plugin_root.join("commands/demo.md"), "# Demo").unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(
|
||||
!result
|
||||
.installed_path
|
||||
.join(".codex-plugin/migrated-command-skills")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn agent_plugin_install_skips_symlinked_skill_file() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
let skill_root = plugin_root.join("skills/greet");
|
||||
fs::create_dir_all(&skill_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let outside_skill = tmp.path().join("outside-SKILL.md");
|
||||
fs::write(&outside_skill, "---\nname: greet\n---\n").unwrap();
|
||||
std::os::unix::fs::symlink(&outside_skill, skill_root.join("SKILL.md")).unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(result.installed_path.join("plugin.json").is_file());
|
||||
assert!(!result.installed_path.join("skills/greet/SKILL.md").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn agent_plugin_install_skips_symlinked_executable() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let plugin_root = tmp.path().join("agent-plugin");
|
||||
let bin_root = plugin_root.join("bin");
|
||||
fs::create_dir_all(&bin_root).unwrap();
|
||||
fs::write(
|
||||
plugin_root.join("plugin.json"),
|
||||
r#"{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name":"agent-plugin"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let outside_executable = tmp.path().join("outside-tool");
|
||||
fs::write(&outside_executable, "#!/bin/sh\n").unwrap();
|
||||
std::os::unix::fs::symlink(&outside_executable, bin_root.join("tool")).unwrap();
|
||||
let plugin_id = PluginId::new("agent-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
let result = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(AbsolutePathBuf::try_from(plugin_root).unwrap(), plugin_id)
|
||||
.expect("install Agent Plugin");
|
||||
|
||||
assert!(result.installed_path.join("plugin.json").is_file());
|
||||
assert!(!result.installed_path.join("bin/tool").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_reads_version_directory_name() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/local",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("local".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
store.active_plugin_root(&plugin_id).unwrap().as_path(),
|
||||
tmp.path().join("plugins/cache/debug/sample-plugin/local")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_prefers_default_local_version_when_multiple_versions_exist() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/0123456789abcdef",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/local",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("local".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_returns_latest_version_when_default_is_missing() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/0123456789abcdef",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/fedcba9876543210",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("fedcba9876543210".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_plugin_version_compares_semver_versions_semantically() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/9.0.0",
|
||||
"sample-plugin",
|
||||
);
|
||||
write_plugin(
|
||||
&tmp.path().join("plugins/cache/debug"),
|
||||
"sample-plugin/10.0.0",
|
||||
"sample-plugin",
|
||||
);
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("10.0.0".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_with_new_version_keeps_existing_plugin_root_and_prunes_old_versions() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample-plugin".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
write_plugin_with_version(tmp.path(), "v1", "sample-plugin", Some("1.0.0"));
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("v1")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
write_plugin_with_version(tmp.path(), "v2", "sample-plugin", Some("2.0.0"));
|
||||
store
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("v2")).unwrap(),
|
||||
plugin_id.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.active_plugin_version(&plugin_id),
|
||||
Some("2.0.0".to_string())
|
||||
);
|
||||
assert!(
|
||||
tmp.path()
|
||||
.join("plugins/cache/debug/sample-plugin/2.0.0")
|
||||
.is_dir()
|
||||
);
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("plugins/cache/debug/sample-plugin/1.0.0")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_plugin_version_would_stay_active_for_local_or_later_versions() {
|
||||
assert!(old_plugin_version_would_stay_active(
|
||||
DEFAULT_PLUGIN_VERSION,
|
||||
"1.0.0"
|
||||
));
|
||||
assert!(old_plugin_version_would_stay_active("10.0.0", "9.0.0"));
|
||||
assert!(!old_plugin_version_would_stay_active("1.0.0", "2.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_root_rejects_path_separators_in_key_segments() {
|
||||
let err = PluginId::parse("../../etc@debug").unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid plugin name: dots must separate non-empty name segments in `../../etc@debug`"
|
||||
);
|
||||
|
||||
let err = PluginId::parse("sample@../../etc").unwrap_err();
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed in `sample@../../etc`"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_manifest_names_with_path_separators() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "../../etc");
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
PluginId::new("source-dir".to_string(), "debug".to_string()).unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid plugin name: dots must separate non-empty name segments"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_marketplace_names_with_path_separators() {
|
||||
let err = PluginId::new("sample-plugin".to_string(), "../../etc".to_string()).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid marketplace name: only ASCII letters, digits, `_`, and `-` are allowed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_rejects_manifest_names_that_do_not_match_marketplace_plugin_name() {
|
||||
let tmp = tempdir().unwrap();
|
||||
write_plugin(tmp.path(), "source-dir", "manifest-name");
|
||||
|
||||
let err = PluginStore::new(tmp.path().to_path_buf())
|
||||
.install(
|
||||
AbsolutePathBuf::try_from(tmp.path().join("source-dir")).unwrap(),
|
||||
PluginId::new("different-name".to_string(), "debug".to_string()).unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"plugin.json name `manifest-name` does not match marketplace plugin name `different-name`"
|
||||
);
|
||||
}
|
||||
566
codex-rs/core-plugins/src/test_support.rs
Normal file
566
codex-rs/core-plugins/src/test_support.rs
Normal file
@@ -0,0 +1,566 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::OPENAI_API_CURATED_MARKETPLACE_NAME;
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::PluginsConfigInput;
|
||||
use crate::PluginsManager;
|
||||
use crate::http_client_selector::HttpClientSelector;
|
||||
use crate::remote::RemotePluginServiceConfig;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RequestBuilder;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_login::auth::BedrockAccessKeysAuth;
|
||||
use codex_login::auth::BedrockApiKeyAuth;
|
||||
use codex_login::test_support::auth_manager_from_optional_auth;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_runtime_agent_instance::RuntimeAuthSlot;
|
||||
use codex_skills::LoadedSkillRoot;
|
||||
use codex_skills::LoadedSkills;
|
||||
use codex_skills::SkillError;
|
||||
use codex_skills::SkillLoadFuture;
|
||||
use codex_skills::SkillMetadata;
|
||||
use codex_skills::SkillRootLoadRequest;
|
||||
use codex_skills::SkillRootLoader;
|
||||
use codex_skills::parse_skill_frontmatter_metadata;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::PluginSkillRoot;
|
||||
use codex_utils_plugins::SkillDiscoveryMode;
|
||||
use codex_utils_plugins::migrated_command_skills_root;
|
||||
use http::Method;
|
||||
use toml::Value;
|
||||
|
||||
pub(crate) const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
pub(crate) const TEST_CURATED_PLUGIN_CACHE_VERSION: &str = "01234567";
|
||||
|
||||
#[cfg(windows)]
|
||||
/// Model redirected directories without requiring Windows symlink privileges.
|
||||
pub(crate) fn create_directory_junction(target: &Path, alias: &Path) {
|
||||
let output = codex_utils_process::background_command("cmd")
|
||||
.args(["/D", "/C", "mklink", "/J"])
|
||||
.arg(alias)
|
||||
.arg(target)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "mklink /J failed: {output:?}");
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager(codex_home: PathBuf) -> PluginsManager {
|
||||
PluginsManager::new(
|
||||
codex_home,
|
||||
test_auth_manager(/*auth_mode*/ None),
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager_with_options(
|
||||
codex_home: PathBuf,
|
||||
restriction_product: Option<Product>,
|
||||
auth_mode: Option<AuthMode>,
|
||||
) -> PluginsManager {
|
||||
PluginsManager::new_with_options(
|
||||
codex_home,
|
||||
restriction_product,
|
||||
test_auth_manager(auth_mode),
|
||||
RuntimeAuthSlot::default(),
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_plugins_manager_with_auth_manager(
|
||||
codex_home: PathBuf,
|
||||
restriction_product: Option<Product>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
) -> PluginsManager {
|
||||
PluginsManager::new_with_options(
|
||||
codex_home,
|
||||
restriction_product,
|
||||
auth_manager,
|
||||
RuntimeAuthSlot::default(),
|
||||
test_skill_root_loader(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn test_auth_manager(auth_mode: Option<AuthMode>) -> Arc<AuthManager> {
|
||||
auth_manager_from_optional_auth(test_codex_auth(auth_mode))
|
||||
}
|
||||
|
||||
pub(crate) async fn set_test_auth_mode(auth_manager: &AuthManager, auth_mode: Option<AuthMode>) {
|
||||
set_test_auth(auth_manager, test_codex_auth(auth_mode)).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn set_test_auth(auth_manager: &AuthManager, auth: Option<CodexAuth>) {
|
||||
let Some(auth) = auth else {
|
||||
auth_manager.clear_external_auth();
|
||||
return;
|
||||
};
|
||||
auth_manager
|
||||
.set_external_auth(Arc::new(StaticExternalAuth(auth)))
|
||||
.await
|
||||
.expect("test auth should update");
|
||||
}
|
||||
|
||||
fn test_codex_auth(auth_mode: Option<AuthMode>) -> Option<CodexAuth> {
|
||||
auth_mode.map(|auth_mode| match auth_mode {
|
||||
AuthMode::ApiKey => CodexAuth::from_api_key("test-api-key"),
|
||||
AuthMode::Chatgpt => CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
AuthMode::ChatgptAuthTokens => CodexAuth::from_external_chatgpt_tokens(
|
||||
"header.e30.test",
|
||||
"test-account",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.expect("test ChatGPT tokens should parse"),
|
||||
AuthMode::Headers => CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new())),
|
||||
AuthMode::BedrockApiKey => CodexAuth::BedrockApiKey(BedrockApiKeyAuth {
|
||||
api_key: "test-api-key".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
}),
|
||||
AuthMode::BedrockAccessKeys => CodexAuth::BedrockAccessKeys(BedrockAccessKeysAuth {
|
||||
access_key_id: "test-access-key-id".to_string(),
|
||||
secret_access_key: "test-secret-access-key".to_string(),
|
||||
session_token: None,
|
||||
}),
|
||||
AuthMode::AgentIdentity | AuthMode::PersonalAccessToken => {
|
||||
panic!("test auth mode requires a purpose-built CodexAuth")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
struct StaticExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_skill_root_loader() -> Arc<dyn SkillRootLoader<PluginSkillRoot>> {
|
||||
Arc::new(TestSkillRootLoader)
|
||||
}
|
||||
|
||||
struct TestSkillRootLoader;
|
||||
|
||||
impl SkillRootLoader<PluginSkillRoot> for TestSkillRootLoader {
|
||||
fn load_roots(
|
||||
&self,
|
||||
request: SkillRootLoadRequest<PluginSkillRoot>,
|
||||
) -> SkillLoadFuture<'_, LoadedSkills> {
|
||||
Box::pin(async move {
|
||||
let mut loaded_roots = Vec::new();
|
||||
for root in request.roots {
|
||||
let cached = request
|
||||
.snapshots
|
||||
.as_ref()
|
||||
.and_then(|cache| cache.get(&root));
|
||||
let snapshot = match cached {
|
||||
Some(snapshot) => snapshot,
|
||||
None => {
|
||||
let snapshot = load_test_skill_root(&root);
|
||||
if let Some(snapshots) = &request.snapshots {
|
||||
snapshots.insert(root.clone(), snapshot.clone());
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
};
|
||||
let migrated_root = migrated_command_skills_root(&root.plugin_root);
|
||||
let canonical_migrated_root = fs::canonicalize(migrated_root.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or(migrated_root);
|
||||
loaded_roots.push((snapshot.root == canonical_migrated_root, snapshot));
|
||||
}
|
||||
|
||||
let native_names = loaded_roots
|
||||
.iter()
|
||||
.filter(|(migrated, _)| !migrated)
|
||||
.flat_map(|(_, snapshot)| &snapshot.skills)
|
||||
.map(|skill| (skill.plugin_id.clone(), skill.name.clone()))
|
||||
.collect::<HashSet<_>>();
|
||||
let mut seen_paths = HashSet::new();
|
||||
let mut outcome = LoadedSkills::default();
|
||||
for (migrated, snapshot) in loaded_roots {
|
||||
outcome
|
||||
.skills
|
||||
.extend(snapshot.skills.into_iter().filter(|skill| {
|
||||
(!migrated
|
||||
|| !native_names
|
||||
.contains(&(skill.plugin_id.clone(), skill.name.clone())))
|
||||
&& skill.matches_product_restriction_for_product(
|
||||
request.restriction_product,
|
||||
)
|
||||
&& seen_paths.insert(skill.path_to_skills_md.clone())
|
||||
}));
|
||||
outcome.errors.extend(snapshot.errors);
|
||||
}
|
||||
outcome.skills.sort_by(|left, right| {
|
||||
left.name.cmp(&right.name).then_with(|| {
|
||||
left.path_to_skills_md
|
||||
.to_abs_path()
|
||||
.expect("host test skill path")
|
||||
.cmp(
|
||||
&right
|
||||
.path_to_skills_md
|
||||
.to_abs_path()
|
||||
.expect("host test skill path"),
|
||||
)
|
||||
})
|
||||
});
|
||||
outcome
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn load_test_skill_root(root: &PluginSkillRoot) -> LoadedSkillRoot {
|
||||
let canonical_root = fs::canonicalize(root.path.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or_else(|| root.path.clone());
|
||||
let mut skills = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut discovery_paths = HashMap::new();
|
||||
let mut directories = vec![root.path.clone()];
|
||||
while let Some(directory) = directories.pop() {
|
||||
let Ok(entries) = fs::read_dir(directory.as_path()) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if (root.discovery_mode == SkillDiscoveryMode::Recursive || directory == root.path)
|
||||
&& let Ok(path) = AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
{
|
||||
directories.push(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if path.file_name().is_none_or(|name| name != "SKILL.md")
|
||||
|| (root.discovery_mode == SkillDiscoveryMode::DirectChildren
|
||||
&& directory == root.path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(path) = AbsolutePathBuf::from_absolute_path_checked(path) else {
|
||||
continue;
|
||||
};
|
||||
let canonical_path = fs::canonicalize(path.as_path())
|
||||
.ok()
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok())
|
||||
.unwrap_or_else(|| path.clone());
|
||||
let parsed = fs::read_to_string(path.as_path())
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|contents| {
|
||||
parse_skill_frontmatter_metadata(&contents, || {
|
||||
directory
|
||||
.as_path()
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
})
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match parsed {
|
||||
Ok(parsed) => {
|
||||
discovery_paths.insert(
|
||||
PathUri::from_abs_path(&canonical_path),
|
||||
PathUri::from_abs_path(&path),
|
||||
);
|
||||
skills.push(SkillMetadata {
|
||||
name: format!("{}:{}", root.plugin_namespace, parsed.name),
|
||||
description: parsed.description,
|
||||
short_description: parsed.short_description,
|
||||
interface: None,
|
||||
dependencies: None,
|
||||
policy: None,
|
||||
path_to_skills_md: PathUri::from_abs_path(&canonical_path),
|
||||
scope: SkillScope::User,
|
||||
plugin_id: Some(root.plugin_identity.plugin_id.clone()),
|
||||
remote_plugin_id: root.plugin_identity.remote_plugin_id.clone(),
|
||||
});
|
||||
}
|
||||
Err(message) => errors.push(SkillError {
|
||||
path: canonical_path,
|
||||
message,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LoadedSkillRoot {
|
||||
root: canonical_root,
|
||||
skills,
|
||||
skill_discovery_path_by_path: Arc::new(discovery_paths),
|
||||
errors,
|
||||
is_agent_plugin: root.discovery_mode == SkillDiscoveryMode::DirectChildren,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn test_http_client_factory() -> HttpClientFactory {
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RecordingHttpClientSelector {
|
||||
selected_urls: Arc<Mutex<Vec<String>>>,
|
||||
delegate: RouteAwareClientPool,
|
||||
}
|
||||
|
||||
impl RecordingHttpClientSelector {
|
||||
fn record_url(&self, url: &str) {
|
||||
match self.selected_urls.lock() {
|
||||
Ok(mut selected_urls) => selected_urls.push(url.to_string()),
|
||||
Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new() -> (Arc<Self>, Arc<Mutex<Vec<String>>>) {
|
||||
let selected_urls = Arc::new(Mutex::new(Vec::new()));
|
||||
let delegate = RouteAwareClientPool::with_chatgpt_cloudflare_cookies(
|
||||
test_http_client_factory(),
|
||||
ClientRouteClass::Api,
|
||||
);
|
||||
(
|
||||
Arc::new(Self {
|
||||
selected_urls: Arc::clone(&selected_urls),
|
||||
delegate,
|
||||
}),
|
||||
selected_urls,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpClientSelector for RecordingHttpClientSelector {
|
||||
fn for_current_account(&self) -> Arc<dyn HttpClientSelector> {
|
||||
Arc::new(Self {
|
||||
selected_urls: Arc::clone(&self.selected_urls),
|
||||
delegate: self.delegate.for_current_account(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request(&self, method: Method, url: &str) -> RequestBuilder {
|
||||
self.record_url(url);
|
||||
self.delegate.request(method, url)
|
||||
}
|
||||
|
||||
fn request_for_account(
|
||||
&self,
|
||||
method: Method,
|
||||
url: &str,
|
||||
binding: &codex_http_client::NetworkPolicy,
|
||||
) -> Option<RequestBuilder> {
|
||||
self.record_url(url);
|
||||
self.delegate.request_for_account(method, url, binding)
|
||||
}
|
||||
fn outbound_proxy_policy(&self) -> OutboundProxyPolicy {
|
||||
self.delegate.outbound_proxy_policy()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn recording_remote_plugin_service_config(
|
||||
chatgpt_base_url: String,
|
||||
) -> (RemotePluginServiceConfig, Arc<Mutex<Vec<String>>>) {
|
||||
let (http_clients, selected_urls) = RecordingHttpClientSelector::new();
|
||||
(
|
||||
RemotePluginServiceConfig {
|
||||
runtime_auth: None,
|
||||
chatgpt_base_url,
|
||||
product_sku: crate::remote::CODEX_PRODUCT_SKU.to_string(),
|
||||
http_clients,
|
||||
},
|
||||
selected_urls,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn recorded_http_client_urls(selected_urls: &Mutex<Vec<String>>) -> Vec<String> {
|
||||
match selected_urls.lock() {
|
||||
Ok(selected_urls) => selected_urls.clone(),
|
||||
Err(error) => panic!("selected URL recorder lock should not be poisoned: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_file(path: &Path, contents: &str) {
|
||||
fs::create_dir_all(path.parent().expect("file should have a parent")).unwrap();
|
||||
fs::write(path, contents).unwrap();
|
||||
}
|
||||
|
||||
pub(crate) fn write_curated_plugin(root: &Path, plugin_name: &str) {
|
||||
let plugin_root = root.join("plugins").join(plugin_name);
|
||||
write_file(
|
||||
&plugin_root.join(".codex-plugin/plugin.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"description": "Plugin that includes skills, MCP servers, and app connectors"
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join("skills/SKILL.md"),
|
||||
"---\nname: sample\ndescription: sample\n---\n",
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".mcp.json"),
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"sample-docs": {
|
||||
"type": "http",
|
||||
"url": "https://sample.example/mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
write_file(
|
||||
&plugin_root.join(".app.json"),
|
||||
r#"{
|
||||
"apps": {
|
||||
"calendar": {
|
||||
"id": "connector_calendar"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn write_openai_curated_marketplace(root: &Path, plugin_names: &[&str]) {
|
||||
write_curated_marketplace(
|
||||
root,
|
||||
"marketplace.json",
|
||||
OPENAI_CURATED_MARKETPLACE_NAME,
|
||||
/*display_name*/ None,
|
||||
plugin_names,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn write_openai_api_curated_marketplace(root: &Path, plugin_names: &[&str]) {
|
||||
write_curated_marketplace(
|
||||
root,
|
||||
"api_marketplace.json",
|
||||
OPENAI_API_CURATED_MARKETPLACE_NAME,
|
||||
Some("OpenAI Curated"),
|
||||
plugin_names,
|
||||
);
|
||||
}
|
||||
|
||||
fn write_curated_marketplace(
|
||||
root: &Path,
|
||||
manifest_name: &str,
|
||||
marketplace_name: &str,
|
||||
display_name: Option<&str>,
|
||||
plugin_names: &[&str],
|
||||
) {
|
||||
let plugins = plugin_names
|
||||
.iter()
|
||||
.map(|plugin_name| {
|
||||
format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"source": {{
|
||||
"source": "local",
|
||||
"path": "./plugins/{plugin_name}"
|
||||
}}
|
||||
}}"#
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",\n");
|
||||
let interface = display_name
|
||||
.map(|display_name| {
|
||||
format!(
|
||||
r#"
|
||||
"interface": {{
|
||||
"displayName": "{display_name}"
|
||||
}},"#
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
write_file(
|
||||
&root.join(".agents/plugins").join(manifest_name),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",{interface}
|
||||
"plugins": [
|
||||
{plugins}
|
||||
]
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
for plugin_name in plugin_names {
|
||||
write_curated_plugin(root, plugin_name);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_curated_plugin_sha_with(codex_home: &Path, sha: &str) {
|
||||
write_file(&codex_home.join(".tmp/plugins.sha"), &format!("{sha}\n"));
|
||||
}
|
||||
|
||||
pub(crate) async fn load_plugins_config(codex_home: &Path, cwd: &Path) -> PluginsConfigInput {
|
||||
let codex_home = AbsolutePathBuf::try_from(codex_home).expect("codex home should be absolute");
|
||||
let cwd = AbsolutePathBuf::try_from(cwd).expect("cwd should be absolute");
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
codex_home.as_path(),
|
||||
Some(cwd),
|
||||
&[],
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await
|
||||
.expect("config should load");
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let model_provider_id = effective_config
|
||||
.get("model_provider")
|
||||
.and_then(toml::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
PluginsConfigInput::new(
|
||||
config_layer_stack,
|
||||
effective_config
|
||||
.clone()
|
||||
.try_into::<codex_config::config_toml::ConfigToml>()
|
||||
.unwrap()
|
||||
.plugins,
|
||||
model_provider_id,
|
||||
feature_enabled(&effective_config, "plugins", /*default_enabled*/ true),
|
||||
feature_enabled(
|
||||
&effective_config,
|
||||
"remote_plugin",
|
||||
/*default_enabled*/ true,
|
||||
),
|
||||
"https://chatgpt.com/backend-api/".to_string(),
|
||||
test_http_client_factory(),
|
||||
/*product_sku*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn feature_enabled(config: &Value, key: &str, default_enabled: bool) -> bool {
|
||||
config
|
||||
.get("features")
|
||||
.and_then(Value::as_table)
|
||||
.and_then(|features| features.get(key))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(default_enabled)
|
||||
}
|
||||
100
codex-rs/core-plugins/src/toggles.rs
Normal file
100
codex-rs/core-plugins/src/toggles.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub fn collect_plugin_enabled_candidates<'a>(
|
||||
edits: impl Iterator<Item = (&'a String, &'a JsonValue)>,
|
||||
) -> BTreeMap<String, bool> {
|
||||
let mut pending_changes = BTreeMap::new();
|
||||
for (key_path, value) in edits {
|
||||
let segments = key_path
|
||||
.split('.')
|
||||
.map(str::to_string)
|
||||
.collect::<Vec<String>>();
|
||||
match segments.as_slice() {
|
||||
[plugins, plugin_id, enabled]
|
||||
if plugins == "plugins" && enabled == "enabled" && value.is_boolean() =>
|
||||
{
|
||||
if let Some(enabled) = value.as_bool() {
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
[plugins, plugin_id] if plugins == "plugins" => {
|
||||
if let Some(enabled) = value.get("enabled").and_then(JsonValue::as_bool) {
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
[plugins] if plugins == "plugins" => {
|
||||
let Some(entries) = value.as_object() else {
|
||||
continue;
|
||||
};
|
||||
for (plugin_id, plugin_value) in entries {
|
||||
let Some(enabled) = plugin_value.get("enabled").and_then(JsonValue::as_bool)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
pending_changes.insert(plugin_id.clone(), enabled);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pending_changes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::collect_plugin_enabled_candidates;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn collect_plugin_enabled_candidates_tracks_direct_and_table_writes() {
|
||||
let candidates = collect_plugin_enabled_candidates(
|
||||
[
|
||||
(&"plugins.sample@test.enabled".to_string(), &json!(true)),
|
||||
(
|
||||
&"plugins.other@test".to_string(),
|
||||
&json!({ "enabled": false, "ignored": true }),
|
||||
),
|
||||
(
|
||||
&"plugins".to_string(),
|
||||
&json!({
|
||||
"nested@test": { "enabled": true },
|
||||
"skip@test": { "name": "skip" },
|
||||
}),
|
||||
),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
BTreeMap::from([
|
||||
("nested@test".to_string(), true),
|
||||
("other@test".to_string(), false),
|
||||
("sample@test".to_string(), true),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_plugin_enabled_candidates_uses_last_write_for_same_plugin() {
|
||||
let candidates = collect_plugin_enabled_candidates(
|
||||
[
|
||||
(&"plugins.sample@test.enabled".to_string(), &json!(true)),
|
||||
(
|
||||
&"plugins.sample@test".to_string(),
|
||||
&json!({ "enabled": false }),
|
||||
),
|
||||
]
|
||||
.into_iter(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
candidates,
|
||||
BTreeMap::from([("sample@test".to_string(), false)])
|
||||
);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user