Compare commits

...
16 changed files with 583 additions and 1 deletions

No files matched your search

@@ -48,6 +48,7 @@ use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexErrKind;
use crate::facts::CodexPluginScriptLifecycleEvent;
use crate::facts::CompactionImplementation;
use crate::facts::CompactionPhase;
use crate::facts::CompactionReason;
@@ -62,6 +63,8 @@ use crate::facts::HookRunInput;
use crate::facts::InputError;
use crate::facts::InvocationType;
use crate::facts::PluginInstallFailedInput;
use crate::facts::PluginScriptLifecycleStatus;
use crate::facts::PluginScriptSkill;
use crate::facts::PluginState;
use crate::facts::PluginStateChangedInput;
use crate::facts::PluginUsedInput;
@@ -3339,6 +3342,121 @@ async fn reducer_includes_plugin_id_for_plugin_skill_invocations() {
);
}
#[tokio::test]
async fn reducer_enriches_plugin_script_lifecycle_events_without_sensitive_paths() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
reducer
.ingest(
AnalyticsFact::Initialize {
connection_id: 7,
params: InitializeParams {
client_info: ClientInfo {
name: "codex-tui".to_string(),
title: None,
version: "1.0.0".to_string(),
},
capabilities: Some(InitializeCapabilities {
experimental_api: true,
request_attestation: false,
opt_out_notification_methods: None,
}),
},
product_client_id: DEFAULT_ORIGINATOR.to_string(),
runtime: sample_runtime_metadata(),
rpc_transport: AppServerRpcTransport::Stdio,
},
&mut events,
)
.await;
reducer
.ingest(
AnalyticsFact::ClientResponse {
connection_id: 7,
request_id: RequestId::Integer(1),
response: Box::new(sample_thread_start_response(
"thread-1", /*ephemeral*/ false, "gpt-5",
)),
},
&mut events,
)
.await;
events.clear();
let sensitive_skill_path =
PathBuf::from("/Users/private/.codex/plugins/cache/openai/sample/skills/doc/SKILL.md");
let skill = PluginScriptSkill {
skill_name: "sample:doc".to_string(),
skill_path: sensitive_skill_path.clone(),
};
let expected_skill_id = skill_id_for_local_skill(
/*repo_url*/ None,
/*repo_root*/ None,
sensitive_skill_path.as_path(),
"sample:doc",
);
for (status, duration_ms, exit_code) in [
(PluginScriptLifecycleStatus::Started, None, None),
(PluginScriptLifecycleStatus::Completed, Some(42), Some(0)),
] {
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::PluginScriptLifecycle(Box::new(
CodexPluginScriptLifecycleEvent {
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
plugin_id: "sample@openai-curated".to_string(),
execution_id: "execution-1".to_string(),
script_path: "scripts/run.py".to_string(),
timestamp: "2026-06-12T17:39:31.000Z".to_string(),
status,
duration_ms,
exit_code,
skill: Some(skill.clone()),
},
))),
&mut events,
)
.await;
}
let payload = serde_json::to_value(&events).expect("serialize events");
assert_eq!(payload.as_array().map(Vec::len), Some(2));
let started = &payload[0];
let completed = &payload[1];
assert_eq!(started["event_type"], "codex_plugin_lifecycle_event");
assert_eq!(started["event_params"]["version"], 1);
assert_eq!(started["event_params"]["thread_id"], "thread-1");
assert_eq!(started["event_params"]["session_id"], "session-thread-1");
assert_eq!(started["event_params"]["turn_id"], "turn-1");
assert_eq!(
started["event_params"]["app_server_client"]["product_client_id"],
DEFAULT_ORIGINATOR
);
assert_eq!(
started["event_params"]["plugin_id"],
"sample@openai-curated"
);
assert_eq!(started["event_params"]["execution_id"], "execution-1");
assert_eq!(started["event_params"]["script_path"], "scripts/run.py");
assert_eq!(
started["event_params"]["timestamp"],
"2026-06-12T17:39:31.000Z"
);
assert_eq!(started["event_params"]["status"], "started");
assert_eq!(started["event_params"]["skill_id"], expected_skill_id);
assert!(started["event_params"].get("duration_ms").is_none());
assert!(started["event_params"].get("exit_code").is_none());
assert_eq!(completed["event_params"]["status"], "completed");
assert_eq!(completed["event_params"]["duration_ms"], 42);
assert_eq!(completed["event_params"]["exit_code"], 0);
assert_eq!(completed["event_params"]["skill_id"], expected_skill_id);
let serialized = payload.to_string();
assert!(!serialized.contains("/Users/private"));
assert!(!serialized.contains("SKILL.md"));
}
#[tokio::test]
async fn reducer_ingests_hook_run_fact() {
let mut reducer = AnalyticsReducer::default();
+9
View File
@@ -313,6 +313,15 @@ impl AnalyticsEventsClient {
))));
}
pub fn track_plugin_script_lifecycle(
&self,
event: crate::facts::CodexPluginScriptLifecycleEvent,
) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::PluginScriptLifecycle(Box::new(event)),
));
}
pub fn track_turn_resolved_config(&self, fact: TurnResolvedConfigFact) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::TurnResolvedConfig(Box::new(fact)),
+31
View File
@@ -14,6 +14,7 @@ use crate::facts::CompactionTrigger;
use crate::facts::GoalEventKind;
use crate::facts::HookRunFact;
use crate::facts::InvocationType;
use crate::facts::PluginScriptLifecycleStatus;
use crate::facts::PluginState;
use crate::facts::SubAgentThreadStartedInput;
use crate::facts::ThreadInitializationMode;
@@ -66,6 +67,7 @@ pub(crate) enum TrackEventRequest {
HookRun(CodexHookRunEventRequest),
Compaction(Box<CodexCompactionEventRequest>),
Goal(Box<CodexGoalEventRequest>),
PluginScriptLifecycle(Box<CodexPluginScriptLifecycleEventRequest>),
TurnEvent(Box<CodexTurnEventRequest>),
TurnSteer(CodexTurnSteerEventRequest),
CommandExecution(CodexCommandExecutionEventRequest),
@@ -842,6 +844,35 @@ pub(crate) struct CodexGoalEventRequest {
pub(crate) event_params: CodexGoalEventParams,
}
#[derive(Serialize)]
pub(crate) struct CodexPluginScriptLifecycleEventParams {
pub(crate) version: u32,
pub(crate) thread_id: String,
pub(crate) session_id: String,
pub(crate) turn_id: String,
pub(crate) app_server_client: CodexAppServerClientMetadata,
pub(crate) runtime: CodexRuntimeMetadata,
pub(crate) thread_source: Option<ThreadSource>,
pub(crate) subagent_source: Option<String>,
pub(crate) parent_thread_id: Option<String>,
pub(crate) plugin_id: String,
pub(crate) execution_id: String,
pub(crate) script_path: String,
pub(crate) timestamp: String,
pub(crate) status: PluginScriptLifecycleStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) duration_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) exit_code: Option<i32>,
pub(crate) skill_id: Option<String>,
}
#[derive(Serialize)]
pub(crate) struct CodexPluginScriptLifecycleEventRequest {
pub(crate) event_type: &'static str,
pub(crate) event_params: CodexPluginScriptLifecycleEventParams,
}
#[derive(Serialize)]
pub(crate) struct CodexTurnEventParams {
pub(crate) thread_id: String,
+30
View File
@@ -441,6 +441,35 @@ pub struct CodexGoalEvent {
pub cumulative_time_accounted_seconds: Option<i64>,
}
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginScriptLifecycleStatus {
Started,
Completed,
Failed,
Cancelled,
}
#[derive(Clone, Debug)]
pub struct PluginScriptSkill {
pub skill_name: String,
pub skill_path: PathBuf,
}
#[derive(Clone, Debug)]
pub struct CodexPluginScriptLifecycleEvent {
pub thread_id: String,
pub turn_id: String,
pub plugin_id: String,
pub execution_id: String,
pub script_path: String,
pub timestamp: String,
pub status: PluginScriptLifecycleStatus,
pub duration_ms: Option<u64>,
pub exit_code: Option<i32>,
pub skill: Option<PluginScriptSkill>,
}
#[allow(dead_code)]
pub(crate) enum AnalyticsFact {
Initialize {
@@ -493,6 +522,7 @@ pub(crate) enum CustomAnalyticsFact {
SubAgentThreadStarted(SubAgentThreadStartedInput),
Compaction(Box<CodexCompactionEvent>),
Goal(Box<CodexGoalEvent>),
PluginScriptLifecycle(Box<CodexPluginScriptLifecycleEvent>),
GuardianReview(Box<GuardianReviewEventParams>),
TurnResolvedConfig(Box<TurnResolvedConfigFact>),
TurnTokenUsage(Box<TurnTokenUsageFact>),
+3
View File
@@ -29,6 +29,7 @@ pub use facts::AppInvocation;
pub use facts::CodexCompactionEvent;
pub use facts::CodexErrKind;
pub use facts::CodexGoalEvent;
pub use facts::CodexPluginScriptLifecycleEvent;
pub use facts::CodexTurnSteerEvent;
pub use facts::CompactionImplementation;
pub use facts::CompactionPhase;
@@ -42,6 +43,8 @@ pub use facts::GoalEventKind;
pub use facts::HookRunFact;
pub use facts::InputError;
pub use facts::InvocationType;
pub use facts::PluginScriptLifecycleStatus;
pub use facts::PluginScriptSkill;
pub use facts::SkillInvocation;
pub use facts::SubAgentThreadStartedInput;
pub use facts::ThreadInitializationMode;
+70
View File
@@ -28,6 +28,8 @@ use crate::events::CodexOnboardingExternalAgentImportFailureMetadata;
use crate::events::CodexPluginEventRequest;
use crate::events::CodexPluginInstallFailedEventRequest;
use crate::events::CodexPluginInstallFailedMetadata;
use crate::events::CodexPluginScriptLifecycleEventParams;
use crate::events::CodexPluginScriptLifecycleEventRequest;
use crate::events::CodexPluginUsedEventRequest;
use crate::events::CodexReviewEventParams;
use crate::events::CodexReviewEventRequest;
@@ -71,6 +73,7 @@ use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexGoalEvent;
use crate::facts::CodexPluginScriptLifecycleEvent;
use crate::facts::CustomAnalyticsFact;
use crate::facts::ExternalAgentConfigImportCompletedInput;
use crate::facts::ExternalAgentConfigImportFailureInput;
@@ -214,6 +217,16 @@ impl<'a> AnalyticsDropSite<'a> {
}
}
fn plugin_script_lifecycle(input: &'a CodexPluginScriptLifecycleEvent) -> Self {
Self {
event_name: "plugin script lifecycle",
thread_id: &input.thread_id,
turn_id: Some(&input.turn_id),
review_id: None,
item_id: None,
}
}
fn tool_item(
notification: &'a codex_app_server_protocol::ItemCompletedNotification,
item_id: &'a str,
@@ -487,6 +500,9 @@ impl AnalyticsReducer {
CustomAnalyticsFact::Goal(input) => {
self.ingest_goal(*input, out);
}
CustomAnalyticsFact::PluginScriptLifecycle(input) => {
self.ingest_plugin_script_lifecycle(*input, out).await;
}
CustomAnalyticsFact::GuardianReview(input) => {
self.ingest_guardian_review(*input, out);
}
@@ -1383,6 +1399,60 @@ impl AnalyticsReducer {
})));
}
async fn ingest_plugin_script_lifecycle(
&mut self,
input: CodexPluginScriptLifecycleEvent,
out: &mut Vec<TrackEventRequest>,
) {
let Some((connection_state, thread_metadata)) =
self.thread_context_or_warn(AnalyticsDropSite::plugin_script_lifecycle(&input))
else {
return;
};
let skill_id = if let Some(skill) = input.skill.as_ref() {
let repo_root = get_git_repo_root(skill.skill_path.as_path());
let repo_url = if let Some(root) = repo_root.as_ref() {
collect_git_info(root)
.await
.and_then(|info| info.repository_url)
} else {
None
};
Some(skill_id_for_local_skill(
repo_url.as_deref(),
repo_root.as_deref(),
skill.skill_path.as_path(),
skill.skill_name.as_str(),
))
} else {
None
};
out.push(TrackEventRequest::PluginScriptLifecycle(Box::new(
CodexPluginScriptLifecycleEventRequest {
event_type: "codex_plugin_lifecycle_event",
event_params: CodexPluginScriptLifecycleEventParams {
version: 1,
thread_id: input.thread_id,
session_id: thread_metadata.session_id.clone(),
turn_id: input.turn_id,
app_server_client: connection_state.app_server_client.clone(),
runtime: connection_state.runtime.clone(),
thread_source: thread_metadata.thread_source.clone(),
subagent_source: thread_metadata.subagent_source.clone(),
parent_thread_id: thread_metadata.parent_thread_id.clone(),
plugin_id: input.plugin_id,
execution_id: input.execution_id,
script_path: input.script_path,
timestamp: input.timestamp,
status: input.status,
duration_ms: input.duration_ms,
exit_code: input.exit_code,
skill_id,
},
},
)));
}
fn ingest_guardian_review_completed(
&mut self,
notification: codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification,
+35
View File
@@ -10,6 +10,8 @@ use crate::marketplace::list_marketplaces;
use crate::marketplace::load_marketplace;
use crate::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use crate::remote::RemoteInstalledPlugin;
use crate::startup_sync::curated_plugins_repo_path;
use crate::startup_sync::read_curated_plugins_sha;
use crate::store::PluginStore;
use crate::store::plugin_version_for_source;
use codex_app_server_protocol::AuthMode;
@@ -665,6 +667,7 @@ async fn load_plugin(
config_name,
manifest_name: None,
manifest_description: None,
is_first_party: false,
root,
enabled: plugin.enabled,
skill_roots: Vec::new(),
@@ -705,6 +708,7 @@ async fn load_plugin(
return loaded_plugin;
};
loaded_plugin.is_first_party = is_openai_curated_plugin(&loaded_plugin_id, &plugin_root, store);
let manifest_paths = &manifest.paths;
match scope {
PluginLoadScope::AllCapabilities {
@@ -746,6 +750,37 @@ async fn load_plugin(
loaded_plugin
}
fn is_openai_curated_plugin(
plugin_id: &PluginId,
loaded_root: &AbsolutePathBuf,
store: &PluginStore,
) -> bool {
if !is_openai_curated_marketplace_name(&plugin_id.marketplace_name) {
return false;
}
let Some(curated_sha) = read_curated_plugins_sha(store.codex_home()) else {
return false;
};
let expected_version = curated_plugin_cache_version(&curated_sha);
let expected_root = store.plugin_root(plugin_id, &expected_version);
if loaded_root != &expected_root || !expected_root.as_path().is_dir() {
return false;
}
let marketplace_path =
curated_plugins_repo_path(store.codex_home()).join(".agents/plugins/marketplace.json");
let Ok(marketplace_path) = AbsolutePathBuf::try_from(marketplace_path) else {
return false;
};
load_marketplace(&marketplace_path).is_ok_and(|marketplace| {
marketplace
.plugins
.iter()
.any(|plugin| plugin.name == plugin_id.plugin_name)
})
}
fn apply_plugin_mcp_server_policy(config: &mut McpServerConfig, policy: &PluginMcpServerConfig) {
config.enabled = policy.enabled;
if let Some(approval_mode) = policy.default_tools_approval_mode {
+136
View File
@@ -1,6 +1,12 @@
use super::*;
use crate::PluginLoadOutcome;
use crate::manifest::load_plugin_manifest;
use crate::startup_sync::curated_plugins_repo_path;
use crate::test_support::TEST_CURATED_PLUGIN_CACHE_VERSION;
use crate::test_support::TEST_CURATED_PLUGIN_SHA;
use crate::test_support::write_curated_plugin_sha_with;
use crate::test_support::write_file;
use crate::test_support::write_openai_curated_marketplace;
use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerSource;
use codex_config::ConfigRequirements;
@@ -226,6 +232,136 @@ fn curated_plugin_cache_version_preserves_non_git_sha_versions() {
assert_eq!(curated_plugin_cache_version("0123456"), "0123456");
}
fn curated_plugin_config_layer(temp_dir: &TempDir, plugin_name: &str) -> ConfigLayerStack {
ConfigLayerStack::new(
vec![user_layer(
user_config_path(temp_dir, "config.toml"),
&format!(
r#"[plugins."{plugin_name}@openai-curated"]
enabled = true
"#,
),
)],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("valid curated plugin config")
}
fn write_curated_cached_plugin(codex_home: &Path, plugin_name: &str, version: &str) {
let plugin_root = codex_home
.join("plugins/cache/openai-curated")
.join(plugin_name)
.join(version);
write_file(
&plugin_root.join(".codex-plugin/plugin.json"),
&format!(r#"{{"name":"{plugin_name}"}}"#),
);
write_file(&plugin_root.join("skills/SKILL.md"), "skill");
}
async fn load_curated_plugin(temp_dir: &TempDir, plugin_name: &str) -> PluginLoadOutcome {
PluginLoadOutcome::from_plugins(
load_plugins_from_layer_stack(
&curated_plugin_config_layer(temp_dir, plugin_name),
HashMap::new(),
&PluginStore::new(temp_dir.path().to_path_buf()),
Some(Product::Codex),
/*prefer_remote_curated_conflicts*/ false,
)
.await,
)
}
#[tokio::test]
async fn load_curated_plugin_uses_synced_sha_root_when_it_is_only_installed_root() {
let temp_dir = TempDir::new().expect("tempdir");
let curated_root = curated_plugins_repo_path(temp_dir.path());
write_openai_curated_marketplace(&curated_root, &["slack"]);
write_curated_plugin_sha_with(temp_dir.path(), TEST_CURATED_PLUGIN_SHA);
write_curated_cached_plugin(temp_dir.path(), "slack", TEST_CURATED_PLUGIN_CACHE_VERSION);
let outcome = load_curated_plugin(&temp_dir, "slack").await;
let plugin = outcome.plugins().first().expect("configured plugin");
let synced_root = AbsolutePathBuf::try_from(temp_dir.path().join(format!(
"plugins/cache/openai-curated/slack/{TEST_CURATED_PLUGIN_CACHE_VERSION}"
)))
.expect("synced plugin root");
assert_eq!(plugin.root, synced_root);
assert!(plugin.is_first_party);
assert_eq!(
outcome.effective_first_party_plugin_roots(),
vec![codex_plugin::FirstPartyPluginRoot {
plugin_id: "slack@openai-curated".to_string(),
plugin_root: synced_root,
}]
);
}
#[tokio::test]
async fn load_curated_plugin_without_synced_cache_root_is_not_first_party() {
let temp_dir = TempDir::new().expect("tempdir");
let curated_root = curated_plugins_repo_path(temp_dir.path());
write_openai_curated_marketplace(&curated_root, &["slack"]);
write_curated_plugin_sha_with(temp_dir.path(), TEST_CURATED_PLUGIN_SHA);
write_curated_cached_plugin(temp_dir.path(), "slack", "local");
let outcome = load_curated_plugin(&temp_dir, "slack").await;
assert!(
!outcome
.plugins()
.first()
.expect("configured plugin")
.is_first_party
);
assert_eq!(outcome.effective_first_party_plugin_roots(), Vec::new());
}
#[tokio::test]
async fn load_curated_plugin_keeps_local_root_priority_over_synced_sha_root() {
let temp_dir = TempDir::new().expect("tempdir");
let curated_root = curated_plugins_repo_path(temp_dir.path());
write_openai_curated_marketplace(&curated_root, &["slack"]);
write_curated_plugin_sha_with(temp_dir.path(), TEST_CURATED_PLUGIN_SHA);
write_curated_cached_plugin(temp_dir.path(), "slack", "local");
write_curated_cached_plugin(temp_dir.path(), "slack", TEST_CURATED_PLUGIN_CACHE_VERSION);
let outcome = load_curated_plugin(&temp_dir, "slack").await;
let plugin = outcome.plugins().first().expect("configured plugin");
let local_root = AbsolutePathBuf::try_from(
temp_dir
.path()
.join("plugins/cache/openai-curated/slack/local"),
)
.expect("local plugin root");
assert_eq!(plugin.root, local_root);
assert!(!plugin.is_first_party);
assert_eq!(outcome.effective_first_party_plugin_roots(), Vec::new());
}
#[tokio::test]
async fn load_curated_plugin_missing_from_synced_marketplace_is_not_first_party() {
let temp_dir = TempDir::new().expect("tempdir");
let curated_root = curated_plugins_repo_path(temp_dir.path());
write_openai_curated_marketplace(&curated_root, &["github"]);
write_curated_plugin_sha_with(temp_dir.path(), TEST_CURATED_PLUGIN_SHA);
write_curated_cached_plugin(temp_dir.path(), "slack", TEST_CURATED_PLUGIN_CACHE_VERSION);
let outcome = load_curated_plugin(&temp_dir, "slack").await;
assert!(
!outcome
.plugins()
.first()
.expect("configured plugin")
.is_first_party
);
assert_eq!(outcome.effective_first_party_plugin_roots(), Vec::new());
}
fn plugin_id() -> PluginId {
PluginId::parse("demo-plugin@test-marketplace").expect("plugin id")
}
+30
View File
@@ -1,5 +1,6 @@
use super::LoadedPlugin;
use super::PluginLoadOutcome;
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
use crate::app_mcp_routing::apply_app_mcp_routing_policy;
use crate::installed_marketplaces::installed_marketplace_roots_from_layer_stack;
use crate::is_openai_curated_marketplace_name;
@@ -1091,6 +1092,7 @@ impl PluginsManager {
return Err(err.into());
}
};
self.validate_curated_marketplace_install_source(&request.marketplace_path, &resolved)?;
let plugin_id = resolved.plugin_id.clone();
match self.install_resolved_plugin(resolved).await {
Ok(outcome) => Ok(outcome),
@@ -1122,6 +1124,7 @@ impl PluginsManager {
return Err(err.into());
}
};
self.validate_curated_marketplace_install_source(&request.marketplace_path, &resolved)?;
let plugin_id = resolved.plugin_id.as_key();
// This only forwards the backend mutation before the local install flow.
if let Err(err) = crate::remote_legacy::enable_remote_plugin(
@@ -1208,6 +1211,33 @@ impl PluginsManager {
}
}
fn validate_curated_marketplace_install_source(
&self,
marketplace_path: &AbsolutePathBuf,
resolved: &ResolvedMarketplacePlugin,
) -> Result<(), PluginInstallError> {
if resolved.plugin_id.marketplace_name != OPENAI_CURATED_MARKETPLACE_NAME {
return Ok(());
}
let expected_path = curated_plugins_repo_path(self.codex_home.as_path())
.join(".agents/plugins/marketplace.json");
let expected_path = AbsolutePathBuf::try_from(expected_path)
.ok()
.and_then(|path| path.canonicalize().ok());
let requested_path = marketplace_path.canonicalize().ok();
if requested_path
.zip(expected_path)
.is_none_or(|(requested, expected)| requested != expected)
{
return Err(PluginStoreError::Invalid(format!(
"marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' can only be installed from the synced curated marketplace"
))
.into());
}
Ok(())
}
async fn install_resolved_plugin(
&self,
resolved: ResolvedMarketplacePlugin,
@@ -622,6 +622,7 @@ async fn load_plugins_loads_default_skills_and_mcp_servers() {
manifest_description: Some(
"Plugin that includes the sample MCP server and Skills".to_string(),
),
is_first_party: false,
root: AbsolutePathBuf::try_from(plugin_root.clone()).unwrap(),
enabled: true,
skill_roots: vec![plugin_root.join("skills").abs()],
@@ -1586,6 +1587,7 @@ async fn load_plugins_preserves_disabled_plugins_without_effective_contributions
config_name: "sample@test".to_string(),
manifest_name: None,
manifest_description: None,
is_first_party: false,
root: AbsolutePathBuf::try_from(plugin_root).unwrap(),
enabled: false,
skill_roots: Vec::new(),
@@ -1754,6 +1756,7 @@ fn capability_index_filters_inactive_and_zero_capability_plugins() {
config_name: config_name.to_string(),
manifest_name: Some(manifest_name.to_string()),
manifest_description: None,
is_first_party: false,
root: AbsolutePathBuf::try_from(codex_home.path().join(dir_name)).unwrap(),
enabled: true,
skill_roots: Vec::new(),
@@ -2077,6 +2080,38 @@ async fn install_openai_curated_plugin_uses_short_sha_cache_version() {
);
}
#[tokio::test]
async fn install_plugin_rejects_spoofed_openai_curated_marketplace() {
let tmp = tempfile::tempdir().unwrap();
let curated_root = curated_plugins_repo_path(tmp.path());
write_openai_curated_marketplace(&curated_root, &["slack"]);
write_curated_plugin_sha(tmp.path(), TEST_CURATED_PLUGIN_SHA);
let spoofed_root = tmp.path().join("spoofed-marketplace");
write_openai_curated_marketplace(&spoofed_root, &["slack"]);
let err = PluginsManager::new(tmp.path().to_path_buf())
.install_plugin(PluginInstallRequest {
plugin_name: "slack".to_string(),
marketplace_path: AbsolutePathBuf::try_from(
spoofed_root.join(".agents/plugins/marketplace.json"),
)
.unwrap(),
})
.await
.unwrap_err();
assert!(err.is_invalid_request());
assert!(
err.to_string()
.contains("can only be installed from the synced curated marketplace")
);
assert!(
!tmp.path()
.join("plugins/cache/openai-curated/slack")
.exists()
);
}
#[tokio::test]
async fn install_plugin_uses_manifest_version_for_non_curated_plugins() {
let tmp = tempfile::tempdir().unwrap();
+12 -1
View File
@@ -26,6 +26,7 @@ pub struct PluginInstallResult {
#[derive(Debug, Clone)]
pub struct PluginStore {
codex_home: AbsolutePathBuf,
root: AbsolutePathBuf,
data_root: AbsolutePathBuf,
}
@@ -42,8 +43,18 @@ impl PluginStore {
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 { root, data_root })
Ok(Self {
codex_home,
root,
data_root,
})
}
pub fn codex_home(&self) -> &AbsolutePathBuf {
&self.codex_home
}
pub fn root(&self) -> &AbsolutePathBuf {
+1
View File
@@ -136,6 +136,7 @@ pub(super) async fn spawn_review_thread(
turn_metadata_state,
extension_data,
turn_skills: TurnSkillsContext::new(parent_turn_context.turn_skills.snapshot.clone()),
first_party_plugin_roots: Arc::clone(&parent_turn_context.first_party_plugin_roots),
turn_timing_state: Arc::new(TurnTimingState::default()),
terminal_error: Arc::new(Mutex::new(None)),
server_model_warning_emitted: AtomicBool::new(false),
+4
View File
@@ -5048,6 +5048,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
.plugins_manager
.plugins_for_config(&per_turn_config.plugins_config_input())
.await;
let first_party_plugin_roots = plugin_outcome.effective_first_party_plugin_roots();
let effective_skill_roots = plugin_outcome.effective_plugin_skill_roots();
let skills_input =
crate::skills_load_input_from_config(&per_turn_config, effective_skill_roots);
@@ -5075,6 +5076,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
session_configuration.cwd().clone(),
"turn_id".to_string(),
skills_snapshot,
first_party_plugin_roots,
);
let session = Session {
@@ -7091,6 +7093,7 @@ where
.plugins_manager
.plugins_for_config(&per_turn_config.plugins_config_input())
.await;
let first_party_plugin_roots = plugin_outcome.effective_first_party_plugin_roots();
let effective_skill_roots = plugin_outcome.effective_plugin_skill_roots();
let skills_input =
crate::skills_load_input_from_config(&per_turn_config, effective_skill_roots);
@@ -7118,6 +7121,7 @@ where
session_configuration.cwd().clone(),
"turn_id".to_string(),
skills_snapshot,
first_party_plugin_roots,
));
let session = Arc::new(Session {
@@ -6,6 +6,7 @@ use codex_core_skills::HostSkillsSnapshot;
use codex_file_system::FileSystemSandboxContext;
use codex_model_provider::SharedModelProvider;
use codex_model_provider::create_model_provider;
use codex_plugin::FirstPartyPluginRoot;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::models::AdditionalPermissionProfile;
@@ -138,6 +139,7 @@ pub struct TurnContext {
pub(crate) turn_metadata_state: Arc<TurnMetadataState>,
pub(crate) extension_data: Arc<codex_extension_api::ExtensionData>,
pub(crate) turn_skills: TurnSkillsContext,
pub(crate) first_party_plugin_roots: Arc<Vec<FirstPartyPluginRoot>>,
pub(crate) turn_timing_state: Arc<TurnTimingState>,
pub(crate) terminal_error: Arc<Mutex<Option<String>>>,
pub(crate) server_model_warning_emitted: AtomicBool,
@@ -289,6 +291,7 @@ impl TurnContext {
turn_metadata_state: self.turn_metadata_state.clone(),
extension_data: Arc::clone(&self.extension_data),
turn_skills: self.turn_skills.clone(),
first_party_plugin_roots: Arc::clone(&self.first_party_plugin_roots),
turn_timing_state: Arc::clone(&self.turn_timing_state),
terminal_error: Arc::clone(&self.terminal_error),
server_model_warning_emitted: AtomicBool::new(
@@ -494,6 +497,7 @@ impl Session {
cwd: AbsolutePathBuf,
sub_id: String,
skills_snapshot: HostSkillsSnapshot,
first_party_plugin_roots: Vec<FirstPartyPluginRoot>,
) -> TurnContext {
let reasoning_effort = session_configuration.collaboration_mode.reasoning_effort();
let reasoning_summary = session_configuration
@@ -575,6 +579,7 @@ impl Session {
turn_metadata_state,
extension_data,
turn_skills: TurnSkillsContext::new(skills_snapshot),
first_party_plugin_roots: Arc::new(first_party_plugin_roots),
turn_timing_state: Arc::new(TurnTimingState::default()),
terminal_error: Arc::new(Mutex::new(None)),
server_model_warning_emitted: AtomicBool::new(false),
@@ -727,6 +732,7 @@ impl Session {
.plugins_manager
.plugins_for_config(&per_turn_config.plugins_config_input())
.await;
let first_party_plugin_roots = plugin_outcome.effective_first_party_plugin_roots();
let effective_skill_roots = plugin_outcome.effective_plugin_skill_roots();
let skills_input = skills_load_input_from_config(&per_turn_config, effective_skill_roots);
let fs = primary_turn_environment
@@ -764,6 +770,7 @@ impl Session {
cwd,
sub_id,
skills_snapshot,
first_party_plugin_roots,
);
turn_context.realtime_active = self.conversation.running_state().await.is_some();
+1
View File
@@ -13,6 +13,7 @@ mod provider;
use codex_config::HookEventsToml;
use codex_utils_absolute_path::AbsolutePathBuf;
pub use load_outcome::EffectiveSkillRoots;
pub use load_outcome::FirstPartyPluginRoot;
pub use load_outcome::LoadedPlugin;
pub use load_outcome::PluginLoadOutcome;
pub use load_outcome::prompt_safe_plugin_description;
+61
View File
@@ -11,6 +11,11 @@ use crate::PluginHookSource;
use crate::app_connector_ids_from_declarations;
const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FirstPartyPluginRoot {
pub plugin_id: String,
pub plugin_root: AbsolutePathBuf,
}
/// A plugin that was loaded from disk, including merged MCP server definitions.
#[derive(Debug, Clone, PartialEq)]
@@ -18,6 +23,7 @@ pub struct LoadedPlugin<M> {
pub config_name: String,
pub manifest_name: Option<String>,
pub manifest_description: Option<String>,
pub is_first_party: bool,
pub root: AbsolutePathBuf,
pub enabled: bool,
pub skill_roots: Vec<AbsolutePathBuf>,
@@ -141,6 +147,26 @@ impl<M: Clone> PluginLoadOutcome<M> {
skill_roots
}
pub fn effective_first_party_plugin_roots(&self) -> Vec<FirstPartyPluginRoot> {
let mut plugin_roots = Vec::new();
let mut seen_paths = HashSet::new();
for plugin in self
.plugins
.iter()
.filter(|plugin| plugin.is_active() && plugin.is_first_party)
{
if seen_paths.insert(plugin.root.clone()) {
plugin_roots.push(FirstPartyPluginRoot {
plugin_id: plugin.config_name.clone(),
plugin_root: plugin.root.clone(),
});
}
}
plugin_roots.sort_unstable_by(|a, b| a.plugin_root.cmp(&b.plugin_root));
plugin_roots
}
pub fn effective_mcp_servers(&self) -> HashMap<String, M> {
let mut mcp_servers = HashMap::new();
for plugin in self.plugins.iter().filter(|plugin| plugin.is_active()) {
@@ -219,6 +245,7 @@ mod tests {
config_name: config_name.to_string(),
manifest_name: None,
manifest_description: None,
is_first_party: false,
root: test_path(config_name),
enabled: true,
skill_roots,
@@ -249,4 +276,38 @@ mod tests {
}]
);
}
#[test]
fn effective_first_party_plugin_roots_only_includes_active_openai_plugins() {
let shared_root = test_path("shared-plugin");
let mut first_party = loaded_plugin("first@test", Vec::new());
first_party.root = shared_root.clone();
first_party.is_first_party = true;
let mut duplicate = loaded_plugin("duplicate@test", Vec::new());
duplicate.root = shared_root.clone();
duplicate.is_first_party = true;
let third_party = loaded_plugin("third@test", Vec::new());
let mut disabled = loaded_plugin("disabled@test", Vec::new());
disabled.is_first_party = true;
disabled.enabled = false;
let mut broken = loaded_plugin("broken@test", Vec::new());
broken.is_first_party = true;
broken.error = Some("broken".to_string());
let outcome = PluginLoadOutcome::from_plugins(vec![
first_party,
duplicate,
third_party,
disabled,
broken,
]);
assert_eq!(
outcome.effective_first_party_plugin_roots(),
vec![FirstPartyPluginRoot {
plugin_id: "first@test".to_string(),
plugin_root: shared_root,
}]
);
}
}