Merge remote-tracking branch 'origin/main' into dev/stevenlee/plugin-service-preview-routing

# Conflicts:
#	codex-rs/app-server/src/request_processors/plugins.rs
#	codex-rs/core-plugins/src/remote.rs
This commit is contained in:
Steven Lee
2026-06-23 20:20:52 +00:00
158 changed files with 2001 additions and 973 deletions
+1
View File
@@ -2888,6 +2888,7 @@ dependencies = [
"codex-app-server-protocol",
"codex-client",
"codex-file-system",
"codex-network-proxy",
"codex-protocol",
"codex-sandboxing",
"codex-shell-command",
@@ -177,6 +177,7 @@ fn sample_thread_with_metadata(
) -> Thread {
Thread {
id: thread_id.to_string(),
extra: None,
session_id: format!("session-{thread_id}"),
forked_from_id: None,
parent_thread_id,
@@ -219,7 +220,7 @@ fn sample_thread_start_response(
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AppServerAskForApproval::OnFailure,
approval_policy: AppServerAskForApproval::OnRequest,
approvals_reviewer: AppServerApprovalsReviewer::User,
sandbox: AppServerSandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -284,7 +285,7 @@ fn sample_thread_resume_response_with_source(
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AppServerAskForApproval::OnFailure,
approval_policy: AppServerAskForApproval::OnRequest,
approvals_reviewer: AppServerApprovalsReviewer::User,
sandbox: AppServerSandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -3026,6 +3027,7 @@ fn plugin_used_event_serializes_expected_shape() {
"event_type": "codex_plugin_used",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": null,
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
@@ -3056,6 +3058,7 @@ fn plugin_management_event_serializes_expected_shape() {
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": null,
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
@@ -3085,6 +3088,7 @@ fn plugin_install_failed_event_serializes_expected_shape() {
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": null,
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
@@ -3098,7 +3102,7 @@ fn plugin_install_failed_event_serializes_expected_shape() {
}
#[test]
fn plugin_management_event_can_use_remote_plugin_id_override() {
fn plugin_management_event_keeps_plugin_id_local_when_remote_id_exists() {
let mut plugin = sample_plugin_metadata();
plugin.remote_plugin_id = Some("plugins~Plugin_remote".to_string());
let event = TrackEventRequest::PluginInstalled(CodexPluginEventRequest {
@@ -3109,11 +3113,21 @@ fn plugin_management_event_can_use_remote_plugin_id_override() {
let payload = serde_json::to_value(&event).expect("serialize plugin installed event");
assert_eq!(
payload["event_params"]["plugin_id"],
"plugins~Plugin_remote"
payload,
json!({
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": "plugins~Plugin_remote",
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
"mcp_server_count": 2,
"connector_ids": ["calendar", "drive"],
"product_client_id": originator().value
}
})
);
assert_eq!(payload["event_params"]["plugin_name"], "sample");
assert_eq!(payload["event_params"]["marketplace_name"], "test");
}
#[test]
@@ -3453,6 +3467,7 @@ async fn reducer_ingests_plugin_state_changed_fact() {
"event_type": "codex_plugin_disabled",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": null,
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
@@ -3488,6 +3503,7 @@ async fn reducer_ingests_plugin_install_failed_fact() {
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "sample@test",
"remote_plugin_id": null,
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
@@ -3505,7 +3521,7 @@ async fn reducer_ingests_plugin_install_failed_fact_without_detail() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
let plugin = PluginTelemetryMetadata {
plugin_id: PluginId::parse("unknown@openai-curated-remote").expect("valid plugin id"),
plugin_id: None,
remote_plugin_id: Some("plugins~Plugin_00000000000000000000000000000000".to_string()),
capability_summary: None,
};
@@ -3528,9 +3544,10 @@ async fn reducer_ingests_plugin_install_failed_fact_without_detail() {
json!([{
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "plugins~Plugin_00000000000000000000000000000000",
"plugin_name": "unknown",
"marketplace_name": "openai-curated-remote",
"plugin_id": null,
"remote_plugin_id": "plugins~Plugin_00000000000000000000000000000000",
"plugin_name": null,
"marketplace_name": null,
"has_skills": null,
"mcp_server_count": null,
"connector_ids": null,
@@ -4569,7 +4586,7 @@ async fn turn_completed_without_started_notification_emits_null_started_at() {
fn sample_plugin_metadata() -> PluginTelemetryMetadata {
PluginTelemetryMetadata {
plugin_id: PluginId::parse("sample@test").expect("valid plugin id"),
plugin_id: Some(PluginId::parse("sample@test").expect("valid plugin id")),
remote_plugin_id: None,
capability_summary: Some(PluginCapabilitySummary {
config_name: "sample@test".to_string(),
+10 -1
View File
@@ -38,6 +38,7 @@ use codex_app_server_protocol::ServerResponse;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::default_client::create_client;
use codex_plugin::PluginId;
use codex_plugin::PluginTelemetryMetadata;
use codex_protocol::request_permissions::RequestPermissionsResponse;
use std::collections::HashSet;
@@ -173,7 +174,15 @@ impl AnalyticsEventsQueue {
if emitted.len() >= ANALYTICS_EVENT_DEDUPE_MAX_KEYS {
emitted.clear();
}
emitted.insert((tracking.turn_id.clone(), plugin.plugin_id.as_key()))
let Some(plugin_id) = plugin
.plugin_id
.as_ref()
.map(PluginId::as_key)
.or_else(|| plugin.remote_plugin_id.clone())
else {
return true;
};
emitted.insert((tracking.turn_id.clone(), plugin_id))
}
}
+4 -3
View File
@@ -277,6 +277,7 @@ fn sample_thread_archive_request() -> ClientRequest {
fn sample_thread(thread_id: &str) -> Thread {
Thread {
id: thread_id.to_string(),
extra: None,
session_id: format!("session-{thread_id}"),
forked_from_id: None,
parent_thread_id: None,
@@ -309,7 +310,7 @@ fn sample_thread_start_response() -> ClientResponsePayload {
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AppServerAskForApproval::OnFailure,
approval_policy: AppServerAskForApproval::OnRequest,
approvals_reviewer: AppServerApprovalsReviewer::User,
sandbox: AppServerSandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -327,7 +328,7 @@ fn sample_thread_resume_response() -> ClientResponsePayload {
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AppServerAskForApproval::OnFailure,
approval_policy: AppServerAskForApproval::OnRequest,
approvals_reviewer: AppServerApprovalsReviewer::User,
sandbox: AppServerSandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -346,7 +347,7 @@ fn sample_thread_fork_response() -> ClientResponsePayload {
cwd: test_path_buf("/tmp").abs(),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AppServerAskForApproval::OnFailure,
approval_policy: AppServerAskForApproval::OnRequest,
approvals_reviewer: AppServerApprovalsReviewer::User,
sandbox: AppServerSandboxPolicy::DangerFullAccess,
active_permission_profile: None,
+8 -4
View File
@@ -26,6 +26,7 @@ use crate::now_unix_millis;
use codex_app_server_protocol::CodexErrorInfo;
use codex_app_server_protocol::CommandExecutionSource;
use codex_login::default_client::originator;
use codex_plugin::PluginId;
use codex_plugin::PluginTelemetryMetadata;
use codex_protocol::approvals::NetworkApprovalProtocol;
use codex_protocol::models::AdditionalPermissionProfile;
@@ -933,6 +934,7 @@ pub(crate) struct CodexTurnSteerEventRequest {
#[derive(Serialize)]
pub(crate) struct CodexPluginMetadata {
pub(crate) plugin_id: Option<String>,
pub(crate) remote_plugin_id: Option<String>,
pub(crate) plugin_name: Option<String>,
pub(crate) marketplace_name: Option<String>,
pub(crate) has_skills: Option<bool>,
@@ -1040,11 +1042,13 @@ pub(crate) fn codex_plugin_metadata(plugin: PluginTelemetryMetadata) -> CodexPlu
remote_plugin_id,
capability_summary,
} = plugin;
let event_plugin_id = remote_plugin_id.unwrap_or_else(|| plugin_id.as_key());
CodexPluginMetadata {
plugin_id: Some(event_plugin_id),
plugin_name: Some(plugin_id.plugin_name),
marketplace_name: Some(plugin_id.marketplace_name),
plugin_id: plugin_id.as_ref().map(PluginId::as_key),
remote_plugin_id,
plugin_name: plugin_id
.as_ref()
.map(|plugin_id| plugin_id.plugin_name.clone()),
marketplace_name: plugin_id.map(|plugin_id| plugin_id.marketplace_name),
has_skills: capability_summary
.as_ref()
.map(|summary| summary.has_skills),
@@ -125,7 +125,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -450,7 +450,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -3626,6 +3625,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -3765,6 +3765,10 @@
],
"type": "object"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadGoal": {
"properties": {
"createdAt": {
@@ -4440,7 +4444,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -5111,6 +5115,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -6864,7 +6864,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -16831,6 +16830,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -17052,6 +17052,10 @@
"title": "ThreadDeletedNotification",
"type": "object"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadForkParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.",
@@ -18034,7 +18038,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
"$ref": "#/definitions/v2/LegacyAppPathString"
},
"type": {
"enum": [
@@ -19699,6 +19703,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -990,7 +990,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -14610,6 +14609,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -14831,6 +14831,10 @@
"title": "ThreadDeletedNotification",
"type": "object"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadForkParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\n\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.",
@@ -15813,7 +15817,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -17478,6 +17482,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -173,7 +173,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -15,7 +15,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -1106,7 +1106,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1106,7 +1106,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1250,7 +1250,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1438,6 +1438,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -19,7 +19,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -42,7 +42,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -1059,6 +1058,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -1165,6 +1165,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1751,7 +1755,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -2017,6 +2021,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -63,7 +63,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -42,7 +42,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -1059,6 +1058,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -1165,6 +1165,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1751,7 +1755,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -2017,6 +2021,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -39,7 +39,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -19,7 +19,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -42,7 +42,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -1059,6 +1058,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -1165,6 +1165,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1751,7 +1755,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -2017,6 +2021,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -865,6 +865,7 @@
"description": "Optional Git metadata captured when the thread was created."
},
"id": {
"description": "Identifier for this thread. Codex-generated thread IDs are UUIDv7.",
"type": "string"
},
"modelProvider": {
@@ -971,6 +972,10 @@
],
"type": "string"
},
"ThreadExtra": {
"description": "Extra app-server data for a thread.",
"type": "object"
},
"ThreadId": {
"type": "string"
},
@@ -1557,7 +1562,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1823,6 +1828,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -1250,7 +1250,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1438,6 +1438,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -41,7 +41,6 @@
{
"enum": [
"untrusted",
"on-failure",
"on-request",
"never"
],
@@ -1250,7 +1250,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1438,6 +1438,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -1250,7 +1250,7 @@
"type": "string"
},
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
"$ref": "#/definitions/LegacyAppPathString"
},
"type": {
"enum": [
@@ -1438,6 +1438,7 @@
"description": "Only populated when the Turn's status is failed."
},
"id": {
"description": "Identifier for this turn. Codex-generated turn IDs are UUIDv7.",
"type": "string"
},
"items": {
@@ -2,4 +2,9 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Identifier for a Codex thread.
*
* Codex-generated thread IDs are UUIDv7, and some use cases rely on that.
*/
export type ThreadId = string;
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type AskForApproval = "untrusted" | "on-failure" | "on-request" | { "granular": { sandbox_approval: boolean, rules: boolean, skill_approval: boolean, request_permissions: boolean, mcp_elicitations: boolean, } } | "never";
export type AskForApproval = "untrusted" | "on-request" | { "granular": { sandbox_approval: boolean, rules: boolean, skill_approval: boolean, request_permissions: boolean, mcp_elicitations: boolean, } } | "never";
+24 -41
View File
@@ -8,87 +8,70 @@ import type { ThreadSource } from "./ThreadSource";
import type { ThreadStatus } from "./ThreadStatus";
import type { Turn } from "./Turn";
export type Thread = { id: string,
/**
export type Thread = {/**
* Identifier for this thread. Codex-generated thread IDs are UUIDv7.
*/
id: string, /**
* Session id shared by threads that belong to the same session tree.
*/
sessionId: string,
/**
sessionId: string, /**
* Source thread id when this thread was created by forking another thread.
*/
forkedFromId: string | null,
/**
forkedFromId: string | null, /**
* The ID of the parent thread. This will only be set if this thread is a subagent.
*/
parentThreadId: string | null,
/**
parentThreadId: string | null, /**
* Usually the first user message in the thread, if available.
*/
preview: string,
/**
preview: string, /**
* Whether the thread is ephemeral and should not be materialized on disk.
*/
ephemeral: boolean,
/**
ephemeral: boolean, /**
* Model provider used for this thread (for example, 'openai').
*/
modelProvider: string,
/**
modelProvider: string, /**
* Unix timestamp (in seconds) when the thread was created.
*/
createdAt: number,
/**
createdAt: number, /**
* Unix timestamp (in seconds) when the thread was last updated.
*/
updatedAt: number,
/**
updatedAt: number, /**
* Unix timestamp (in seconds) used for thread recency ordering.
*/
recencyAt: number | null,
/**
recencyAt: number | null, /**
* Current runtime status for the thread.
*/
status: ThreadStatus,
/**
status: ThreadStatus, /**
* [UNSTABLE] Path to the thread on disk.
*/
path: string | null,
/**
path: string | null, /**
* Working directory captured for the thread.
*/
cwd: AbsolutePathBuf,
/**
cwd: AbsolutePathBuf, /**
* Version of the CLI that created the thread.
*/
cliVersion: string,
/**
cliVersion: string, /**
* Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).
*/
source: SessionSource,
/**
source: SessionSource, /**
* Optional analytics source classification for this thread.
*/
threadSource: ThreadSource | null,
/**
threadSource: ThreadSource | null, /**
* Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
*/
agentNickname: string | null,
/**
agentNickname: string | null, /**
* Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
*/
agentRole: string | null,
/**
agentRole: string | null, /**
* Optional Git metadata captured when the thread was created.
*/
gitInfo: GitInfo | null,
/**
gitInfo: GitInfo | null, /**
* Optional user-facing thread title.
*/
name: string | null,
/**
name: string | null, /**
* Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read`
* (when `includeTurns` is true) responses.
* For all other responses and notifications returning a Thread,
* the turns field will be an empty list.
*/
turns: Array<Turn>, };
turns: Array<Turn>};
@@ -0,0 +1,8 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Extra app-server data for a thread.
*/
export type ThreadExtra = Record<string, never>;
@@ -105,4 +105,4 @@ reasoningEffort: ReasoningEffort | null,
/**
* Last known status of the target agents, when available.
*/
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch", id: string, query: string, action: WebSearchAction | null, } | { "type": "imageView", id: string, path: AbsolutePathBuf, } | { "type": "sleep", id: string, durationMs: number, } | { "type": "imageGeneration", id: string, status: string, revisedPrompt: string | null, result: string, savedPath?: AbsolutePathBuf, } | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch", id: string, query: string, action: WebSearchAction | null, } | { "type": "imageView", id: string, path: LegacyAppPathString, } | { "type": "sleep", id: string, durationMs: number, } | { "type": "imageGeneration", id: string, status: string, revisedPrompt: string | null, result: string, savedPath?: AbsolutePathBuf, } | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
+5 -1
View File
@@ -6,7 +6,11 @@ import type { TurnError } from "./TurnError";
import type { TurnItemsView } from "./TurnItemsView";
import type { TurnStatus } from "./TurnStatus";
export type Turn = { id: string,
export type Turn = {
/**
* Identifier for this turn. Codex-generated turn IDs are UUIDv7.
*/
id: string,
/**
* Thread items currently included in this turn payload.
*/
@@ -395,6 +395,7 @@ export type { ThreadCompactStartResponse } from "./ThreadCompactStartResponse";
export type { ThreadDeleteParams } from "./ThreadDeleteParams";
export type { ThreadDeleteResponse } from "./ThreadDeleteResponse";
export type { ThreadDeletedNotification } from "./ThreadDeletedNotification";
export type { ThreadExtra } from "./ThreadExtra";
export type { ThreadForkParams } from "./ThreadForkParams";
export type { ThreadForkResponse } from "./ThreadForkResponse";
export type { ThreadGoal } from "./ThreadGoal";
@@ -2573,6 +2573,7 @@ mod tests {
response: v2::ThreadStartResponse {
thread: v2::Thread {
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
extra: None,
session_id: "67e55044-10b1-426f-9247-bb680e5fe0c7".to_string(),
forked_from_id: None,
parent_thread_id: None,
@@ -2604,7 +2605,7 @@ mod tests {
"/tmp/AGENTS.md",
)),
],
approval_policy: v2::AskForApproval::OnFailure,
approval_policy: v2::AskForApproval::OnRequest,
approvals_reviewer: v2::ApprovalsReviewer::User,
sandbox: v2::SandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -2622,6 +2623,7 @@ mod tests {
"response": {
"thread": {
"id": "67e55044-10b1-426f-9247-bb680e5fe0c8",
"extra": null,
"sessionId": "67e55044-10b1-426f-9247-bb680e5fe0c7",
"forkedFromId": null,
"parentThreadId": null,
@@ -2651,7 +2653,7 @@ mod tests {
"cwd": absolute_path_string("tmp"),
"runtimeWorkspaceRoots": [],
"instructionSources": [absolute_path_string("tmp/AGENTS.md")],
"approvalPolicy": "on-failure",
"approvalPolicy": "on-request",
"approvalsReviewer": "user",
"sandbox": {
"type": "dangerFullAccess"
@@ -836,7 +836,7 @@ impl ThreadHistoryBuilder {
fn handle_view_image_tool_call(&mut self, payload: &ViewImageToolCallEvent) {
let item = ThreadItem::ImageView {
id: payload.call_id.clone(),
path: payload.path.clone(),
path: payload.path.clone().into(),
};
self.upsert_item_in_current_turn(item);
}
@@ -356,7 +356,10 @@ pub enum ThreadItem {
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
ImageView { id: String, path: AbsolutePathBuf },
ImageView {
id: String,
path: LegacyAppPathString,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Sleep {
@@ -855,7 +858,7 @@ impl From<CoreTurnItem> for ThreadItem {
},
CoreTurnItem::ImageView(image) => ThreadItem::ImageView {
id: image.id,
path: image.path,
path: image.path.into(),
},
CoreTurnItem::Sleep(sleep) => ThreadItem::Sleep {
id: sleep.id,
@@ -163,7 +163,6 @@ pub enum AskForApproval {
#[serde(rename = "untrusted")]
#[ts(rename = "untrusted")]
UnlessTrusted,
OnFailure,
OnRequest,
#[experimental("askForApproval.granular")]
Granular {
@@ -182,7 +181,6 @@ impl AskForApproval {
pub fn to_core(self) -> CoreAskForApproval {
match self {
AskForApproval::UnlessTrusted => CoreAskForApproval::UnlessTrusted,
AskForApproval::OnFailure => CoreAskForApproval::OnFailure,
AskForApproval::OnRequest => CoreAskForApproval::OnRequest,
AskForApproval::Granular {
sandbox_approval,
@@ -206,7 +204,6 @@ impl From<CoreAskForApproval> for AskForApproval {
fn from(value: CoreAskForApproval) -> Self {
match value {
CoreAskForApproval::UnlessTrusted => AskForApproval::UnlessTrusted,
CoreAskForApproval::OnFailure => AskForApproval::OnFailure,
CoreAskForApproval::OnRequest => AskForApproval::OnRequest,
CoreAskForApproval::Granular(granular_config) => AskForApproval::Granular {
sandbox_approval: granular_config.sandbox_approval,
@@ -168,6 +168,7 @@ fn thread_resume_response_round_trips_initial_turns_page() {
let response = ThreadResumeResponse {
thread: Thread {
id: "thr_123".to_string(),
extra: None,
session_id: "thr_123".to_string(),
forked_from_id: None,
parent_thread_id: None,
@@ -195,7 +196,7 @@ fn thread_resume_response_round_trips_initial_turns_page() {
cwd: absolute_path("tmp"),
runtime_workspace_roots: Vec::new(),
instruction_sources: Vec::new(),
approval_policy: AskForApproval::OnFailure,
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: ApprovalsReviewer::User,
sandbox: SandboxPolicy::DangerFullAccess,
active_permission_profile: None,
@@ -2573,14 +2574,14 @@ fn core_turn_item_into_thread_item_converts_supported_variants() {
let image_view_item = TurnItem::ImageView(ImageViewItem {
id: "view-image-1".to_string(),
path: test_path_buf("/tmp/view-image.png").abs(),
path: PathUri::from_abs_path(&test_path_buf("/tmp/view-image.png").abs()),
});
assert_eq!(
ThreadItem::from(image_view_item),
ThreadItem::ImageView {
id: "view-image-1".to_string(),
path: test_path_buf("/tmp/view-image.png").abs(),
path: LegacyAppPathString::from_abs_path(&test_path_buf("/tmp/view-image.png").abs()),
}
);
@@ -3689,7 +3690,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
"modelProvider": "openai",
"serviceTier": null,
"cwd": absolute_path_string("tmp"),
"approvalPolicy": "on-failure",
"approvalPolicy": "on-request",
"approvalsReviewer": "user",
"sandbox": { "type": "dangerFullAccess" },
"reasoningEffort": null
@@ -2,6 +2,7 @@ use super::CodexErrorInfo;
use super::ThreadItem;
use super::ThreadStatus;
use super::TurnStatus;
use codex_experimental_api_macros::ExperimentalApi;
use codex_protocol::protocol::SessionSource as CoreSessionSource;
use codex_protocol::protocol::SubAgentSource as CoreSubAgentSource;
use codex_protocol::protocol::ThreadSource as CoreThreadSource;
@@ -120,6 +121,12 @@ impl From<ThreadSource> for CoreThreadSource {
}
}
/// Extra app-server data for a thread.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase", export_to = "v2/")]
pub struct ThreadExtra {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -129,11 +136,15 @@ pub struct GitInfo {
pub origin_url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS, ExperimentalApi)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Thread {
/// Identifier for this thread. Codex-generated thread IDs are UUIDv7.
pub id: String,
/// Optional implementation-specific thread data.
#[experimental("thread.extra")]
pub extra: Option<ThreadExtra>,
/// Session id shared by threads that belong to the same session tree.
pub session_id: String,
/// Source thread id when this thread was created by forking another thread.
@@ -186,6 +197,7 @@ pub struct Thread {
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct Turn {
/// Identifier for this turn. Codex-generated turn IDs are UUIDv7.
pub id: String,
/// Thread items currently included in this turn payload.
pub items: Vec<ThreadItem>,
+13 -10
View File
@@ -46,12 +46,13 @@ cargo run -p codex-app-server-test-client -- \
Use `--capture-file /tmp/plugin-analytics.jsonl` to select the output path.
The command validates one `codex_plugin_disabled`, `codex_plugin_enabled`, and
`codex_plugin_used` event with the expected local plugin identity and capability
metadata. The enabled and disabled events come from successful writes to the
temporary config; the command does not mutate the remote enabled state. It
prints the events and leaves the JSONL file in place for inspection. It does not
install or uninstall plugins and does not modify the profile's persistent
config.
`codex_plugin_used` event with the expected local and remote plugin identities
and capability metadata. Each event includes the local ID in `plugin_id` and the
backend ID in `remote_plugin_id`. The enabled and disabled events come from
successful writes to the temporary config; the command does not mutate the
remote enabled state. It prints the events and leaves the JSONL file in place
for inspection. It does not install or uninstall plugins and does not modify
the profile's persistent config.
### Testing remote install and uninstall analytics
@@ -63,9 +64,11 @@ or CI.
Choose a remote plugin that is available to the active account and is not
currently installed. The command refuses to run when the plugin is already
installed, installs it, validates `codex_plugin_installed`, uninstalls it, and
verifies that the original uninstalled state was restored. The current install
event uses the backend ID as `plugin_id`. Uninstall is part of cleanup but is
not yet an analytics assertion.
validates `codex_plugin_uninstalled`, and verifies that the original
uninstalled state was restored.
The mutation events include the local Codex ID in `plugin_id` and the backend ID
in `remote_plugin_id`.
`--remote-plugin-id` takes the backend ID, such as `plugins~Plugin_...`, not the
local `<plugin>@<marketplace>` ID.
@@ -83,7 +86,7 @@ Analytics use the normal queue, reduction, batching, and serialization path,
but the debug capture destination suppresses analytics network delivery. The
command prints one of these final states:
- `PASS`: the install event validated and the plugin is uninstalled.
- `PASS`: the install and uninstall events validated and the plugin is uninstalled.
- `FAIL-CLEAN`: validation failed, but the original uninstalled state was
restored.
- `FAIL-LOCAL-CACHE`: the backend is uninstalled, but local cleanup reported
@@ -35,7 +35,7 @@ pub(super) fn read_events_for_remote_plugin(
matching.extend(
events
.iter()
.filter(|event| event["event_params"]["plugin_id"] == remote_plugin_id)
.filter(|event| event["event_params"]["remote_plugin_id"] == remote_plugin_id)
.cloned(),
);
}
@@ -44,6 +44,7 @@ pub(super) fn read_events_for_remote_plugin(
pub(super) struct PluginEventIdentity<'a> {
pub(super) plugin_id: &'a str,
pub(super) remote_plugin_id: &'a str,
pub(super) plugin_name: &'a str,
pub(super) marketplace_name: &'a str,
}
@@ -52,25 +53,29 @@ pub(super) fn validate_mutation_events(
events: Vec<Value>,
expected: PluginEventIdentity<'_>,
) -> Result<Vec<Value>> {
let event_type = "codex_plugin_installed";
let matching = events
.iter()
.filter(|event| event["event_type"] == event_type)
.collect::<Vec<_>>();
let [event] = matching.as_slice() else {
bail!(
"expected exactly one `{event_type}` event for `{}`, found {}",
expected.plugin_id,
matching.len()
);
};
validate_event(event, &expected)?;
Ok(vec![(*event).clone()])
let mut validated = Vec::new();
for event_type in ["codex_plugin_installed", "codex_plugin_uninstalled"] {
let matching = events
.iter()
.filter(|event| event["event_type"] == event_type)
.collect::<Vec<_>>();
let [event] = matching.as_slice() else {
bail!(
"expected exactly one `{event_type}` event for `{}`, found {}",
expected.remote_plugin_id,
matching.len()
);
};
validate_event(event, &expected)?;
validated.push((*event).clone());
}
Ok(validated)
}
fn validate_event(event: &Value, expected: &PluginEventIdentity<'_>) -> Result<()> {
let params = &event["event_params"];
require_string(params, "plugin_id", expected.plugin_id)?;
require_string(params, "remote_plugin_id", expected.remote_plugin_id)?;
require_string(params, "plugin_name", expected.plugin_name)?;
require_string(params, "marketplace_name", expected.marketplace_name)?;
for field in [
@@ -14,15 +14,17 @@ const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_test";
fn reads_and_validates_remote_plugin_mutation_events() {
let path = unique_capture_path("valid");
let installed = mutation_event("codex_plugin_installed");
let uninstalled = mutation_event("codex_plugin_uninstalled");
let unrelated = json!({
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "plugins~Plugin_other"
"plugin_id": "other@openai-curated-remote",
"remote_plugin_id": "plugins~Plugin_other"
}
});
let contents = [
json!({"events": [unrelated]}),
json!({"events": [installed]}),
json!({"events": [installed, uninstalled]}),
]
.into_iter()
.map(|payload| serde_json::to_string(&payload).expect("serialize capture payload"))
@@ -35,7 +37,7 @@ fn reads_and_validates_remote_plugin_mutation_events() {
let validated =
validate_mutation_events(events, expected_identity()).expect("validate mutation events");
assert_eq!(validated, vec![installed]);
assert_eq!(validated, vec![installed, uninstalled]);
fs::remove_file(path).expect("remove capture file");
}
@@ -62,7 +64,8 @@ fn mutation_event(event_type: &str) -> Value {
json!({
"event_type": event_type,
"event_params": {
"plugin_id": REMOTE_PLUGIN_ID,
"plugin_id": "sample@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "sample",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
@@ -75,7 +78,8 @@ fn mutation_event(event_type: &str) -> Value {
fn expected_identity() -> PluginEventIdentity<'static> {
PluginEventIdentity {
plugin_id: REMOTE_PLUGIN_ID,
plugin_id: "sample@openai-curated-remote",
remote_plugin_id: REMOTE_PLUGIN_ID,
plugin_name: "sample",
marketplace_name: "openai-curated-remote",
}
@@ -312,13 +312,19 @@ fn run_mutation_sequence(
state_err
}
})?;
wait_for_remote_plugin_event(
capture_path,
&expected.remote_plugin_id,
"codex_plugin_uninstalled",
)?;
let captured_events =
read_events_for_remote_plugin(capture_path, &expected.remote_plugin_id)?;
let events = validate_mutation_events(
captured_events,
PluginEventIdentity {
plugin_id: &expected.remote_plugin_id,
plugin_id: &expected.plugin_id,
remote_plugin_id: &expected.remote_plugin_id,
plugin_name: &expected.plugin_name,
marketplace_name: &expected.marketplace_name,
},
@@ -159,6 +159,7 @@ fn wait_for_plugin_usage(
#[derive(Debug)]
struct ExpectedPlugin {
plugin_id: String,
remote_plugin_id: String,
plugin_name: String,
marketplace_name: String,
}
@@ -208,13 +209,15 @@ fn expected_plugin(response: &PluginInstalledResponse, plugin_id: &str) -> Resul
plugin.availability
);
}
plugin
let remote_plugin_id = plugin
.remote_plugin_id
.as_ref()
.with_context(|| format!("plugin `{plugin_id}` does not have a remote plugin id"))?;
.with_context(|| format!("plugin `{plugin_id}` does not have a remote plugin id"))?
.clone();
Ok(ExpectedPlugin {
plugin_id: plugin.id.clone(),
remote_plugin_id,
plugin_name: plugin.name.clone(),
marketplace_name: marketplace.name.clone(),
})
@@ -444,6 +447,7 @@ fn event_count(events: &[Value], event_type: &str) -> usize {
fn validate_identity(event: &Value, expected: &ExpectedPlugin) -> Result<()> {
let params = &event["event_params"];
require_string(params, "plugin_id", &expected.plugin_id)?;
require_string(params, "remote_plugin_id", &expected.remote_plugin_id)?;
require_string(params, "plugin_name", &expected.plugin_name)?;
require_string(params, "marketplace_name", &expected.marketplace_name)
}
@@ -23,6 +23,7 @@ use codex_mcp::McpOAuthLoginSupport;
use codex_mcp::oauth_login_support;
use codex_mcp::should_retry_without_scopes;
use codex_plugin::PluginId;
use codex_plugin::PluginTelemetryMetadata;
use codex_rmcp_client::perform_oauth_login_silent;
#[derive(Clone)]
@@ -1515,6 +1516,7 @@ impl PluginRequestProcessor {
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&remote_marketplace_name,
/*plugin_id*/ None,
error_type,
err.to_string(),
);
@@ -1525,6 +1527,12 @@ impl PluginRequestProcessor {
})?;
let actual_remote_marketplace_name = remote_detail.marketplace_name.clone();
let remote_plugin_name = remote_detail.summary.name.clone();
let resolved_plugin_id = PluginId::parse(&remote_detail.summary.id).map_err(|err| {
internal_error(format!(
"invalid resolved plugin id `{}`: {err}",
remote_detail.summary.id
))
})?;
if remote_detail.summary.availability == PluginAvailability::DisabledByAdmin {
return Err(invalid_request(format!(
"remote plugin {remote_plugin_id} is disabled by admin"
@@ -1556,6 +1564,7 @@ impl PluginRequestProcessor {
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
Some(&resolved_plugin_id),
error_type,
err.to_string(),
);
@@ -1572,6 +1581,7 @@ impl PluginRequestProcessor {
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
Some(&resolved_plugin_id),
error_type,
err.to_string(),
);
@@ -1593,6 +1603,7 @@ impl PluginRequestProcessor {
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
Some(&result.plugin_id),
error_type,
err.to_string(),
);
@@ -1689,6 +1700,7 @@ impl PluginRequestProcessor {
&self,
remote_plugin_id: &str,
marketplace_name: &str,
plugin_id: Option<&PluginId>,
error_type: &'static str,
error_message: String,
) {
@@ -1699,16 +1711,17 @@ impl PluginRequestProcessor {
error = %error_message,
"remote plugin install failed"
);
// The remote id is reported separately; this local name only satisfies
// PluginId validation before remote details are available.
let Ok(plugin_id) = PluginId::new("unknown".to_string(), marketplace_name.to_string())
else {
return;
let plugin = if let Some(plugin_id) = plugin_id {
self.thread_manager
.plugins_manager()
.telemetry_metadata_for_plugin_id_with_remote_id(plugin_id, remote_plugin_id)
} else {
PluginTelemetryMetadata {
plugin_id: None,
remote_plugin_id: Some(remote_plugin_id.to_string()),
capability_summary: None,
}
};
let plugin = self
.thread_manager
.plugins_manager()
.telemetry_metadata_for_plugin_id_with_remote_id(&plugin_id, remote_plugin_id);
self.analytics_events_client
.track_plugin_install_failed(plugin, error_type.to_string());
}
@@ -1965,11 +1978,31 @@ impl PluginRequestProcessor {
let auth = self.auth_manager.auth().await;
let remote_plugin_service_config = remote_plugin_service_config(&config);
let uninstall_target = codex_core_plugins::remote::resolve_remote_plugin_uninstall_target(
&remote_plugin_service_config,
auth.as_ref(),
&plugin_id,
)
.await
.map_err(|err| {
remote_plugin_catalog_error_to_jsonrpc(err, "resolve remote plugin before uninstall")
})?;
let plugins_manager = self.thread_manager.plugins_manager();
let mut plugin_telemetry = plugins_manager
.telemetry_metadata_for_installed_plugin_with_remote_id(
&uninstall_target.plugin_id,
&uninstall_target.remote_plugin_id,
)
.await;
if plugin_telemetry.capability_summary.is_none() {
plugin_telemetry.capability_summary =
Some(uninstall_target.fallback_capability_summary.clone());
}
let uninstall_result = codex_core_plugins::remote::uninstall_remote_plugin(
&remote_plugin_service_config,
auth.as_ref(),
config.codex_home.to_path_buf(),
&plugin_id,
uninstall_target,
)
.await;
@@ -1977,7 +2010,8 @@ impl PluginRequestProcessor {
&uninstall_result,
Ok(()) | Err(RemotePluginCatalogError::CacheRemove(_))
) {
let plugins_manager = self.thread_manager.plugins_manager();
self.analytics_events_client
.track_plugin_uninstalled(plugin_telemetry);
if plugins_manager.clear_remote_installed_plugins_cache() {
self.on_effective_plugins_changed();
}
@@ -4156,6 +4156,7 @@ pub(crate) fn thread_from_stored_thread(
let thread_id = thread.thread_id.to_string();
let thread = Thread {
id: thread_id.clone(),
extra: None,
session_id: thread_id,
forked_from_id: thread.forked_from_id.map(|id| id.to_string()),
parent_thread_id: thread.parent_thread_id.map(|id| id.to_string()),
@@ -4366,6 +4367,7 @@ fn build_thread_from_snapshot(
let now = time::OffsetDateTime::now_utc().unix_timestamp();
Thread {
id: thread_id.to_string(),
extra: None,
session_id,
forked_from_id: None,
parent_thread_id: config_snapshot.parent_thread_id.map(|id| id.to_string()),
@@ -183,6 +183,7 @@ mod tests {
fn test_thread(items: Vec<ThreadItem>) -> Thread {
Thread {
id: "thread-1".to_string(),
extra: None,
session_id: "session-1".to_string(),
forked_from_id: None,
parent_thread_id: None,
@@ -314,6 +314,7 @@ pub(crate) fn summary_to_thread(
let thread_id = conversation_id.to_string();
Thread {
id: thread_id.clone(),
extra: None,
session_id: thread_id,
forked_from_id: None,
parent_thread_id: None,
+1
View File
@@ -889,6 +889,7 @@ mod tests {
fn test_thread(thread_id: &str, source: codex_app_server_protocol::SessionSource) -> Thread {
Thread {
id: thread_id.to_string(),
extra: None,
session_id: thread_id.to_string(),
forked_from_id: None,
parent_thread_id: None,
@@ -538,12 +538,10 @@ async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Res
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["plugin_name"], "unknown");
assert_eq!(
event_params["marketplace_name"],
"caller-marketplace-is-ignored"
);
assert_eq!(event_params["plugin_id"], json!(null));
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["plugin_name"], json!(null));
assert_eq!(event_params["marketplace_name"], json!(null));
assert_eq!(
event_params["error_type"],
"remote_catalog_unexpected_status"
@@ -883,6 +881,7 @@ async fn plugin_install_tracks_analytics_event() -> Result<()> {
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "sample-plugin@debug",
"remote_plugin_id": null,
"plugin_name": "sample-plugin",
"marketplace_name": "debug",
"has_skills": false,
@@ -946,6 +945,7 @@ async fn plugin_install_failure_tracks_analytics_event() -> Result<()> {
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "sample-plugin@debug");
assert_eq!(event_params["remote_plugin_id"], json!(null));
assert_eq!(event_params["plugin_name"], "sample-plugin");
assert_eq!(event_params["marketplace_name"], "debug");
assert_eq!(event_params["has_skills"], json!(null));
@@ -995,7 +995,8 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> {
"events": [{
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": REMOTE_PLUGIN_ID,
"plugin_id": "linear@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "linear",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
@@ -1072,7 +1073,8 @@ async fn plugin_install_preserves_status_when_remote_bundle_error_body_is_too_la
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote");
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["marketplace_name"], "openai-curated-remote");
assert_eq!(event_params["error_type"], "remote_bundle_download_status");
assert!(
@@ -139,6 +139,7 @@ async fn plugin_uninstall_tracks_analytics_event() -> Result<()> {
"event_type": "codex_plugin_uninstalled",
"event_params": {
"plugin_id": "sample-plugin@debug",
"remote_plugin_id": null,
"plugin_name": "sample-plugin",
"marketplace_name": "debug",
"has_skills": false,
@@ -216,6 +217,11 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#))
.mount(&server)
.await;
let remote_plugin_cache_root = codex_home
.path()
@@ -225,6 +231,11 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
remote_plugin_cache_root.join("1.0.0/.codex-plugin/plugin.json"),
r#"{"name":"linear","version":"1.0.0"}"#,
)?;
std::fs::create_dir_all(remote_plugin_cache_root.join("1.0.0/skills/plan-work"))?;
std::fs::write(
remote_plugin_cache_root.join("1.0.0/skills/plan-work/SKILL.md"),
"---\nname: plan-work\ndescription: Plan work\n---\n",
)?;
let legacy_remote_plugin_cache_root = codex_home.path().join(format!(
"plugins/cache/openai-curated-remote/{REMOTE_PLUGIN_ID}"
));
@@ -233,6 +244,10 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
// Simulate a background remote-cache refresh removing the local bundle
// before the uninstall request captures its telemetry metadata.
std::fs::remove_dir_all(remote_plugin_cache_root.join("1.0.0"))?;
let request_id = mcp
.send_plugin_uninstall_request(PluginUninstallParams {
plugin_id: REMOTE_PLUGIN_ID.to_string(),
@@ -255,6 +270,25 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
.await?;
assert!(!remote_plugin_cache_root.exists());
assert!(!legacy_remote_plugin_cache_root.exists());
let payload = wait_for_plugin_analytics_payload(&server).await?;
assert_eq!(
payload,
json!({
"events": [{
"event_type": "codex_plugin_uninstalled",
"event_params": {
"plugin_id": "linear@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "linear",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": DEFAULT_CLIENT_NAME,
}
}]
})
);
Ok(())
}
@@ -638,7 +672,11 @@ async fn mount_remote_plugin_detail_with_name(
"interface": {{
"short_description": "Plan and track work"
}},
"skills": []
"skills": [{{
"name": "plan-work",
"description": "Plan work",
"interface": null
}}]
}}
}}"#
);
@@ -652,6 +690,29 @@ async fn mount_remote_plugin_detail_with_name(
.await;
}
async fn wait_for_plugin_analytics_payload(server: &MockServer) -> Result<serde_json::Value> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let Some(requests) = server.received_requests().await else {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
};
if let Some(request) = requests.iter().find(|request| {
request.method == "POST"
&& request
.url
.path()
.ends_with("/codex/analytics-events/events")
}) {
return serde_json::from_slice(&request.body)
.map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"));
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?
}
async fn wait_for_remote_plugin_request_count(
server: &MockServer,
method_name: &str,
+3
View File
@@ -383,6 +383,7 @@ async fn run_command_under_sandbox(
network_sandbox_policy,
sandbox_policy_cwd: sandbox_policy_cwd.as_path(),
enforce_managed_network,
managed_network: None,
environment_id: None,
network: network.as_ref(),
extra_allow_unix_sockets: allow_unix_sockets,
@@ -472,6 +473,7 @@ async fn run_command_under_windows_session(
) -> ! {
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_windows_sandbox::WindowsSandboxProxySettingsMode;
use codex_windows_sandbox::WindowsSandboxSessionRequest;
use codex_windows_sandbox::spawn_windows_sandbox_session_for_level;
@@ -484,6 +486,7 @@ async fn run_command_under_windows_session(
cwd: cwd.as_path(),
env_map: env,
windows_sandbox_level: WindowsSandboxLevel::from_config(config),
proxy_settings_mode: WindowsSandboxProxySettingsMode::Reconcile,
proxy_enforced: false,
timeout_ms: None,
read_roots_override: None,
@@ -206,9 +206,6 @@ fn tool_with_model_visible_input_schema_leaves_tools_without_file_params_unchang
#[test]
fn elicitation_granular_policy_defaults_to_prompting() {
assert!(!elicitation_is_rejected_by_policy(
AskForApproval::OnFailure
));
assert!(!elicitation_is_rejected_by_policy(
AskForApproval::OnRequest
));
@@ -808,7 +805,7 @@ async fn list_all_tools_uses_cached_tool_info_snapshot_while_client_is_pending()
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -845,7 +842,7 @@ async fn list_available_server_infos_uses_cache_while_client_is_pending() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -884,7 +881,7 @@ async fn list_all_tools_accepts_canonical_namespaced_tool_names() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -928,7 +925,7 @@ async fn list_all_tools_applies_legacy_mcp_prefix_by_default() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -971,7 +968,7 @@ async fn list_all_tools_blocks_while_client_is_pending_without_cached_tool_info_
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1008,7 +1005,7 @@ async fn shutdown_cancels_pending_tool_listing() {
}
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1053,7 +1050,7 @@ async fn shutdown_continues_after_caller_is_aborted() {
}
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1097,7 +1094,7 @@ async fn list_all_tools_does_not_block_when_cached_tool_info_snapshot_is_empty()
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1137,7 +1134,7 @@ async fn list_all_tools_uses_cached_tool_info_snapshot_when_client_startup_fails
))
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1184,7 +1181,7 @@ async fn list_all_tools_adds_server_metadata_to_cached_tools() {
let pending_client = futures::future::pending::<Result<ManagedClient, StartupOutcomeError>>()
.boxed()
.shared();
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1252,7 +1249,7 @@ fn server_metadata_preserves_tool_approval_policy() {
#[test]
fn host_owned_codex_apps_requires_server_metadata() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1265,7 +1262,7 @@ fn host_owned_codex_apps_requires_server_metadata() {
#[test]
fn host_owned_codex_apps_matches_reserved_name_with_server_metadata() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let permission_profile = Constrained::allow_any(PermissionProfile::default());
let mut manager = McpConnectionManager::new_uninitialized(
&approval_policy,
@@ -1288,7 +1285,7 @@ fn host_owned_codex_apps_matches_reserved_name_with_server_metadata() {
#[tokio::test]
async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
let approval_policy = Constrained::allow_any(AskForApproval::OnFailure);
let approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let (tx_event, rx_event) = async_channel::unbounded();
drop(rx_event);
let codex_home = tempdir().expect("tempdir");
-1
View File
@@ -247,7 +247,6 @@ impl ElicitationRequestManager {
pub(crate) fn elicitation_is_rejected_by_policy(approval_policy: AskForApproval) -> bool {
match approval_policy {
AskForApproval::Never => true,
AskForApproval::OnFailure => false,
AskForApproval::OnRequest => false,
AskForApproval::UnlessTrusted => false,
AskForApproval::Granular(granular_config) => !granular_config.allows_mcp_elicitations(),
+1 -2
View File
@@ -27,7 +27,7 @@ fn test_mcp_config(codex_home: PathBuf) -> McpConfig {
mcp_oauth_callback_port: None,
mcp_oauth_callback_url: None,
skill_mcp_dependency_install_enabled: true,
approval_policy: Constrained::allow_any(AskForApproval::OnFailure),
approval_policy: Constrained::allow_any(AskForApproval::OnRequest),
codex_linux_sandbox_exe: None,
use_legacy_landlock: false,
apps_enabled: false,
@@ -84,7 +84,6 @@ fn mcp_prompt_auto_approval_honors_unrestricted_managed_profiles() {
fn mcp_prompt_auto_approval_honors_approved_tools_in_all_permission_modes() {
for approval_policy in [
AskForApproval::UnlessTrusted,
AskForApproval::OnFailure,
AskForApproval::OnRequest,
AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: true,
@@ -2513,17 +2513,6 @@ allowed_approvals_reviewers = ["user"]
.can_set(&AskForApproval::UnlessTrusted)
.is_ok()
);
assert_eq!(
requirements
.approval_policy
.can_set(&AskForApproval::OnFailure),
Err(ConstraintError::InvalidValue {
field_name: "approval_policy",
candidate: "OnFailure".into(),
allowed: "[UnlessTrusted, OnRequest]".into(),
requirement_source: RequirementSource::Unknown,
})
);
assert!(
requirements
.approval_policy
+4 -4
View File
@@ -52,7 +52,7 @@ fn active_user_layer_is_highest_precedence_user_layer() {
toml::from_str(
r#"
model = "base"
approval_policy = "on-failure"
approval_policy = "on-request"
"#,
)
.expect("base config"),
@@ -86,7 +86,7 @@ approval_policy = "on-failure"
.expect("merged user config")
.get("approval_policy")
.and_then(toml::Value::as_str),
Some("on-failure")
Some("on-request")
);
}
@@ -107,7 +107,7 @@ fn with_user_config_updates_matching_user_layer_without_replacing_active_profile
file: profile_file.clone(),
profile: Some("work".to_string()),
},
toml::from_str(r#"approval_policy = "on-failure""#).expect("profile config"),
toml::from_str(r#"approval_policy = "on-request""#).expect("profile config"),
);
let stack = ConfigLayerStack::new(
vec![base_layer, profile_layer],
@@ -136,6 +136,6 @@ fn with_user_config_updates_matching_user_layer_without_replacing_active_profile
.expect("merged user config")
.get("approval_policy")
.and_then(toml::Value::as_str),
Some("on-failure")
Some("on-request")
);
}
+35 -4
View File
@@ -716,6 +716,37 @@ impl PluginsManager {
remote_installed_plugins_to_config(plugins, &self.store)
}
fn remote_plugin_id_for(&self, plugin_id: &PluginId) -> Option<String> {
let cached_remote_plugin_id = {
let cache = match self.remote_installed_plugins_cache.read() {
Ok(cache) => cache,
Err(err) => err.into_inner(),
};
cache.as_ref().and_then(|plugins| {
plugins.iter().find_map(|plugin| {
(plugin.name == plugin_id.plugin_name
&& plugin.marketplace_name == plugin_id.marketplace_name)
.then(|| plugin.id.clone())
})
})
};
if cached_remote_plugin_id.is_some() {
return cached_remote_plugin_id;
}
match self.store.remote_plugin_id(plugin_id) {
Ok(remote_plugin_id) => remote_plugin_id,
Err(err) => {
tracing::warn!(
plugin_id = %plugin_id.as_key(),
error = %err,
"failed to read persisted remote plugin identity"
);
None
}
}
}
pub async fn telemetry_metadata_for_installed_plugin(
&self,
plugin_id: &PluginId,
@@ -747,8 +778,8 @@ impl PluginsManager {
plugin_id: &PluginId,
) -> PluginTelemetryMetadata {
PluginTelemetryMetadata {
plugin_id: plugin_id.clone(),
remote_plugin_id: None,
plugin_id: Some(plugin_id.clone()),
remote_plugin_id: self.remote_plugin_id_for(plugin_id),
capability_summary: None,
}
}
@@ -770,8 +801,8 @@ impl PluginsManager {
) -> Option<PluginTelemetryMetadata> {
let plugin_id = PluginId::parse(&summary.config_name).ok()?;
Some(PluginTelemetryMetadata {
plugin_id,
remote_plugin_id: None,
remote_plugin_id: self.remote_plugin_id_for(&plugin_id),
plugin_id: Some(plugin_id),
capability_summary: Some(summary.clone()),
})
}
+101 -4
View File
@@ -859,7 +859,7 @@ async fn installed_plugin_telemetry_metadata_collects_capabilities() {
assert_eq!(
metadata,
PluginTelemetryMetadata {
plugin_id,
plugin_id: Some(plugin_id),
remote_plugin_id: None,
capability_summary: Some(PluginCapabilitySummary {
config_name: "sample@test".to_string(),
@@ -873,6 +873,71 @@ async fn installed_plugin_telemetry_metadata_collects_capabilities() {
);
}
#[tokio::test]
async fn installed_plugin_telemetry_metadata_resolves_persisted_remote_identity() {
let codex_home = TempDir::new().unwrap();
write_cached_plugin(codex_home.path(), "openai-curated-remote", "linear");
let plugin_id =
PluginId::parse("linear@openai-curated-remote").expect("plugin id should parse");
PluginStore::new(codex_home.path().to_path_buf())
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_linear")
.expect("persist remote plugin id");
let manager = PluginsManager::new(codex_home.path().to_path_buf());
let metadata = manager
.telemetry_metadata_for_installed_plugin(&plugin_id)
.await;
assert_eq!(
metadata,
PluginTelemetryMetadata {
plugin_id: Some(plugin_id),
remote_plugin_id: Some("plugins~Plugin_linear".to_string()),
capability_summary: Some(PluginCapabilitySummary {
config_name: "linear@openai-curated-remote".to_string(),
display_name: "linear".to_string(),
description: None,
has_skills: true,
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
}),
}
);
}
#[tokio::test]
async fn installed_plugin_telemetry_metadata_prefers_remote_snapshot_identity() {
let codex_home = TempDir::new().unwrap();
write_cached_plugin(codex_home.path(), "openai-curated-remote", "linear");
let plugin_id =
PluginId::parse("linear@openai-curated-remote").expect("plugin id should parse");
PluginStore::new(codex_home.path().to_path_buf())
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_stale")
.expect("persist remote plugin id");
let manager = PluginsManager::new(codex_home.path().to_path_buf());
manager.write_remote_installed_plugins_cache(vec![remote_installed_linear_plugin()]);
let metadata = manager
.telemetry_metadata_for_installed_plugin(&plugin_id)
.await;
assert_eq!(
metadata,
PluginTelemetryMetadata {
plugin_id: Some(plugin_id),
remote_plugin_id: Some("plugins~Plugin_linear".to_string()),
capability_summary: Some(PluginCapabilitySummary {
config_name: "linear@openai-curated-remote".to_string(),
display_name: "linear".to_string(),
description: None,
has_skills: true,
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
}),
}
);
}
#[tokio::test]
async fn installed_plugin_telemetry_metadata_accepts_authoritative_remote_identity() {
let codex_home = TempDir::new().unwrap();
@@ -887,7 +952,7 @@ async fn installed_plugin_telemetry_metadata_accepts_authoritative_remote_identi
assert_eq!(
metadata,
PluginTelemetryMetadata {
plugin_id,
plugin_id: Some(plugin_id),
remote_plugin_id: Some("plugins~Plugin_linear".to_string()),
capability_summary: None,
}
@@ -912,14 +977,46 @@ fn capability_summary_telemetry_metadata_uses_local_identity() {
assert_eq!(
metadata,
Some(PluginTelemetryMetadata {
plugin_id: PluginId::parse("linear@openai-curated-remote")
.expect("plugin id should parse"),
plugin_id: Some(
PluginId::parse("linear@openai-curated-remote").expect("plugin id should parse"),
),
remote_plugin_id: None,
capability_summary: Some(summary),
})
);
}
#[test]
fn capability_summary_telemetry_metadata_resolves_persisted_remote_identity() {
let codex_home = TempDir::new().unwrap();
write_cached_plugin(codex_home.path(), "openai-curated-remote", "linear");
let plugin_id =
PluginId::parse("linear@openai-curated-remote").expect("plugin id should parse");
PluginStore::new(codex_home.path().to_path_buf())
.write_remote_plugin_id(&plugin_id, "plugins~Plugin_linear")
.expect("persist remote plugin id");
let manager = PluginsManager::new(codex_home.path().to_path_buf());
let summary = PluginCapabilitySummary {
config_name: "linear@openai-curated-remote".to_string(),
display_name: "Linear".to_string(),
description: Some("Track work".to_string()),
has_skills: true,
mcp_server_names: vec!["linear".to_string()],
app_connector_ids: vec![AppConnectorId("linear-app".to_string())],
};
let metadata = manager.telemetry_metadata_for_capability_summary(&summary);
assert_eq!(
metadata,
Some(PluginTelemetryMetadata {
plugin_id: Some(plugin_id),
remote_plugin_id: Some("plugins~Plugin_linear".to_string()),
capability_summary: Some(summary),
})
);
}
#[tokio::test]
async fn remote_installed_cache_prefers_local_curated_conflicts_when_remote_plugin_disabled() {
let codex_home = TempDir::new().unwrap();
+71 -12
View File
@@ -13,8 +13,10 @@ use codex_login::default_client::build_reqwest_client;
use codex_login::default_client::chatgpt_cloudflare_cookie_header;
use codex_plugin::AppConnectorId;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginCapabilitySummary;
use codex_plugin::PluginId;
use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_plugins::plugin_service_routing::plugin_service_routing_cookie;
use reqwest::RequestBuilder;
@@ -125,6 +127,13 @@ pub struct RemotePluginServiceConfig {
pub plugin_service_preview: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemotePluginUninstallTarget {
pub plugin_id: PluginId,
pub remote_plugin_id: String,
pub fallback_capability_summary: PluginCapabilitySummary,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RemoteMarketplace {
pub name: String,
@@ -1309,40 +1318,90 @@ pub async fn install_remote_plugin(
})
}
pub async fn resolve_remote_plugin_uninstall_target(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
remote_plugin_id: &str,
) -> Result<RemotePluginUninstallTarget, RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let plugin = fetch_plugin_detail(
config,
auth,
remote_plugin_id,
/*include_download_urls*/ false,
)
.await?;
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
let plugin_id = PluginId::new(plugin.name.clone(), marketplace_name).map_err(|err| {
RemotePluginCatalogError::UnexpectedResponse(format!(
"invalid local plugin id for remote plugin `{}`: {err}",
plugin.id
))
})?;
let app_declarations = plugin
.release
.app_manifest
.as_ref()
.map(plugin_app_declarations_from_value)
.unwrap_or_else(|| app_declarations_from_remote_app_ids(&plugin.release.app_ids));
let mut mcp_server_names = plugin
.release
.mcp_servers
.iter()
.map(|server| server.key.clone())
.collect::<Vec<_>>();
mcp_server_names.sort_unstable();
mcp_server_names.dedup();
let fallback_capability_summary = PluginCapabilitySummary {
config_name: plugin_id.as_key(),
display_name: plugin.release.display_name,
description: prompt_safe_plugin_description(Some(&plugin.release.description)),
has_skills: !plugin.release.skills.is_empty(),
mcp_server_names,
app_connector_ids: app_connector_ids_from_declarations(&app_declarations),
};
Ok(RemotePluginUninstallTarget {
plugin_id,
remote_plugin_id: plugin.id,
fallback_capability_summary,
})
}
pub async fn uninstall_remote_plugin(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
codex_home: PathBuf,
plugin_id: &str,
target: RemotePluginUninstallTarget,
) -> Result<(), RemotePluginCatalogError> {
let auth = ensure_chatgpt_auth(auth)?;
let plugin = fetch_plugin_detail(
config, auth, plugin_id, /*include_download_urls*/ false,
)
.await?;
let marketplace_name = remote_plugin_canonical_marketplace_name(&plugin)?.to_string();
let plugin_name = plugin.name;
let RemotePluginUninstallTarget {
plugin_id,
remote_plugin_id,
fallback_capability_summary: _,
} = target;
let marketplace_name = plugin_id.marketplace_name.clone();
let plugin_name = plugin_id.plugin_name.clone();
let base_url = config.chatgpt_base_url.trim_end_matches('/');
let url = format!("{base_url}/ps/plugins/{plugin_id}/uninstall");
let url = format!("{base_url}/ps/plugins/{remote_plugin_id}/uninstall");
let client = build_reqwest_client();
let request = authenticated_request(client.post(&url), auth)?;
let response: RemotePluginMutationResponse = send_and_decode(config, request, &url).await?;
if response.id != plugin_id {
if response.id != remote_plugin_id {
return Err(RemotePluginCatalogError::UnexpectedPluginId {
expected: plugin_id.to_string(),
expected: remote_plugin_id,
actual: response.id,
});
}
if response.enabled {
return Err(RemotePluginCatalogError::UnexpectedEnabledState {
plugin_id: plugin_id.to_string(),
plugin_id: response.id,
expected_enabled: false,
actual_enabled: response.enabled,
});
}
let legacy_plugin_id = plugin_id.to_string();
let legacy_plugin_id = response.id;
tokio::task::spawn_blocking(move || {
remove_remote_plugin_cache(codex_home, marketplace_name, plugin_name, legacy_plugin_id)
})
-7
View File
@@ -252,13 +252,6 @@
],
"type": "string"
},
{
"description": "DEPRECATED: *All* commands are auto‑approved, but they are expected to run inside a sandbox where network access is disabled and writes are confined to a specific set of paths. If the command fails, it will be escalated to the user to approve execution without a sandbox. Prefer `OnRequest` for interactive runs or `Never` for non-interactive runs.",
"enum": [
"on-failure"
],
"type": "string"
},
{
"description": "The model decides when to ask the user for approval.",
"enum": [
+1 -1
View File
@@ -171,7 +171,7 @@ For all of testing, running, building, and formatting, do not attempt to fix unr
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
- When running in non-interactive approval modes like **never** or **on-failure**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task.
- When running in the non-interactive approval mode **never**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task.
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
+1 -1
View File
@@ -145,7 +145,7 @@ For all of testing, running, building, and formatting, do not attempt to fix unr
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
- When running in non-interactive approval modes like **never** or **on-failure**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task.
- When running in the non-interactive approval mode **never**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task.
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
@@ -158,7 +158,7 @@ For all of testing, running, building, and formatting, do not attempt to fix unr
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
- When running in non-interactive approval modes like **never** or **on-failure**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
@@ -640,7 +640,7 @@ async fn selected_user_config_file_layers_over_base_user_config() {
tmp.path().join(CONFIG_TOML_FILE),
r#"
model = "gpt-main"
approval_policy = "on-failure"
approval_policy = "on-request"
"#,
)
.expect("write default user config");
@@ -697,7 +697,7 @@ approval_policy = "on-failure"
.effective_config()
.get("approval_policy")
.and_then(TomlValue::as_str),
Some("on-failure")
Some("on-request")
);
}
@@ -1033,12 +1033,6 @@ personality = true
config_requirements
.approval_policy
.can_set(&AskForApproval::Never)?;
assert!(
config_requirements
.approval_policy
.can_set(&AskForApproval::OnFailure)
.is_err()
);
assert_eq!(
config_requirements.web_search_mode.value(),
WebSearchMode::Cached
+2 -2
View File
@@ -8320,7 +8320,7 @@ model_provider = "openai-custom"
[profiles.zdr]
model = "o3"
model_provider = "openai"
approval_policy = "on-failure"
approval_policy = "on-request"
[profiles.zdr.analytics]
enabled = false
@@ -8328,7 +8328,7 @@ enabled = false
[profiles.gpt5]
model = "gpt-5.4"
model_provider = "openai"
approval_policy = "on-failure"
approval_policy = "on-request"
model_reasoning_effort = "high"
model_reasoning_summary = "detailed"
model_verbosity = "high"
+2
View File
@@ -377,6 +377,7 @@ pub fn build_exec_request(
args: args.to_vec(),
cwd,
env,
managed_network: None,
additional_permissions: None,
};
let options = ExecOptions {
@@ -459,6 +460,7 @@ pub(crate) async fn execute_exec_request(
arg0,
exec_server_sandbox: _,
exec_server_enforce_managed_network: _,
exec_server_managed_network: _,
} = exec_request;
// TODO(anp): Keep PathUri through the local process launch boundary.
+2 -4
View File
@@ -177,7 +177,6 @@ pub(crate) fn prompt_is_rejected_by_policy(
) -> Option<&'static str> {
match approval_policy {
AskForApproval::Never => Some(PROMPT_CONFLICT_REASON),
AskForApproval::OnFailure => None,
AskForApproval::OnRequest => None,
AskForApproval::UnlessTrusted => None,
AskForApproval::Granular(granular_config) => {
@@ -689,15 +688,14 @@ pub(crate) fn render_decision_for_unmatched_command(
Decision::Forbidden
}
}
AskForApproval::OnFailure
| AskForApproval::OnRequest
AskForApproval::OnRequest
| AskForApproval::UnlessTrusted
| AskForApproval::Granular(_) => Decision::Prompt,
};
}
match approval_policy {
AskForApproval::Never | AskForApproval::OnFailure => {
AskForApproval::Never => {
// We allow the command to run, relying on the sandbox for
// protection.
Decision::Allow
+3 -4
View File
@@ -738,10 +738,9 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str);
fn hook_permission_mode(turn_context: &TurnContext) -> String {
match turn_context.approval_policy.value() {
AskForApproval::Never => "bypassPermissions",
AskForApproval::UnlessTrusted
| AskForApproval::OnFailure
| AskForApproval::OnRequest
| AskForApproval::Granular(_) => "default",
AskForApproval::UnlessTrusted | AskForApproval::OnRequest | AskForApproval::Granular(_) => {
"default"
}
}
.to_string()
}
+2 -4
View File
@@ -653,10 +653,8 @@ async fn maybe_request_codex_apps_auth_elicitation(
AskForApproval::Granular(granular_config) if !granular_config.allows_mcp_elicitations() => {
return result;
}
AskForApproval::OnFailure
| AskForApproval::OnRequest
| AskForApproval::UnlessTrusted
| AskForApproval::Granular(_) => {}
AskForApproval::OnRequest | AskForApproval::UnlessTrusted | AskForApproval::Granular(_) => {
}
}
let connector_id = metadata.and_then(|metadata| metadata.connector_id.as_deref());
-1
View File
@@ -2922,7 +2922,6 @@ async fn approve_mode_skips_guardian_in_every_permission_mode() {
for approval_policy in [
AskForApproval::UnlessTrusted,
AskForApproval::OnFailure,
AskForApproval::OnRequest,
AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: true,
+2 -7
View File
@@ -44,10 +44,7 @@ pub fn assess_patch_safety(
}
match policy {
AskForApproval::OnFailure
| AskForApproval::Never
| AskForApproval::OnRequest
| AskForApproval::Granular(_) => {
AskForApproval::Never | AskForApproval::OnRequest | AskForApproval::Granular(_) => {
// Continue to see if this can be auto-approved.
}
// TODO(ragona): I'm not sure this is actually correct? I believe in this case
@@ -66,9 +63,7 @@ pub fn assess_patch_safety(
// Even though the patch appears to be constrained to writable paths, it is
// possible that paths in the patch are hard links to files outside the
// writable roots, so we should still run `apply_patch` in a sandbox in that case.
if is_write_patch_constrained_to_writable_paths(action, file_system_sandbox_policy, cwd)
|| matches!(policy, AskForApproval::OnFailure)
{
if is_write_patch_constrained_to_writable_paths(action, file_system_sandbox_policy, cwd) {
if matches!(
permission_profile,
PermissionProfile::Disabled | PermissionProfile::External { .. }
+4
View File
@@ -15,6 +15,7 @@ use crate::exec::execute_exec_request;
use crate::spawn::CODEX_SANDBOX_ENV_VAR;
use crate::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR;
use codex_file_system::FileSystemSandboxContext;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::exec_output::ExecToolCallOutput;
@@ -63,6 +64,7 @@ pub struct ExecRequest {
pub arg0: Option<String>,
pub(crate) exec_server_sandbox: Option<FileSystemSandboxContext>,
pub(crate) exec_server_enforce_managed_network: bool,
pub(crate) exec_server_managed_network: Option<ManagedNetworkSandboxContext>,
}
impl ExecRequest {
@@ -107,6 +109,7 @@ impl ExecRequest {
arg0,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
}
}
@@ -165,6 +168,7 @@ impl ExecRequest {
arg0,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
}
}
}
+12 -4
View File
@@ -724,7 +724,7 @@ impl Codex {
op: Op,
trace: Option<W3cTraceContext>,
) -> CodexResult<String> {
let id = Uuid::now_v7().to_string();
let id = new_submission_id();
let sub = Submission {
id: id.clone(),
op,
@@ -742,7 +742,7 @@ impl Codex {
client_user_message_id: Option<String>,
) -> CodexResult<String> {
debug_assert!(matches!(op, Op::UserInput { .. }));
let id = Uuid::now_v7().to_string();
let id = new_submission_id();
let sub = Submission {
id: id.clone(),
op,
@@ -869,6 +869,15 @@ impl Codex {
}
}
/// Generate a core submission ID. App-server exposes submission IDs that
/// create turns as a public-facing turn ID.
///
/// Some use cases take advantage of the fact that these are UUID7 which
/// encodes a timestamp, so think carefully before changing this.
fn new_submission_id() -> String {
Uuid::now_v7().to_string()
}
fn get_service_tier(
configured_service_tier: Option<String>,
fast_mode_enabled: bool,
@@ -2237,8 +2246,7 @@ impl Session {
strict_auto_review: false,
});
}
AskForApproval::OnFailure
| AskForApproval::OnRequest
AskForApproval::OnRequest
| AskForApproval::UnlessTrusted
| AskForApproval::Granular(_) => {}
}
-9
View File
@@ -748,15 +748,6 @@ impl Session {
) {
post_session_configured_events.push(event);
}
if config.permissions.approval_policy.value() == AskForApproval::OnFailure {
post_session_configured_events.push(Event {
id: "".to_owned(),
msg: EventMsg::Warning(WarningEvent {
message: "`on-failure` approval policy is deprecated and will be removed in a future release. Use `on-request` for interactive approvals or `never` for non-interactive runs.".to_string(),
}),
});
}
let auth = auth.as_ref();
let auth_mode = auth.map(CodexAuth::auth_mode).map(TelemetryAuthMode::from);
let account_id = auth.and_then(CodexAuth::get_account_id);
+3 -3
View File
@@ -1288,7 +1288,7 @@ async fn reload_user_config_layer_updates_base_and_selected_profile_layers() {
let profile_config_path = codex_home.join("work.config.toml");
std::fs::write(
&base_config_path,
"model = \"base\"\napproval_policy = \"on-failure\"\n",
"model = \"base\"\napproval_policy = \"on-request\"\n",
)
.expect("write base user config");
std::fs::write(&profile_config_path, "model = \"profile-old\"\n")
@@ -10147,7 +10147,7 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() {
// Ensure policy is NOT OnRequest so the early rejection path triggers
turn_context_raw
.approval_policy
.set(AskForApproval::OnFailure)
.set(AskForApproval::Never)
.expect("test setup should allow updating approval policy");
let session = Arc::new(session);
let mut turn_context = Arc::new(turn_context_raw);
@@ -10310,7 +10310,7 @@ async fn unified_exec_rejects_escalated_permissions_when_policy_not_on_request()
let (session, mut turn_context_raw) = make_session_and_context().await;
turn_context_raw
.approval_policy
.set(AskForApproval::OnFailure)
.set(AskForApproval::Never)
.expect("test setup should allow updating approval policy");
let session = Arc::new(session);
let turn_context = Arc::new(turn_context_raw);
@@ -407,7 +407,7 @@ async fn strict_auto_review_turn_grant_forces_guardian_for_shell_command_policy_
turn_context_raw
.approval_policy
.set(AskForApproval::OnFailure)
.set(AskForApproval::Never)
.expect("test setup should allow updating approval policy");
turn_context_raw.permission_profile = codex_protocol::models::PermissionProfile::Disabled;
let mut config = (*turn_context_raw.config).clone();
+1
View File
@@ -226,6 +226,7 @@ pub(crate) async fn execute_user_shell_command(
arg0: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
};
let stdout_stream = Some(StdoutStream {
+8 -16
View File
@@ -24,7 +24,6 @@ use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_utils_path_uri::PathUri;
pub struct ViewImageHandler {
options: ViewImageToolOptions,
@@ -140,36 +139,31 @@ impl ViewImageHandler {
"view_image is unavailable in this session".to_string(),
));
};
// TODO(anp): Resolve tool paths using the selected environment's native path convention
// so view_image can support relative paths in foreign environments.
let cwd = turn_environment.cwd().to_abs_path().map_err(|err| {
let path_uri = turn_environment.cwd().join(&path).map_err(|err| {
FunctionCallError::RespondToModel(format!(
"environment cwd `{}` is not native to the Codex host: {err}",
turn_environment.cwd()
"unable to resolve image path `{path}` against environment cwd `{}`: {err}",
turn_environment.cwd(),
))
})?;
let abs_path = cwd.join(path);
let model_visible_path = path_uri.inferred_native_path_string();
let sandbox = turn.file_system_sandbox_context(
/*additional_permissions*/ None,
turn_environment.cwd(),
);
let fs = turn_environment.environment.get_filesystem();
let path_uri = PathUri::from_abs_path(&abs_path);
let metadata = fs
.get_metadata(&path_uri, Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to locate image at `{}`: {error}",
abs_path.display()
"unable to locate image at `{model_visible_path}`: {error}"
))
})?;
if !metadata.is_file {
return Err(FunctionCallError::RespondToModel(format!(
"image path `{}` is not a file",
abs_path.display()
"image path `{model_visible_path}` is not a file"
)));
}
let file_bytes = fs
@@ -177,11 +171,9 @@ impl ViewImageHandler {
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to read image at `{}`: {error}",
abs_path.display()
"unable to read image at `{model_visible_path}`: {error}"
))
})?;
let event_path = abs_path.clone();
let can_request_original_detail = can_request_original_image_detail(&turn.model_info);
let use_original_detail =
@@ -197,7 +189,7 @@ impl ViewImageHandler {
let item = TurnItem::ImageView(ImageViewItem {
id: call_id,
path: event_path,
path: path_uri,
});
session.emit_turn_item_started(turn.as_ref(), &item).await;
session.emit_turn_item_completed(turn.as_ref(), item).await;
@@ -250,7 +250,6 @@ fn allow_once_and_allow_for_session_both_allow_network() {
fn only_never_policy_disables_network_approval_flow() {
assert!(!allows_network_approval_flow(AskForApproval::Never));
assert!(allows_network_approval_flow(AskForApproval::OnRequest));
assert!(allows_network_approval_flow(AskForApproval::OnFailure));
assert!(allows_network_approval_flow(AskForApproval::UnlessTrusted));
}
@@ -205,7 +205,6 @@ impl Approvable<ApplyPatchRequest> for ApplyPatchRuntime {
match policy {
AskForApproval::Never => false,
AskForApproval::Granular(granular_config) => granular_config.allows_sandbox_approval(),
AskForApproval::OnFailure => true,
AskForApproval::OnRequest => true,
AskForApproval::UnlessTrusted => true,
}
+16 -15
View File
@@ -50,6 +50,7 @@ pub(crate) fn build_sandbox_command(
args: args.to_vec(),
cwd,
env: env.clone(),
managed_network: None,
additional_permissions,
})
}
@@ -67,26 +68,26 @@ pub(crate) fn exec_env_for_sandbox_permissions(
env
}
pub(crate) fn strip_managed_proxy_env(env: &mut HashMap<String, String>) {
for key in PROXY_ENV_KEYS {
env.remove(*key);
pub(crate) fn is_managed_proxy_env_var(key: &str, value: &str) -> bool {
if PROXY_ENV_KEYS.contains(&key) {
return true;
}
for key in CUSTOM_CA_ENV_KEYS {
if env
.get(key)
.is_some_and(|value| is_managed_mitm_ca_trust_bundle_path(value))
{
env.remove(key);
}
if CUSTOM_CA_ENV_KEYS.contains(&key) {
return is_managed_mitm_ca_trust_bundle_path(value);
}
// Only macOS injects a Codex-owned SSH wrapper for the managed SOCKS proxy.
#[cfg(target_os = "macos")]
if env
.get(PROXY_GIT_SSH_COMMAND_ENV_KEY)
.is_some_and(|command| command.starts_with(CODEX_PROXY_GIT_SSH_COMMAND_MARKER))
{
env.remove(PROXY_GIT_SSH_COMMAND_ENV_KEY);
key == PROXY_GIT_SSH_COMMAND_ENV_KEY
&& value.starts_with(CODEX_PROXY_GIT_SSH_COMMAND_MARKER)
}
#[cfg(not(target_os = "macos"))]
{
false
}
}
pub(crate) fn strip_managed_proxy_env(env: &mut HashMap<String, String>) {
env.retain(|key, value| !is_managed_proxy_env_var(key, value));
}
/// Prepends `path_entry` to `PATH`, removing duplicate and empty existing
@@ -168,6 +168,7 @@ pub(super) async fn try_run_zsh_fork(
arg0,
exec_server_sandbox: _,
exec_server_enforce_managed_network: _,
exec_server_managed_network: _,
} = sandbox_exec_request;
let ParsedShellCommand { script, login, .. } = extract_shell_script(&command)?;
let effective_timeout = Duration::from_millis(
@@ -902,6 +903,7 @@ impl CoreShellCommandExecutor {
arg0: self.arg0.clone(),
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_managed_network: None,
},
/*stdout_stream*/ None,
after_spawn,
@@ -1010,6 +1012,7 @@ impl CoreShellCommandExecutor {
args: args.to_vec(),
cwd,
env,
managed_network: None,
additional_permissions,
};
let options = ExecOptions {
@@ -41,6 +41,7 @@ use crate::unified_exec::NoopSpawnLifecycle;
use crate::unified_exec::UnifiedExecError;
use crate::unified_exec::UnifiedExecProcess;
use crate::unified_exec::UnifiedExecProcessManager;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_protocol::error::CodexErr;
use codex_protocol::error::SandboxErr;
@@ -117,6 +118,7 @@ fn build_unified_exec_sandbox_command(
command: &[String],
cwd: &PathUri,
env: &HashMap<String, String>,
managed_network: Option<ManagedNetworkSandboxContext>,
additional_permissions: Option<AdditionalPermissionProfile>,
) -> Result<SandboxCommand, ToolError> {
let (program, args) = command
@@ -127,6 +129,7 @@ fn build_unified_exec_sandbox_command(
args: args.to_vec(),
cwd: cwd.clone(),
env: env.clone(),
managed_network,
additional_permissions,
})
}
@@ -321,22 +324,28 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
req.network.as_ref(),
launch_sandbox_permissions,
);
let mut env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions);
if let Some(network) = managed_network {
network
.apply_to_env_for_optional_environment(
&mut env,
Some(&req.turn_environment.environment_id),
)
.map_err(|err| {
ToolError::Codex(CodexErr::Io(io::Error::other(format!(
"failed to prepare network proxy for environment `{}`: {err}",
req.turn_environment.environment_id
))))
})?;
}
let env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions);
let (env, managed_network_context) = match managed_network {
Some(network) => {
let prepared = network
.prepare_for_optional_environment(
env,
Some(&req.turn_environment.environment_id),
)
.map_err(|err| {
ToolError::Codex(CodexErr::Io(io::Error::other(format!(
"failed to prepare network proxy for environment `{}`: {err}",
req.turn_environment.environment_id
))))
})?;
(prepared.env, Some(prepared.sandbox_context))
}
None => (env, None),
};
let explicit_env_overrides = req.explicit_env_overrides.clone();
#[cfg(unix)]
let mut env = env;
#[cfg(unix)]
let runtime_path_prepends = {
let mut runtime_path_prepends = RuntimePathPrepends::default();
if !environment_is_remote {
@@ -385,6 +394,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
&command,
&req.cwd,
&env,
managed_network_context.clone(),
req.additional_permissions.clone(),
)
.map_err(|error| match error {
@@ -450,6 +460,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
&command,
&req.cwd,
&env,
managed_network_context,
req.additional_permissions.clone(),
)
.map_err(|error| match error {
+4 -3
View File
@@ -196,7 +196,7 @@ impl ExecApprovalRequirement {
}
}
/// - Never, OnFailure: do not ask
/// - Never: do not ask
/// - OnRequest: ask unless filesystem access is unrestricted
/// - Granular: ask unless filesystem access is unrestricted, but auto-reject
/// when granular sandbox approval is disabled.
@@ -206,7 +206,7 @@ pub(crate) fn default_exec_approval_requirement(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
) -> ExecApprovalRequirement {
let needs_approval = match policy {
AskForApproval::Never | AskForApproval::OnFailure => false,
AskForApproval::Never => false,
AskForApproval::OnRequest | AskForApproval::Granular(_) => {
matches!(
file_system_sandbox_policy.kind,
@@ -356,7 +356,6 @@ pub(crate) trait Approvable<Req> {
/// Decide we can request an approval for no-sandbox execution.
fn wants_no_sandbox_approval(&self, policy: AskForApproval) -> bool {
match policy {
AskForApproval::OnFailure => true,
AskForApproval::UnlessTrusted => true,
AskForApproval::Never => false,
AskForApproval::OnRequest => false,
@@ -466,6 +465,7 @@ impl<'a> SandboxAttempt<'a> {
network: Option<&NetworkProxy>,
environment_id: Option<&str>,
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
let managed_network = command.managed_network.clone();
let exec_server_permissions = effective_permission_profile(
self.exec_server_permissions,
command.additional_permissions.as_ref(),
@@ -492,6 +492,7 @@ impl<'a> SandboxAttempt<'a> {
options,
self.workspace_roots.to_vec(),
);
exec_request.exec_server_managed_network = managed_network;
if self.sandbox_requested {
exec_request.exec_server_sandbox = Some(FileSystemSandboxContext {
permissions: exec_server_permissions.into(),
+25 -7
View File
@@ -1,6 +1,7 @@
use super::*;
use crate::sandboxing::SandboxPermissions;
use crate::tools::hook_names::HookToolName;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
@@ -212,7 +213,7 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
.clone()
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(&cwd));
let manager = SandboxManager::new();
let attempt = SandboxAttempt {
let mut attempt = SandboxAttempt {
sandbox: SandboxType::None,
sandbox_requested: true,
permissions: &permissions,
@@ -227,20 +228,24 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
windows_sandbox_private_desktop: false,
network_denial_cancellation_token: None,
};
let command = SandboxCommand {
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
allow_local_binding: false,
};
let command = || SandboxCommand {
program: "/bin/bash".into(),
args: vec!["-lc".to_string(), "pwd".to_string()],
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: Some(managed_network.clone()),
additional_permissions: None,
};
let options = crate::sandboxing::ExecOptions {
let options = || crate::sandboxing::ExecOptions {
expiration: crate::exec::ExecExpiration::DefaultTimeout,
capture_policy: crate::exec::ExecCapturePolicy::ShellTool,
};
let request = attempt
.env_for_exec_server(command, options, /*network*/ None, Some("remote"))
.env_for_exec_server(command(), options(), /*network*/ None, Some("remote"))
.expect("prepare remote exec request");
assert_eq!(
@@ -256,8 +261,8 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
assert_eq!(
request.exec_server_sandbox,
Some(codex_exec_server::FileSystemSandboxContext {
permissions: exec_server_permissions.into(),
cwd: Some(cwd_uri),
permissions: exec_server_permissions.clone().into(),
cwd: Some(cwd_uri.clone()),
workspace_roots: Vec::new(),
windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -265,4 +270,17 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
})
);
assert!(request.exec_server_enforce_managed_network);
assert_eq!(
request.exec_server_managed_network,
Some(managed_network.clone())
);
attempt.sandbox_requested = false;
let request = attempt
.env_for_exec_server(command(), options(), /*network*/ None, Some("remote"))
.expect("prepare unsandboxed remote exec request");
assert_eq!(request.exec_server_sandbox, None);
assert!(!request.exec_server_enforce_managed_network);
assert_eq!(request.exec_server_managed_network, Some(managed_network));
}
+17 -4
View File
@@ -96,6 +96,7 @@ use tracing::warn;
const MULTI_AGENT_V2_NAMESPACE_DESCRIPTION: &str = "Tools for spawning and managing sub-agents.";
const IMAGE_GEN_NAMESPACE: &str = "image_gen";
const IMAGEGEN_TOOL_NAME: &str = "imagegen";
const ACTOR_AUTHORIZATION_HEADER: &str = "x-openai-actor-authorization";
type PlannedRuntime = Arc<dyn CoreToolRuntime>;
@@ -383,10 +384,12 @@ fn image_generation_tool_enabled(turn_context: &TurnContext) -> bool {
}
fn image_generation_runtime_enabled(turn_context: &TurnContext) -> bool {
turn_context
.auth_manager
.as_deref()
.is_some_and(AuthManager::current_auth_uses_codex_backend)
(provider_uses_actor_authorization(turn_context)
|| (turn_context.provider.info().requires_openai_auth
&& turn_context
.auth_manager
.as_deref()
.is_some_and(AuthManager::current_auth_uses_codex_backend)))
&& turn_context.provider.capabilities().image_generation
&& turn_context
.model_info
@@ -394,6 +397,16 @@ fn image_generation_runtime_enabled(turn_context: &TurnContext) -> bool {
.contains(&InputModality::Image)
}
fn provider_uses_actor_authorization(turn_context: &TurnContext) -> bool {
let provider_info = turn_context.provider.info();
!provider_info.requires_openai_auth
&& provider_info.http_headers.as_ref().is_some_and(|headers| {
headers.iter().any(|(name, value)| {
name.eq_ignore_ascii_case(ACTOR_AUTHORIZATION_HEADER) && !value.trim().is_empty()
})
})
}
fn standalone_image_generation_model_visible(turn_context: &TurnContext) -> bool {
if !image_generation_runtime_enabled(turn_context) || !namespace_tools_enabled(turn_context) {
return false;
+128
View File
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::Arc;
use codex_features::Feature;
@@ -270,6 +271,29 @@ fn use_bedrock_provider(turn: &mut TurnContext) {
turn.provider = create_model_provider(provider_info, turn.auth_manager.clone());
}
fn use_provider_auth(
turn: &mut TurnContext,
requires_openai_auth: bool,
actor_header: Option<(&str, &str)>,
) {
let mut provider_info = turn.config.model_provider.clone();
provider_info.requires_openai_auth = requires_openai_auth;
provider_info.http_headers = actor_header.map(|(name, value)| {
HashMap::from([
(name.to_string(), value.to_string()),
(
"ChatGPT-Account-ID".to_string(),
"test-account-id".to_string(),
),
])
});
turn.auth_manager = None;
update_config(turn, |config| {
config.model_provider = provider_info.clone();
});
turn.provider = create_model_provider(provider_info, /*auth_manager*/ None);
}
struct WebRunExtensionTool;
impl ToolExecutor<ExtensionToolCall> for WebRunExtensionTool {
@@ -1455,6 +1479,110 @@ async fn hosted_tools_follow_provider_auth_model_and_config_gates() {
.await;
api_key_auth.assert_visible_lacks(&["image_generation"]);
let unrelated_chatgpt_auth = probe(|turn| {
use_chatgpt_auth(turn);
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
let mut provider_info = turn.provider.info().clone();
provider_info.requires_openai_auth = false;
provider_info.http_headers = None;
update_config(turn, |config| {
config.model_provider = provider_info.clone();
});
turn.provider = create_model_provider(provider_info, turn.auth_manager.clone());
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
unrelated_chatgpt_auth.assert_visible_lacks(&["image_generation"]);
let provider_without_actor_auth = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_provider_auth(
turn, /*requires_openai_auth*/ false, /*actor_header*/ None,
);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
provider_without_actor_auth.assert_visible_lacks(&["image_generation"]);
let provider_authenticated = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_provider_auth(
turn,
/*requires_openai_auth*/ false,
Some(("X-OpenAI-Actor-Authorization", "test-actor-authorization")),
);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
provider_authenticated.assert_visible_contains(&["image_generation"]);
let empty_actor_auth = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_provider_auth(
turn,
/*requires_openai_auth*/ false,
Some(("x-openai-actor-authorization", " ")),
);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
empty_actor_auth.assert_visible_lacks(&["image_generation"]);
let feature_disabled = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ false);
use_provider_auth(
turn,
/*requires_openai_auth*/ false,
Some(("x-openai-actor-authorization", "test-actor-authorization")),
);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
feature_disabled.assert_visible_lacks(&["image_generation"]);
let text_only_model = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_provider_auth(
turn,
/*requires_openai_auth*/ false,
Some(("x-openai-actor-authorization", "test-actor-authorization")),
);
turn.model_info.input_modalities = vec![];
})
.await;
text_only_model.assert_visible_lacks(&["image_generation"]);
let unsupported_image_generation_provider = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_bedrock_provider(turn);
let mut provider_info = turn.provider.info().clone();
provider_info.requires_openai_auth = false;
provider_info.http_headers = Some(HashMap::from([(
"x-openai-actor-authorization".to_string(),
"test-actor-authorization".to_string(),
)]));
turn.auth_manager = None;
update_config(turn, |config| {
config.model_provider = provider_info.clone();
});
turn.provider = create_model_provider(provider_info, /*auth_manager*/ None);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
unsupported_image_generation_provider.assert_visible_lacks(&["image_generation"]);
let codex_managed_auth_provider = probe(|turn| {
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
use_provider_auth(
turn,
/*requires_openai_auth*/ true,
Some(("x-openai-actor-authorization", "test-actor-authorization")),
);
turn.model_info.input_modalities = vec![InputModality::Image];
})
.await;
codex_managed_auth_provider.assert_visible_lacks(&["image_generation"]);
let image_generation = probe(|turn| {
use_chatgpt_auth(turn);
set_feature(turn, Feature::ImageGeneration, /*enabled*/ true);
@@ -26,6 +26,7 @@ use crate::tools::events::ToolEventStage;
use crate::tools::network_approval::DeferredNetworkApproval;
use crate::tools::network_approval::finish_deferred_network_approval;
use crate::tools::orchestrator::ToolOrchestrator;
use crate::tools::runtimes::is_managed_proxy_env_var;
use crate::tools::runtimes::unified_exec::UnifiedExecRequest as UnifiedExecToolRequest;
use crate::tools::runtimes::unified_exec::UnifiedExecRuntime;
use crate::tools::sandboxing::SandboxAttempt;
@@ -143,10 +144,16 @@ fn exec_server_env_for_request(
HashMap<String, String>,
) {
if let Some(exec_server_env_config) = &request.exec_server_env_config {
(
Some(exec_server_env_config.policy.clone()),
env_overlay_for_exec_server(&request.env, &exec_server_env_config.local_policy_env),
)
let mut env =
env_overlay_for_exec_server(&request.env, &exec_server_env_config.local_policy_env);
if request.exec_server_managed_network.is_some() {
for (key, value) in &request.env {
if is_managed_proxy_env_var(key, value) {
env.insert(key.clone(), value.clone());
}
}
}
(Some(exec_server_env_config.policy.clone()), env)
} else {
(None, request.env.clone())
}
@@ -175,6 +182,7 @@ fn exec_server_params_for_request(
arg0: request.arg0.clone(),
sandbox: request.exec_server_sandbox.clone(),
enforce_managed_network: request.exec_server_enforce_managed_network,
managed_network: request.exec_server_managed_network.clone(),
}
}
@@ -1,5 +1,6 @@
use super::*;
use crate::unified_exec::clamp_yield_time;
use codex_network_proxy::ManagedNetworkSandboxContext;
use pretty_assertions::assert_eq;
use tokio::time::Duration;
use tokio::time::Instant;
@@ -76,6 +77,10 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
codex_protocol::permissions::FileSystemSandboxPolicy::unrestricted();
let network_sandbox_policy = codex_protocol::permissions::NetworkSandboxPolicy::Restricted;
let permission_profile = codex_protocol::models::PermissionProfile::Disabled;
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![43123],
allow_local_binding: false,
};
let mut request = ExecRequest {
command: vec!["bash".to_string(), "-lc".to_string(), "true".to_string()],
cwd: cwd.clone().into(),
@@ -83,6 +88,15 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/sandbox-path".to_string()),
("CODEX_THREAD_ID".to_string(), "thread-1".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("CODEX_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
exec_server_env_config: Some(ExecServerEnvConfig {
policy: codex_exec_server::ExecEnvPolicy {
@@ -95,6 +109,15 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
local_policy_env: HashMap::from([
("HOME".to_string(), "/client-home".to_string()),
("PATH".to_string(), "/client-path".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("CODEX_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string()),
(
"SSL_CERT_FILE".to_string(),
"/client/custom-ca.pem".to_string(),
),
]),
}),
network: None,
@@ -112,7 +135,8 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
windows_sandbox_filesystem_overrides: None,
arg0: None,
exec_server_sandbox: None,
exec_server_enforce_managed_network: false,
exec_server_enforce_managed_network: true,
exec_server_managed_network: Some(managed_network.clone()),
};
let params =
@@ -120,12 +144,19 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
assert_eq!(params.process_id.as_str(), "123");
assert_eq!(params.cwd, request.cwd);
assert!(params.enforce_managed_network);
assert_eq!(params.managed_network, Some(managed_network));
assert!(params.env_policy.is_some());
assert_eq!(
params.env,
HashMap::from([
("PATH".to_string(), "/sandbox-path".to_string()),
("CODEX_THREAD_ID".to_string(), "thread-1".to_string()),
(
"HTTP_PROXY".to_string(),
"http://127.0.0.1:43123".to_string(),
),
("CODEX_NETWORK_PROXY_ACTIVE".to_string(), "1".to_string(),),
])
);
request.exec_server_sandbox = Some(
+2 -99
View File
@@ -1085,40 +1085,6 @@ fn scenarios() -> Vec<ScenarioSpec> {
output_contains: "rejected by user",
},
},
ScenarioSpec {
name: "danger_full_access_on_failure_allows_outside_write",
approval_policy: OnFailure,
sandbox_policy: SandboxPolicy::DangerFullAccess,
action: ActionKind::WriteFile {
target: TargetPath::OutsideWorkspace("dfa_on_failure.txt"),
content: "danger-on-failure",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.2"),
outcome: Outcome::Auto,
expectation: Expectation::FileCreated {
target: TargetPath::OutsideWorkspace("dfa_on_failure.txt"),
content: "danger-on-failure",
},
},
ScenarioSpec {
name: "danger_full_access_on_failure_allows_outside_write_gpt_5_1_no_exit",
approval_policy: OnFailure,
sandbox_policy: SandboxPolicy::DangerFullAccess,
action: ActionKind::WriteFile {
target: TargetPath::OutsideWorkspace("dfa_on_failure_5_1.txt"),
content: "danger-on-failure",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.4"),
outcome: Outcome::Auto,
expectation: Expectation::FileCreatedNoExitCode {
target: TargetPath::OutsideWorkspace("dfa_on_failure_5_1.txt"),
content: "danger-on-failure",
},
},
ScenarioSpec {
name: "danger_full_access_unless_trusted_requests_approval",
approval_policy: UnlessTrusted,
@@ -1297,48 +1263,6 @@ fn scenarios() -> Vec<ScenarioSpec> {
message_contains: &["exec command rejected by user"],
},
},
#[cfg(not(target_os = "linux"))] // TODO (pakrym): figure out why linux behaves differently
ScenarioSpec {
name: "read_only_on_failure_escalates_after_sandbox_error",
approval_policy: OnFailure,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
action: ActionKind::WriteFile {
target: TargetPath::Workspace("ro_on_failure.txt"),
content: "read-only-on-failure",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.2"),
outcome: Outcome::ExecApproval {
decision: ReviewDecision::Approved,
expected_reason: Some("command failed; retry without sandbox?"),
},
expectation: Expectation::FileCreated {
target: TargetPath::Workspace("ro_on_failure.txt"),
content: "read-only-on-failure",
},
},
#[cfg(not(target_os = "linux"))]
ScenarioSpec {
name: "read_only_on_failure_escalates_after_sandbox_error_gpt_5_1_no_exit",
approval_policy: OnFailure,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
action: ActionKind::WriteFile {
target: TargetPath::Workspace("ro_on_failure_5_1.txt"),
content: "read-only-on-failure",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.4"),
outcome: Outcome::ExecApproval {
decision: ReviewDecision::Approved,
expected_reason: Some("command failed; retry without sandbox?"),
},
expectation: Expectation::FileCreatedNoExitCode {
target: TargetPath::Workspace("ro_on_failure_5_1.txt"),
content: "read-only-on-failure",
},
},
ScenarioSpec {
name: "read_only_on_request_network_escalates_when_approved",
approval_policy: OnRequest,
@@ -1676,27 +1600,6 @@ fn scenarios() -> Vec<ScenarioSpec> {
body_contains: "workspace-network-ok",
},
},
#[cfg(not(target_os = "linux"))] // TODO (pakrym): figure out why linux behaves differently
ScenarioSpec {
name: "workspace_write_on_failure_escalates_outside_workspace",
approval_policy: OnFailure,
sandbox_policy: workspace_write(false),
action: ActionKind::WriteFile {
target: TargetPath::OutsideWorkspace("ww_on_failure.txt"),
content: "workspace-on-failure",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.2"),
outcome: Outcome::ExecApproval {
decision: ReviewDecision::Approved,
expected_reason: Some("command failed; retry without sandbox?"),
},
expectation: Expectation::FileCreated {
target: TargetPath::OutsideWorkspace("ww_on_failure.txt"),
content: "workspace-on-failure",
},
},
ScenarioSpec {
name: "workspace_write_unless_trusted_requires_approval_outside_workspace",
approval_policy: UnlessTrusted,
@@ -2982,7 +2885,7 @@ mode = "limited"
allow_local_binding = true
"#,
)?;
let approval_policy = AskForApproval::OnFailure;
let approval_policy = AskForApproval::OnRequest;
let sandbox_policy = SandboxPolicy::WorkspaceWrite {
writable_roots: vec![],
network_access: true,
@@ -3467,7 +3370,7 @@ mode = "limited"
allow_local_binding = true
"#,
)?;
let approval_policy = AskForApproval::OnFailure;
let approval_policy = AskForApproval::OnRequest;
let turn_sandbox_policy = SandboxPolicy::WorkspaceWrite {
writable_roots: vec![],
network_access: true,
+1 -66
View File
@@ -2200,7 +2200,7 @@ allow_local_binding = true
)
.await;
let approval_policy = AskForApproval::OnFailure;
let approval_policy = AskForApproval::OnRequest;
let permission_profile = network_workspace_write_profile();
let permission_profile_for_config = permission_profile.clone();
let test = test_codex()
@@ -2283,71 +2283,6 @@ allow_local_binding = true
Ok(())
}
#[cfg(not(target_os = "linux"))]
#[tokio::test]
async fn permission_request_hook_sees_retry_context_after_sandbox_denial() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let call_id = "permissionrequest-retry-shell-command";
let marker = "permissionrequest_retry_marker.txt";
let command = format!("printf retry > {marker}");
let args = serde_json::json!({ "command": command });
let responses = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
core_test_support::responses::ev_function_call(
call_id,
"shell_command",
&serde_json::to_string(&args)?,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "permission request hook allowed retry"),
ev_completed("resp-2"),
]),
],
)
.await;
let mut builder = test_codex()
.with_pre_build_hook(|home| {
install_allow_permission_request_hook(home)
.expect("failed to write permission request hook test fixture");
})
.with_config(trust_discovered_hooks);
let test = builder.build(&server).await?;
let marker_path = test.workspace_path(marker);
let _ = fs::remove_file(&marker_path);
test.submit_turn_with_approval_and_permission_profile(
"retry the shell command after sandbox denial",
AskForApproval::OnFailure,
PermissionProfile::read_only(),
)
.await?;
let requests = responses.requests();
assert_eq!(requests.len(), 2);
requests[1].function_call_output(call_id);
assert_eq!(
fs::read_to_string(&marker_path).context("read retry marker")?,
"retry"
);
assert_single_permission_request_hook_input(
test.codex_home_path(),
&command,
/*description*/ None,
)?;
Ok(())
}
#[tokio::test]
async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -165,7 +165,7 @@ mode = "limited"
allow_local_binding = true
"#,
)?;
let approval_policy = AskForApproval::OnFailure;
let approval_policy = AskForApproval::OnRequest;
let permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Enabled,
@@ -263,7 +263,7 @@ async fn submit_managed_network_turn(
additional_context: Default::default(),
thread_settings: codex_protocol::protocol::ThreadSettingsOverrides {
environments: Some(turn_environment_selections),
approval_policy: Some(AskForApproval::OnFailure),
approval_policy: Some(AskForApproval::OnRequest),
approvals_reviewer: Some(ApprovalsReviewer::User),
sandbox_policy: Some(sandbox_policy),
permission_profile,
-145
View File
@@ -315,151 +315,6 @@ async fn explicit_remote_shell_runs_in_remote_cwd() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_sandbox_denial_requests_approval_and_retries() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_wine_exec!(Ok(()), "requires the Docker-backed POSIX executor");
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
const CALL_ID: &str = "remote-sandbox-denial";
const CONTENTS: &str = "remote sandbox retry succeeded";
let server = start_mock_server().await;
let test = unified_exec_test(&server).await?;
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
let remote_cwd = PathBuf::from(format!("/tmp/codex-remote-denial-cwd-{nonce}")).abs();
let target_path = PathBuf::from(format!("/tmp/codex-remote-denial-target-{nonce}")).abs();
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
let target_uri = PathUri::from_host_native_path(&target_path)?;
test.fs()
.create_directory(
&remote_cwd_uri,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
test.fs()
.remove(
&target_uri,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
let command = format!("printf {CONTENTS:?} > {target_path:?} && cat {target_path:?}");
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-remote-denial-1"),
ev_function_call(
CALL_ID,
"exec_command",
&json!({
"shell": "/bin/sh",
"cmd": command,
"login": false,
"yield_time_ms": 5_000,
"environment_id": REMOTE_ENVIRONMENT_ID,
})
.to_string(),
),
ev_completed("resp-remote-denial-1"),
]),
sse(vec![
ev_response_created("resp-remote-denial-2"),
ev_assistant_message("msg-remote-denial", "done"),
ev_completed("resp-remote-denial-2"),
]),
],
)
.await;
submit_turn_with_approval_and_environments(
&test,
"retry a sandbox-denied command in the remote environment",
vec![TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&remote_cwd),
}],
AskForApproval::OnFailure,
)
.await?;
let event = wait_for_event(&test.codex, |event| {
matches!(
event,
EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_)
)
})
.await;
let EventMsg::ExecApprovalRequest(approval) = event else {
panic!("expected remote sandbox approval before completion: {event:?}");
};
assert_eq!(approval.call_id, CALL_ID);
assert_eq!(
approval.environment_id.as_deref(),
Some(REMOTE_ENVIRONMENT_ID)
);
assert_eq!(
approval.reason.as_deref(),
Some("command failed; retry without sandbox?")
);
test.codex
.submit(Op::ExecApproval {
id: approval.effective_approval_id(),
turn_id: None,
decision: ReviewDecision::Approved,
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert!(
response_mock
.function_call_output_text(CALL_ID)
.is_some_and(|output| output.contains(CONTENTS)),
"approved retry should return the remote command output"
);
assert_eq!(
test.fs()
.read_file_text(&target_uri, /*sandbox*/ None)
.await?,
CONTENTS
);
test.fs()
.remove(
&target_uri,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
test.fs()
.remove(
&remote_cwd_uri,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_executor_does_not_duplicate_initial_environment_context() -> Result<()> {
let server = start_mock_server().await;
+60 -51
View File
@@ -29,7 +29,6 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::user_input::UserInput;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::get_remote_test_env;
use core_test_support::responses;
@@ -42,7 +41,6 @@ use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_wine_exec;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::local;
use core_test_support::test_codex::test_codex;
@@ -59,8 +57,6 @@ use serde_json::json;
use std::fs;
use std::io::Cursor;
use std::path::PathBuf;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
use tokio::time::Duration;
use wiremock::BodyPrintLimit;
@@ -295,6 +291,7 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> {
let rel_path = "assets/example.png";
let abs_path = cwd.join(rel_path);
let path_uri = PathUri::from_abs_path(&abs_path);
let original_width = 2304;
let original_height = 864;
write_workspace_png(
@@ -369,20 +366,20 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> {
match item_started.expect("view image item started event emitted") {
codex_protocol::items::TurnItem::ImageView(item) => {
assert_eq!(item.id, call_id);
assert_eq!(item.path, abs_path);
assert_eq!(item.path, path_uri);
}
other => panic!("expected ImageView item, got {other:?}"),
}
match item_completed.expect("view image item completed event emitted") {
codex_protocol::items::TurnItem::ImageView(item) => {
assert_eq!(item.id, call_id);
assert_eq!(item.path, abs_path);
assert_eq!(item.path, path_uri);
}
other => panic!("expected ImageView item, got {other:?}"),
}
let legacy_event = legacy_event.expect("legacy view image event emitted");
assert_eq!(legacy_event.call_id, call_id);
assert_eq!(legacy_event.path, abs_path);
assert_eq!(legacy_event.path, path_uri);
let req = mock.single_request();
let body = req.body_json();
@@ -557,8 +554,10 @@ async fn view_image_tool_applies_local_sandbox_read_denies() -> anyhow::Result<(
.function_call_output_content_and_success(call_id)
.and_then(|(content, _)| content)
.context("sandboxed view_image error text present")?;
let expected_locate_prefix = format!("unable to locate image at `{}`:", denied_path.display());
let expected_read_prefix = format!("unable to read image at `{}`:", denied_path.display());
let denied_path_display =
PathUri::from_host_native_path(&denied_path)?.inferred_native_path_string();
let expected_locate_prefix = format!("unable to locate image at `{denied_path_display}`:");
let expected_read_prefix = format!("unable to read image at `{denied_path_display}`:");
assert!(
output_text.starts_with(&expected_locate_prefix)
|| output_text.starts_with(&expected_read_prefix),
@@ -570,8 +569,6 @@ async fn view_image_tool_applies_local_sandbox_read_denies() -> anyhow::Result<(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()> {
// TODO(anp): Remove after remote-cwd fixtures use target-native paths.
skip_if_wine_exec!(Ok(()), "hardcodes a POSIX remote cwd");
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
@@ -583,37 +580,26 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
let local_cwd = TempDir::new()?;
fs::write(local_cwd.path().join("remote.png"), b"not a remote image")?;
let local_selection = local(local_cwd.path().abs());
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-view-image-routing-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let image_path = remote_cwd.join("remote.png");
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let remote_cwd_uri = PathUri::from_abs_path(test.executor_environment().cwd());
let image_path_uri = remote_cwd_uri.join("remote.png")?;
let png = png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?;
let image_path_uri = PathUri::from_host_native_path(&image_path)?;
test.fs()
.write_file(&image_path_uri, png, /*sandbox*/ None)
.await?;
let absolute_image_path = image_path_uri.inferred_native_path_string();
let remote_selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&remote_cwd),
cwd: remote_cwd_uri,
};
let call_id = "call-view-image-multi-env";
let relative_call_id = "call-view-image-relative-multi-env";
let absolute_call_id = "call-view-image-absolute-multi-env";
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
call_id,
relative_call_id,
"view_image",
&json!({
"path": "remote.png",
@@ -625,9 +611,22 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_function_call(
absolute_call_id,
"view_image",
&json!({
"path": absolute_image_path,
"environment_id": REMOTE_ENVIRONMENT_ID,
})
.to_string(),
),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-3"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-3"),
]),
],
)
.await;
@@ -638,30 +637,32 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
)
.await?;
let output = response_mock
let request = response_mock
.last_request()
.context("missing request containing view_image output")?
.function_call_output(call_id)
.clone();
let output_items = output
.get("output")
.and_then(Value::as_array)
.context("view_image output should be content items")?;
assert_eq!(output_items.len(), 1);
let image_url = output_items[0]
.get("image_url")
.and_then(Value::as_str)
.context("view_image output should include image_url")?;
assert!(
image_url.starts_with("data:image/png;base64,"),
"unexpected image_url: {image_url}",
);
for call_id in [relative_call_id, absolute_call_id] {
let output = request.function_call_output(call_id);
let output_items = output
.get("output")
.and_then(Value::as_array)
.context("view_image output should be content items")?;
assert_eq!(output_items.len(), 1);
let image_url = output_items[0]
.get("image_url")
.and_then(Value::as_str)
.context("view_image output should include image_url")?;
assert!(
image_url.starts_with("data:image/png;base64,"),
"unexpected image_url: {image_url}",
);
}
test.fs()
.remove(
&remote_cwd_uri,
&image_path_uri,
RemoveOptions {
recursive: true,
recursive: false,
force: true,
},
/*sandbox*/ None,
@@ -1174,7 +1175,8 @@ async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> {
.function_call_output_content_and_success(call_id)
.and_then(|(content, _)| content)
.expect("output text present");
let expected_message = format!("image path `{}` is not a file", abs_path.display());
let expected_path = PathUri::from_host_native_path(&abs_path)?.inferred_native_path_string();
let expected_message = format!("image path `{expected_path}` is not a file");
assert_eq!(output_text, expected_message);
assert!(
@@ -1253,19 +1255,26 @@ async fn view_image_tool_turns_invalid_image_into_placeholder() -> anyhow::Resul
async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let remote_test_env = get_remote_test_env();
println!("view_image missing-file test exec-server environment: {remote_test_env:?}");
let server = start_mock_server().await;
let mut builder = test_codex();
let test = builder.build_with_remote_env(&server).await?;
let TestCodex {
codex,
config,
session_configured,
..
} = &test;
let rel_path = "missing/example.png";
let abs_path = config.cwd.join(rel_path);
// Under wine-exec, the executor cwd is stored as a host-compatible `/C:/...`
// projection. Reconstruct its `PathUri` so the expected error uses the selected
// environment's native Windows spelling, matching the handler.
let expected_path = PathUri::from_abs_path(test.executor_environment().cwd())
.join(rel_path)?
.inferred_native_path_string();
let call_id = "view-image-missing";
let arguments = serde_json::json!({ "path": rel_path }).to_string();
@@ -1309,7 +1318,7 @@ async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> {
.function_call_output_content_and_success(call_id)
.and_then(|(content, _)| content)
.expect("output text present");
let expected_prefix = format!("unable to locate image at `{}`:", abs_path.display());
let expected_prefix = format!("unable to locate image at `{expected_path}`:");
assert!(
output_text.starts_with(&expected_prefix),
"expected error to start with `{expected_prefix}` but got `{output_text}`"

Some files were not shown because too many files have changed in this diff Show More