Merge branch 'main' into codex/viyatb/hooks-trust-precedence

This commit is contained in:
viyatb-oai
2026-04-20 11:09:50 -07:00
committed by GitHub
320 changed files with 17103 additions and 4239 deletions
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
)
url="${base_url%/}/models?client_version=${client_version}"
curl --http1.1 --fail --show-error --location "${headers[@]}" "${url}" | jq '.' > codex-rs/core/models.json
curl --http1.1 --fail --show-error --location "${headers[@]}" "${url}" | jq '.' > codex-rs/models-manager/models.json
- name: Open pull request (if changed)
uses: peter-evans/create-pull-request@c0f553fe549906ede9cf27b5156039d195d2ece0 # v8
+10
View File
@@ -1699,6 +1699,7 @@ dependencies = [
"codex-mcp",
"codex-mcp-server",
"codex-model-provider",
"codex-models-manager",
"codex-protocol",
"codex-responses-api-proxy",
"codex-rmcp-client",
@@ -2384,6 +2385,8 @@ dependencies = [
"codex-terminal-detection",
"codex-utils-template",
"core_test_support",
"crypto_box",
"ed25519-dalek",
"keyring",
"once_cell",
"os_info",
@@ -2414,6 +2417,7 @@ dependencies = [
"async-channel",
"codex-async-utils",
"codex-config",
"codex-exec-server",
"codex-login",
"codex-otel",
"codex-plugin",
@@ -2715,6 +2719,7 @@ dependencies = [
"axum",
"codex-client",
"codex-config",
"codex-exec-server",
"codex-keyring-store",
"codex-protocol",
"codex-utils-cargo-bin",
@@ -2968,6 +2973,7 @@ dependencies = [
"codex-cloud-requirements",
"codex-config",
"codex-connectors",
"codex-core-skills",
"codex-exec-server",
"codex-features",
"codex-feedback",
@@ -2979,6 +2985,7 @@ dependencies = [
"codex-model-provider-info",
"codex-models-manager",
"codex-otel",
"codex-plugin",
"codex-protocol",
"codex-realtime-webrtc",
"codex-rollout",
@@ -2992,6 +2999,8 @@ dependencies = [
"codex-utils-elapsed",
"codex-utils-fuzzy-match",
"codex-utils-oss",
"codex-utils-path",
"codex-utils-plugins",
"codex-utils-pty",
"codex-utils-sandbox-summary",
"codex-utils-sleep-inhibitor",
@@ -3278,6 +3287,7 @@ dependencies = [
"codex-utils-string",
"dirs-next",
"dunce",
"glob",
"pretty_assertions",
"rand 0.8.5",
"serde",
+7
View File
@@ -242,6 +242,7 @@ env_logger = "0.11.9"
eventsource-stream = "0.2.3"
futures = { version = "0.3", default-features = false }
gethostname = "1.1.0"
glob = "0.3"
globset = "0.4"
hmac = "0.12.1"
http = "1.3.1"
@@ -424,6 +425,12 @@ ignored = [
"codex-v8-poc",
]
[profile.dev-small]
inherits = "dev"
opt-level = 0
debug = 0
strip = true
[profile.release]
lto = "fat"
split-debuginfo = "off"
+13 -9
View File
@@ -297,7 +297,7 @@ impl AnalyticsEventsClient {
}
async fn send_track_events(
auth_manager: &AuthManager,
auth_manager: &Arc<AuthManager>,
base_url: &str,
events: Vec<TrackEventRequest>,
) {
@@ -310,9 +310,11 @@ async fn send_track_events(
if !auth.is_chatgpt_auth() {
return;
}
let access_token = match auth.get_token() {
Ok(token) => token,
Err(_) => return,
let Some(authorization_header_value) = auth_manager
.chatgpt_authorization_header_for_auth(&auth)
.await
else {
return;
};
let Some(account_id) = auth.get_account_id() else {
return;
@@ -322,15 +324,17 @@ async fn send_track_events(
let url = format!("{base_url}/codex/analytics-events/events");
let payload = TrackEventsRequest { events };
let response = create_client()
let mut request = create_client()
.post(&url)
.timeout(ANALYTICS_EVENTS_TIMEOUT)
.bearer_auth(&access_token)
.header("authorization", authorization_header_value)
.header("chatgpt-account-id", &account_id)
.header("Content-Type", "application/json")
.json(&payload)
.send()
.await;
.json(&payload);
if auth.is_fedramp_account() {
request = request.header("X-OpenAI-Fedramp", "true");
}
let response = request.send().await;
match response {
Ok(response) if response.status().is_success() => {}
-21
View File
@@ -64,28 +64,15 @@ pub use crate::remote::RemoteAppServerConnectArgs;
/// module exists so clients can remove a direct `codex-core` dependency
/// while legacy startup/config paths are migrated to RPCs.
pub mod legacy_core {
pub use codex_core::Cursor;
pub use codex_core::DEFAULT_AGENTS_MD_FILENAME;
pub use codex_core::INTERACTIVE_SESSION_SOURCES;
pub use codex_core::LOCAL_AGENTS_MD_FILENAME;
pub use codex_core::McpManager;
pub use codex_core::PLUGIN_TEXT_MENTION_SIGIL;
pub use codex_core::RolloutRecorder;
pub use codex_core::TOOL_MENTION_SIGIL;
pub use codex_core::ThreadItem;
pub use codex_core::ThreadSortKey;
pub use codex_core::ThreadsPage;
pub use codex_core::append_message_history_entry;
pub use codex_core::check_execpolicy_for_warnings;
pub use codex_core::find_thread_meta_by_name_str;
pub use codex_core::find_thread_name_by_id;
pub use codex_core::find_thread_names_by_ids;
pub use codex_core::format_exec_policy_error_with_source;
pub use codex_core::grant_read_root_non_elevated;
pub use codex_core::lookup_message_history_entry;
pub use codex_core::message_history_metadata;
pub use codex_core::path_utils;
pub use codex_core::read_session_meta_line;
pub use codex_core::web_search_detail;
pub mod config {
@@ -96,10 +83,6 @@ pub mod legacy_core {
}
}
pub mod config_loader {
pub use codex_core::config_loader::*;
}
pub mod connectors {
pub use codex_core::connectors::*;
}
@@ -124,10 +107,6 @@ pub mod legacy_core {
pub use codex_core::review_prompts::*;
}
pub mod skills {
pub use codex_core::skills::*;
}
pub mod test_support {
pub use codex_core::test_support::*;
}
@@ -1287,6 +1287,17 @@
],
"type": "object"
},
"MarketplaceRemoveParams": {
"properties": {
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"type": "object"
},
"McpResourceReadParams": {
"properties": {
"server": {
@@ -4245,6 +4256,30 @@
"title": "Marketplace/addRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"marketplace/remove"
],
"title": "Marketplace/removeRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/MarketplaceRemoveParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Marketplace/removeRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -7,6 +7,15 @@
},
"AdditionalFileSystemPermissions": {
"properties": {
"entries": {
"items": {
"$ref": "#/definitions/FileSystemSandboxEntry"
},
"type": [
"array",
"null"
]
},
"read": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
@@ -253,6 +262,217 @@
}
]
},
"FileSystemAccessMode": {
"enum": [
"read",
"write",
"none"
],
"type": "string"
},
"FileSystemPath": {
"oneOf": [
{
"properties": {
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": {
"enum": [
"path"
],
"title": "PathFileSystemPathType",
"type": "string"
}
},
"required": [
"path",
"type"
],
"title": "PathFileSystemPath",
"type": "object"
},
{
"properties": {
"pattern": {
"type": "string"
},
"type": {
"enum": [
"glob_pattern"
],
"title": "GlobPatternFileSystemPathType",
"type": "string"
}
},
"required": [
"pattern",
"type"
],
"title": "GlobPatternFileSystemPath",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"special"
],
"title": "SpecialFileSystemPathType",
"type": "string"
},
"value": {
"$ref": "#/definitions/FileSystemSpecialPath"
}
},
"required": [
"type",
"value"
],
"title": "SpecialFileSystemPath",
"type": "object"
}
]
},
"FileSystemSandboxEntry": {
"properties": {
"access": {
"$ref": "#/definitions/FileSystemAccessMode"
},
"path": {
"$ref": "#/definitions/FileSystemPath"
}
},
"required": [
"access",
"path"
],
"type": "object"
},
"FileSystemSpecialPath": {
"oneOf": [
{
"properties": {
"kind": {
"enum": [
"root"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "RootFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"minimal"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "MinimalFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"current_working_directory"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "CurrentWorkingDirectoryFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"project_roots"
],
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind"
],
"title": "KindFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"tmpdir"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "TmpdirFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"slash_tmp"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "SlashTmpFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"unknown"
],
"type": "string"
},
"path": {
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind",
"path"
],
"type": "object"
}
]
},
"NetworkApprovalContext": {
"properties": {
"host": {
@@ -7,6 +7,15 @@
},
"AdditionalFileSystemPermissions": {
"properties": {
"entries": {
"items": {
"$ref": "#/definitions/FileSystemSandboxEntry"
},
"type": [
"array",
"null"
]
},
"read": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
@@ -39,6 +48,217 @@
},
"type": "object"
},
"FileSystemAccessMode": {
"enum": [
"read",
"write",
"none"
],
"type": "string"
},
"FileSystemPath": {
"oneOf": [
{
"properties": {
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": {
"enum": [
"path"
],
"title": "PathFileSystemPathType",
"type": "string"
}
},
"required": [
"path",
"type"
],
"title": "PathFileSystemPath",
"type": "object"
},
{
"properties": {
"pattern": {
"type": "string"
},
"type": {
"enum": [
"glob_pattern"
],
"title": "GlobPatternFileSystemPathType",
"type": "string"
}
},
"required": [
"pattern",
"type"
],
"title": "GlobPatternFileSystemPath",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"special"
],
"title": "SpecialFileSystemPathType",
"type": "string"
},
"value": {
"$ref": "#/definitions/FileSystemSpecialPath"
}
},
"required": [
"type",
"value"
],
"title": "SpecialFileSystemPath",
"type": "object"
}
]
},
"FileSystemSandboxEntry": {
"properties": {
"access": {
"$ref": "#/definitions/FileSystemAccessMode"
},
"path": {
"$ref": "#/definitions/FileSystemPath"
}
},
"required": [
"access",
"path"
],
"type": "object"
},
"FileSystemSpecialPath": {
"oneOf": [
{
"properties": {
"kind": {
"enum": [
"root"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "RootFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"minimal"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "MinimalFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"current_working_directory"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "CurrentWorkingDirectoryFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"project_roots"
],
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind"
],
"title": "KindFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"tmpdir"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "TmpdirFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"slash_tmp"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "SlashTmpFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"unknown"
],
"type": "string"
},
"path": {
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind",
"path"
],
"type": "object"
}
]
},
"RequestPermissionProfile": {
"additionalProperties": false,
"properties": {
@@ -7,6 +7,15 @@
},
"AdditionalFileSystemPermissions": {
"properties": {
"entries": {
"items": {
"$ref": "#/definitions/FileSystemSandboxEntry"
},
"type": [
"array",
"null"
]
},
"read": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
@@ -39,6 +48,217 @@
},
"type": "object"
},
"FileSystemAccessMode": {
"enum": [
"read",
"write",
"none"
],
"type": "string"
},
"FileSystemPath": {
"oneOf": [
{
"properties": {
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": {
"enum": [
"path"
],
"title": "PathFileSystemPathType",
"type": "string"
}
},
"required": [
"path",
"type"
],
"title": "PathFileSystemPath",
"type": "object"
},
{
"properties": {
"pattern": {
"type": "string"
},
"type": {
"enum": [
"glob_pattern"
],
"title": "GlobPatternFileSystemPathType",
"type": "string"
}
},
"required": [
"pattern",
"type"
],
"title": "GlobPatternFileSystemPath",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"special"
],
"title": "SpecialFileSystemPathType",
"type": "string"
},
"value": {
"$ref": "#/definitions/FileSystemSpecialPath"
}
},
"required": [
"type",
"value"
],
"title": "SpecialFileSystemPath",
"type": "object"
}
]
},
"FileSystemSandboxEntry": {
"properties": {
"access": {
"$ref": "#/definitions/FileSystemAccessMode"
},
"path": {
"$ref": "#/definitions/FileSystemPath"
}
},
"required": [
"access",
"path"
],
"type": "object"
},
"FileSystemSpecialPath": {
"oneOf": [
{
"properties": {
"kind": {
"enum": [
"root"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "RootFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"minimal"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "MinimalFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"current_working_directory"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "CurrentWorkingDirectoryFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"project_roots"
],
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind"
],
"title": "KindFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"tmpdir"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "TmpdirFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"slash_tmp"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "SlashTmpFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"unknown"
],
"type": "string"
},
"path": {
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind",
"path"
],
"type": "object"
}
]
},
"GrantedPermissionProfile": {
"properties": {
"fileSystem": {
@@ -993,6 +993,32 @@
],
"type": "object"
},
"FileChangePatchUpdatedNotification": {
"properties": {
"changes": {
"items": {
"$ref": "#/definitions/FileUpdateChange"
},
"type": "array"
},
"itemId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"changes",
"itemId",
"threadId",
"turnId"
],
"type": "object"
},
"FileUpdateChange": {
"properties": {
"diff": {
@@ -4668,6 +4694,26 @@
"title": "Item/fileChange/outputDeltaNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"item/fileChange/patchUpdated"
],
"title": "Item/fileChange/patchUpdatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/FileChangePatchUpdatedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Item/fileChange/patchUpdatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -7,6 +7,15 @@
},
"AdditionalFileSystemPermissions": {
"properties": {
"entries": {
"items": {
"$ref": "#/definitions/FileSystemSandboxEntry"
},
"type": [
"array",
"null"
]
},
"read": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
@@ -586,6 +595,217 @@
],
"type": "object"
},
"FileSystemAccessMode": {
"enum": [
"read",
"write",
"none"
],
"type": "string"
},
"FileSystemPath": {
"oneOf": [
{
"properties": {
"path": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": {
"enum": [
"path"
],
"title": "PathFileSystemPathType",
"type": "string"
}
},
"required": [
"path",
"type"
],
"title": "PathFileSystemPath",
"type": "object"
},
{
"properties": {
"pattern": {
"type": "string"
},
"type": {
"enum": [
"glob_pattern"
],
"title": "GlobPatternFileSystemPathType",
"type": "string"
}
},
"required": [
"pattern",
"type"
],
"title": "GlobPatternFileSystemPath",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"special"
],
"title": "SpecialFileSystemPathType",
"type": "string"
},
"value": {
"$ref": "#/definitions/FileSystemSpecialPath"
}
},
"required": [
"type",
"value"
],
"title": "SpecialFileSystemPath",
"type": "object"
}
]
},
"FileSystemSandboxEntry": {
"properties": {
"access": {
"$ref": "#/definitions/FileSystemAccessMode"
},
"path": {
"$ref": "#/definitions/FileSystemPath"
}
},
"required": [
"access",
"path"
],
"type": "object"
},
"FileSystemSpecialPath": {
"oneOf": [
{
"properties": {
"kind": {
"enum": [
"root"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "RootFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"minimal"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "MinimalFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"current_working_directory"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "CurrentWorkingDirectoryFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"project_roots"
],
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind"
],
"title": "KindFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"tmpdir"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "TmpdirFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"slash_tmp"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "SlashTmpFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"unknown"
],
"type": "string"
},
"path": {
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind",
"path"
],
"type": "object"
}
]
},
"McpElicitationArrayType": {
"enum": [
"array"
@@ -7,6 +7,15 @@
},
"AdditionalFileSystemPermissions": {
"properties": {
"entries": {
"items": {
"$ref": "#/definitions/FileSystemSandboxEntry"
},
"type": [
"array",
"null"
]
},
"read": {
"items": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
@@ -675,6 +684,30 @@
"title": "Marketplace/addRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"marketplace/remove"
],
"title": "Marketplace/removeRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/MarketplaceRemoveParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Marketplace/removeRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -2227,6 +2260,217 @@
"title": "FileChangeRequestApprovalResponse",
"type": "object"
},
"FileSystemAccessMode": {
"enum": [
"read",
"write",
"none"
],
"type": "string"
},
"FileSystemPath": {
"oneOf": [
{
"properties": {
"path": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
},
"type": {
"enum": [
"path"
],
"title": "PathFileSystemPathType",
"type": "string"
}
},
"required": [
"path",
"type"
],
"title": "PathFileSystemPath",
"type": "object"
},
{
"properties": {
"pattern": {
"type": "string"
},
"type": {
"enum": [
"glob_pattern"
],
"title": "GlobPatternFileSystemPathType",
"type": "string"
}
},
"required": [
"pattern",
"type"
],
"title": "GlobPatternFileSystemPath",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"special"
],
"title": "SpecialFileSystemPathType",
"type": "string"
},
"value": {
"$ref": "#/definitions/FileSystemSpecialPath"
}
},
"required": [
"type",
"value"
],
"title": "SpecialFileSystemPath",
"type": "object"
}
]
},
"FileSystemSandboxEntry": {
"properties": {
"access": {
"$ref": "#/definitions/FileSystemAccessMode"
},
"path": {
"$ref": "#/definitions/FileSystemPath"
}
},
"required": [
"access",
"path"
],
"type": "object"
},
"FileSystemSpecialPath": {
"oneOf": [
{
"properties": {
"kind": {
"enum": [
"root"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "RootFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"minimal"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "MinimalFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"current_working_directory"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "CurrentWorkingDirectoryFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"project_roots"
],
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind"
],
"title": "KindFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"tmpdir"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "TmpdirFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"slash_tmp"
],
"type": "string"
}
},
"required": [
"kind"
],
"title": "SlashTmpFileSystemSpecialPath",
"type": "object"
},
{
"properties": {
"kind": {
"enum": [
"unknown"
],
"type": "string"
},
"path": {
"type": "string"
},
"subpath": {
"type": [
"string",
"null"
]
}
},
"required": [
"kind",
"path"
],
"type": "object"
}
]
},
"FuzzyFileSearchMatchType": {
"enum": [
"file",
@@ -4046,6 +4290,26 @@
"title": "Item/fileChange/outputDeltaNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"item/fileChange/patchUpdated"
],
"title": "Item/fileChange/patchUpdatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/FileChangePatchUpdatedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Item/fileChange/patchUpdatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -7741,6 +8005,34 @@
"title": "FileChangeOutputDeltaNotification",
"type": "object"
},
"FileChangePatchUpdatedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"changes": {
"items": {
"$ref": "#/definitions/v2/FileUpdateChange"
},
"type": "array"
},
"itemId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"changes",
"itemId",
"threadId",
"turnId"
],
"title": "FileChangePatchUpdatedNotification",
"type": "object"
},
"FileUpdateChange": {
"properties": {
"diff": {
@@ -9333,6 +9625,42 @@
],
"type": "object"
},
"MarketplaceRemoveParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveParams",
"type": "object"
},
"MarketplaceRemoveResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"installedRoot": {
"anyOf": [
{
"$ref": "#/definitions/v2/AbsolutePathBuf"
},
{
"type": "null"
}
]
},
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveResponse",
"type": "object"
},
"McpAuthStatus": {
"enum": [
"unsupported",
@@ -1271,6 +1271,30 @@
"title": "Marketplace/addRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"marketplace/remove"
],
"title": "Marketplace/removeRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/MarketplaceRemoveParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Marketplace/removeRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -4318,6 +4342,34 @@
"title": "FileChangeOutputDeltaNotification",
"type": "object"
},
"FileChangePatchUpdatedNotification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"changes": {
"items": {
"$ref": "#/definitions/FileUpdateChange"
},
"type": "array"
},
"itemId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"changes",
"itemId",
"threadId",
"turnId"
],
"title": "FileChangePatchUpdatedNotification",
"type": "object"
},
"FileUpdateChange": {
"properties": {
"diff": {
@@ -6065,6 +6117,42 @@
],
"type": "object"
},
"MarketplaceRemoveParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveParams",
"type": "object"
},
"MarketplaceRemoveResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"installedRoot": {
"anyOf": [
{
"$ref": "#/definitions/AbsolutePathBuf"
},
{
"type": "null"
}
]
},
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveResponse",
"type": "object"
},
"McpAuthStatus": {
"enum": [
"unsupported",
@@ -9580,6 +9668,26 @@
"title": "Item/fileChange/outputDeltaNotification",
"type": "object"
},
{
"properties": {
"method": {
"enum": [
"item/fileChange/patchUpdated"
],
"title": "Item/fileChange/patchUpdatedNotificationMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/FileChangePatchUpdatedNotification"
}
},
"required": [
"method",
"params"
],
"title": "Item/fileChange/patchUpdatedNotification",
"type": "object"
},
{
"properties": {
"method": {
@@ -0,0 +1,107 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"FileUpdateChange": {
"properties": {
"diff": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/PatchChangeKind"
},
"path": {
"type": "string"
}
},
"required": [
"diff",
"kind",
"path"
],
"type": "object"
},
"PatchChangeKind": {
"oneOf": [
{
"properties": {
"type": {
"enum": [
"add"
],
"title": "AddPatchChangeKindType",
"type": "string"
}
},
"required": [
"type"
],
"title": "AddPatchChangeKind",
"type": "object"
},
{
"properties": {
"type": {
"enum": [
"delete"
],
"title": "DeletePatchChangeKindType",
"type": "string"
}
},
"required": [
"type"
],
"title": "DeletePatchChangeKind",
"type": "object"
},
{
"properties": {
"move_path": {
"type": [
"string",
"null"
]
},
"type": {
"enum": [
"update"
],
"title": "UpdatePatchChangeKindType",
"type": "string"
}
},
"required": [
"type"
],
"title": "UpdatePatchChangeKind",
"type": "object"
}
]
}
},
"properties": {
"changes": {
"items": {
"$ref": "#/definitions/FileUpdateChange"
},
"type": "array"
},
"itemId": {
"type": "string"
},
"threadId": {
"type": "string"
},
"turnId": {
"type": "string"
}
},
"required": [
"changes",
"itemId",
"threadId",
"turnId"
],
"title": "FileChangePatchUpdatedNotification",
"type": "object"
}
@@ -0,0 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveParams",
"type": "object"
}
@@ -0,0 +1,29 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"AbsolutePathBuf": {
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
"type": "string"
}
},
"properties": {
"installedRoot": {
"anyOf": [
{
"$ref": "#/definitions/AbsolutePathBuf"
},
{
"type": "null"
}
]
},
"marketplaceName": {
"type": "string"
}
},
"required": [
"marketplaceName"
],
"title": "MarketplaceRemoveResponse",
"type": "object"
}
File diff suppressed because one or more lines are too long
@@ -16,6 +16,7 @@ import type { DeprecationNoticeNotification } from "./v2/DeprecationNoticeNotifi
import type { ErrorNotification } from "./v2/ErrorNotification";
import type { ExternalAgentConfigImportCompletedNotification } from "./v2/ExternalAgentConfigImportCompletedNotification";
import type { FileChangeOutputDeltaNotification } from "./v2/FileChangeOutputDeltaNotification";
import type { FileChangePatchUpdatedNotification } from "./v2/FileChangePatchUpdatedNotification";
import type { FsChangedNotification } from "./v2/FsChangedNotification";
import type { HookCompletedNotification } from "./v2/HookCompletedNotification";
import type { HookStartedNotification } from "./v2/HookStartedNotification";
@@ -61,4 +62,4 @@ import type { WindowsWorldWritableWarningNotification } from "./v2/WindowsWorldW
/**
* Notification sent from the server to the client.
*/
export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification };
export type ServerNotification = { "method": "error", "params": ErrorNotification } | { "method": "thread/started", "params": ThreadStartedNotification } | { "method": "thread/status/changed", "params": ThreadStatusChangedNotification } | { "method": "thread/archived", "params": ThreadArchivedNotification } | { "method": "thread/unarchived", "params": ThreadUnarchivedNotification } | { "method": "thread/closed", "params": ThreadClosedNotification } | { "method": "skills/changed", "params": SkillsChangedNotification } | { "method": "thread/name/updated", "params": ThreadNameUpdatedNotification } | { "method": "thread/tokenUsage/updated", "params": ThreadTokenUsageUpdatedNotification } | { "method": "turn/started", "params": TurnStartedNotification } | { "method": "hook/started", "params": HookStartedNotification } | { "method": "turn/completed", "params": TurnCompletedNotification } | { "method": "hook/completed", "params": HookCompletedNotification } | { "method": "turn/diff/updated", "params": TurnDiffUpdatedNotification } | { "method": "turn/plan/updated", "params": TurnPlanUpdatedNotification } | { "method": "item/started", "params": ItemStartedNotification } | { "method": "item/autoApprovalReview/started", "params": ItemGuardianApprovalReviewStartedNotification } | { "method": "item/autoApprovalReview/completed", "params": ItemGuardianApprovalReviewCompletedNotification } | { "method": "item/completed", "params": ItemCompletedNotification } | { "method": "rawResponseItem/completed", "params": RawResponseItemCompletedNotification } | { "method": "item/agentMessage/delta", "params": AgentMessageDeltaNotification } | { "method": "item/plan/delta", "params": PlanDeltaNotification } | { "method": "command/exec/outputDelta", "params": CommandExecOutputDeltaNotification } | { "method": "item/commandExecution/outputDelta", "params": CommandExecutionOutputDeltaNotification } | { "method": "item/commandExecution/terminalInteraction", "params": TerminalInteractionNotification } | { "method": "item/fileChange/outputDelta", "params": FileChangeOutputDeltaNotification } | { "method": "item/fileChange/patchUpdated", "params": FileChangePatchUpdatedNotification } | { "method": "serverRequest/resolved", "params": ServerRequestResolvedNotification } | { "method": "item/mcpToolCall/progress", "params": McpToolCallProgressNotification } | { "method": "mcpServer/oauthLogin/completed", "params": McpServerOauthLoginCompletedNotification } | { "method": "mcpServer/startupStatus/updated", "params": McpServerStatusUpdatedNotification } | { "method": "account/updated", "params": AccountUpdatedNotification } | { "method": "account/rateLimits/updated", "params": AccountRateLimitsUpdatedNotification } | { "method": "app/list/updated", "params": AppListUpdatedNotification } | { "method": "externalAgentConfig/import/completed", "params": ExternalAgentConfigImportCompletedNotification } | { "method": "fs/changed", "params": FsChangedNotification } | { "method": "item/reasoning/summaryTextDelta", "params": ReasoningSummaryTextDeltaNotification } | { "method": "item/reasoning/summaryPartAdded", "params": ReasoningSummaryPartAddedNotification } | { "method": "item/reasoning/textDelta", "params": ReasoningTextDeltaNotification } | { "method": "thread/compacted", "params": ContextCompactedNotification } | { "method": "model/rerouted", "params": ModelReroutedNotification } | { "method": "warning", "params": WarningNotification } | { "method": "deprecationNotice", "params": DeprecationNoticeNotification } | { "method": "configWarning", "params": ConfigWarningNotification } | { "method": "fuzzyFileSearch/sessionUpdated", "params": FuzzyFileSearchSessionUpdatedNotification } | { "method": "fuzzyFileSearch/sessionCompleted", "params": FuzzyFileSearchSessionCompletedNotification } | { "method": "thread/realtime/started", "params": ThreadRealtimeStartedNotification } | { "method": "thread/realtime/itemAdded", "params": ThreadRealtimeItemAddedNotification } | { "method": "thread/realtime/transcript/delta", "params": ThreadRealtimeTranscriptDeltaNotification } | { "method": "thread/realtime/transcript/done", "params": ThreadRealtimeTranscriptDoneNotification } | { "method": "thread/realtime/outputAudio/delta", "params": ThreadRealtimeOutputAudioDeltaNotification } | { "method": "thread/realtime/sdp", "params": ThreadRealtimeSdpNotification } | { "method": "thread/realtime/error", "params": ThreadRealtimeErrorNotification } | { "method": "thread/realtime/closed", "params": ThreadRealtimeClosedNotification } | { "method": "windows/worldWritableWarning", "params": WindowsWorldWritableWarningNotification } | { "method": "windowsSandbox/setupCompleted", "params": WindowsSandboxSetupCompletedNotification } | { "method": "account/login/completed", "params": AccountLoginCompletedNotification };
@@ -2,5 +2,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { FileSystemSandboxEntry } from "./FileSystemSandboxEntry";
export type AdditionalFileSystemPermissions = { read: Array<AbsolutePathBuf> | null, write: Array<AbsolutePathBuf> | null, };
export type AdditionalFileSystemPermissions = { read: Array<AbsolutePathBuf> | null, write: Array<AbsolutePathBuf> | null, entries?: Array<FileSystemSandboxEntry>, };
@@ -0,0 +1,6 @@
// 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.
import type { FileUpdateChange } from "./FileUpdateChange";
export type FileChangePatchUpdatedNotification = { threadId: string, turnId: string, itemId: string, changes: Array<FileUpdateChange>, };
@@ -0,0 +1,5 @@
// 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.
export type FileSystemAccessMode = "read" | "write" | "none";
@@ -0,0 +1,7 @@
// 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.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { FileSystemSpecialPath } from "./FileSystemSpecialPath";
export type FileSystemPath = { "type": "path", path: AbsolutePathBuf, } | { "type": "glob_pattern", pattern: string, } | { "type": "special", value: FileSystemSpecialPath, };
@@ -0,0 +1,7 @@
// 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.
import type { FileSystemAccessMode } from "./FileSystemAccessMode";
import type { FileSystemPath } from "./FileSystemPath";
export type FileSystemSandboxEntry = { path: FileSystemPath, access: FileSystemAccessMode, };
@@ -0,0 +1,5 @@
// 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.
export type FileSystemSpecialPath = { "kind": "root" } | { "kind": "minimal" } | { "kind": "current_working_directory" } | { "kind": "project_roots", subpath: string | null, } | { "kind": "tmpdir" } | { "kind": "slash_tmp" } | { "kind": "unknown", path: string, subpath: string | null, };
@@ -0,0 +1,5 @@
// 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.
export type MarketplaceRemoveParams = { marketplaceName: string, };
@@ -0,0 +1,6 @@
// 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.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
export type MarketplaceRemoveResponse = { marketplaceName: string, installedRoot: AbsolutePathBuf | null, };
@@ -98,8 +98,13 @@ export type { FeedbackUploadParams } from "./FeedbackUploadParams";
export type { FeedbackUploadResponse } from "./FeedbackUploadResponse";
export type { FileChangeApprovalDecision } from "./FileChangeApprovalDecision";
export type { FileChangeOutputDeltaNotification } from "./FileChangeOutputDeltaNotification";
export type { FileChangePatchUpdatedNotification } from "./FileChangePatchUpdatedNotification";
export type { FileChangeRequestApprovalParams } from "./FileChangeRequestApprovalParams";
export type { FileChangeRequestApprovalResponse } from "./FileChangeRequestApprovalResponse";
export type { FileSystemAccessMode } from "./FileSystemAccessMode";
export type { FileSystemPath } from "./FileSystemPath";
export type { FileSystemSandboxEntry } from "./FileSystemSandboxEntry";
export type { FileSystemSpecialPath } from "./FileSystemSpecialPath";
export type { FileUpdateChange } from "./FileUpdateChange";
export type { FsChangedNotification } from "./FsChangedNotification";
export type { FsCopyParams } from "./FsCopyParams";
@@ -157,6 +162,8 @@ export type { MarketplaceAddParams } from "./MarketplaceAddParams";
export type { MarketplaceAddResponse } from "./MarketplaceAddResponse";
export type { MarketplaceInterface } from "./MarketplaceInterface";
export type { MarketplaceLoadErrorInfo } from "./MarketplaceLoadErrorInfo";
export type { MarketplaceRemoveParams } from "./MarketplaceRemoveParams";
export type { MarketplaceRemoveResponse } from "./MarketplaceRemoveResponse";
export type { McpAuthStatus } from "./McpAuthStatus";
export type { McpElicitationArrayType } from "./McpElicitationArrayType";
export type { McpElicitationBooleanSchema } from "./McpElicitationBooleanSchema";
@@ -344,6 +344,10 @@ client_request_definitions! {
params: v2::MarketplaceAddParams,
response: v2::MarketplaceAddResponse,
},
MarketplaceRemove => "marketplace/remove" {
params: v2::MarketplaceRemoveParams,
response: v2::MarketplaceRemoveResponse,
},
PluginList => "plugin/list" {
params: v2::PluginListParams,
response: v2::PluginListResponse,
@@ -1019,6 +1023,7 @@ server_notification_definitions! {
CommandExecutionOutputDelta => "item/commandExecution/outputDelta" (v2::CommandExecutionOutputDeltaNotification),
TerminalInteraction => "item/commandExecution/terminalInteraction" (v2::TerminalInteractionNotification),
FileChangeOutputDelta => "item/fileChange/outputDelta" (v2::FileChangeOutputDeltaNotification),
FileChangePatchUpdated => "item/fileChange/patchUpdated" (v2::FileChangePatchUpdatedNotification),
ServerRequestResolved => "serverRequest/resolved" (v2::ServerRequestResolvedNotification),
McpToolCallProgress => "item/mcpToolCall/progress" (v2::McpToolCallProgressNotification),
McpServerOauthLoginCompleted => "mcpServer/oauthLogin/completed" (v2::McpServerOauthLoginCompletedNotification),
@@ -2051,6 +2056,7 @@ mod tests {
file_system: Some(v2::AdditionalFileSystemPermissions {
read: Some(vec![absolute_path("/tmp/allowed")]),
write: None,
entries: None,
}),
}),
proposed_execpolicy_amendment: None,
@@ -232,7 +232,9 @@ impl ThreadHistoryBuilder {
RolloutItem::EventMsg(event) => self.handle_event(event),
RolloutItem::Compacted(payload) => self.handle_compacted(payload),
RolloutItem::ResponseItem(item) => self.handle_response_item(item),
RolloutItem::TurnContext(_) | RolloutItem::SessionMeta(_) => {}
RolloutItem::TurnContext(_)
| RolloutItem::SessionMeta(_)
| RolloutItem::SessionState(_) => {}
}
}
+265 -14
View File
@@ -46,6 +46,10 @@ use codex_protocol::openai_models::ModelAvailabilityNux as CoreModelAvailability
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::default_input_modalities;
use codex_protocol::parse_command::ParsedCommand as CoreParsedCommand;
use codex_protocol::permissions::FileSystemAccessMode as CoreFileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath as CoreFileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry as CoreFileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSpecialPath as CoreFileSystemSpecialPath;
use codex_protocol::plan_tool::PlanItemArg as CorePlanItemArg;
use codex_protocol::plan_tool::StepStatus as CorePlanStepStatus;
use codex_protocol::protocol::AgentStatus as CoreAgentStatus;
@@ -1156,22 +1160,46 @@ impl From<CoreNetworkApprovalContext> for NetworkApprovalContext {
pub struct AdditionalFileSystemPermissions {
pub read: Option<Vec<AbsolutePathBuf>>,
pub write: Option<Vec<AbsolutePathBuf>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub entries: Option<Vec<FileSystemSandboxEntry>>,
}
impl From<CoreFileSystemPermissions> for AdditionalFileSystemPermissions {
fn from(value: CoreFileSystemPermissions) -> Self {
Self {
read: value.read,
write: value.write,
if let Some((read, write)) = value.legacy_read_write_roots() {
Self {
read,
write,
entries: None,
}
} else {
Self {
read: None,
write: None,
entries: Some(
value
.entries
.into_iter()
.map(FileSystemSandboxEntry::from)
.collect(),
),
}
}
}
}
impl From<AdditionalFileSystemPermissions> for CoreFileSystemPermissions {
fn from(value: AdditionalFileSystemPermissions) -> Self {
Self {
read: value.read,
write: value.write,
if let Some(entries) = value.entries {
Self {
entries: entries
.into_iter()
.map(CoreFileSystemSandboxEntry::from)
.collect(),
}
} else {
CoreFileSystemPermissions::from_read_write_roots(value.read, value.write)
}
}
}
@@ -1226,6 +1254,121 @@ impl From<RequestPermissionProfile> for CoreRequestPermissionProfile {
}
}
v2_enum_from_core!(
pub enum FileSystemAccessMode from CoreFileSystemAccessMode {
Read,
Write,
None
}
);
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[ts(tag = "kind")]
#[ts(export_to = "v2/")]
pub enum FileSystemSpecialPath {
Root,
Minimal,
CurrentWorkingDirectory,
ProjectRoots {
subpath: Option<PathBuf>,
},
Tmpdir,
SlashTmp,
Unknown {
path: String,
subpath: Option<PathBuf>,
},
}
impl From<CoreFileSystemSpecialPath> for FileSystemSpecialPath {
fn from(value: CoreFileSystemSpecialPath) -> Self {
match value {
CoreFileSystemSpecialPath::Root => Self::Root,
CoreFileSystemSpecialPath::Minimal => Self::Minimal,
CoreFileSystemSpecialPath::CurrentWorkingDirectory => Self::CurrentWorkingDirectory,
CoreFileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots { subpath },
CoreFileSystemSpecialPath::Tmpdir => Self::Tmpdir,
CoreFileSystemSpecialPath::SlashTmp => Self::SlashTmp,
CoreFileSystemSpecialPath::Unknown { path, subpath } => Self::Unknown { path, subpath },
}
}
}
impl From<FileSystemSpecialPath> for CoreFileSystemSpecialPath {
fn from(value: FileSystemSpecialPath) -> Self {
match value {
FileSystemSpecialPath::Root => Self::Root,
FileSystemSpecialPath::Minimal => Self::Minimal,
FileSystemSpecialPath::CurrentWorkingDirectory => Self::CurrentWorkingDirectory,
FileSystemSpecialPath::ProjectRoots { subpath } => Self::ProjectRoots { subpath },
FileSystemSpecialPath::Tmpdir => Self::Tmpdir,
FileSystemSpecialPath::SlashTmp => Self::SlashTmp,
FileSystemSpecialPath::Unknown { path, subpath } => Self::Unknown { path, subpath },
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum FileSystemPath {
Path { path: AbsolutePathBuf },
GlobPattern { pattern: String },
Special { value: FileSystemSpecialPath },
}
impl From<CoreFileSystemPath> for FileSystemPath {
fn from(value: CoreFileSystemPath) -> Self {
match value {
CoreFileSystemPath::Path { path } => Self::Path { path },
CoreFileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
CoreFileSystemPath::Special { value } => Self::Special {
value: value.into(),
},
}
}
}
impl From<FileSystemPath> for CoreFileSystemPath {
fn from(value: FileSystemPath) -> Self {
match value {
FileSystemPath::Path { path } => Self::Path { path },
FileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
FileSystemPath::Special { value } => Self::Special {
value: value.into(),
},
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FileSystemSandboxEntry {
pub path: FileSystemPath,
pub access: FileSystemAccessMode,
}
impl From<CoreFileSystemSandboxEntry> for FileSystemSandboxEntry {
fn from(value: CoreFileSystemSandboxEntry) -> Self {
Self {
path: value.path.into(),
access: value.access.into(),
}
}
}
impl From<FileSystemSandboxEntry> for CoreFileSystemSandboxEntry {
fn from(value: FileSystemSandboxEntry) -> Self {
Self {
path: value.path.into(),
access: value.access.to_core(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -3481,6 +3624,21 @@ pub struct MarketplaceAddResponse {
pub already_added: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceRemoveParams {
pub marketplace_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct MarketplaceRemoveResponse {
pub marketplace_name: String,
pub installed_root: Option<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -5777,6 +5935,16 @@ pub struct FileChangeOutputDeltaNotification {
pub delta: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct FileChangePatchUpdatedNotification {
pub thread_id: String,
pub turn_id: String,
pub item_id: String,
pub changes: Vec<FileUpdateChange>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -6916,6 +7084,7 @@ mod tests {
AbsolutePathBuf::try_from(PathBuf::from(read_write_path))
.expect("path must be absolute"),
]),
entries: None,
}),
}
);
@@ -6926,16 +7095,16 @@ mod tests {
network: Some(CoreNetworkPermissions {
enabled: Some(true),
}),
file_system: Some(CoreFileSystemPermissions {
read: Some(vec![
file_system: Some(CoreFileSystemPermissions::from_read_write_roots(
Some(vec![
AbsolutePathBuf::try_from(PathBuf::from(read_only_path))
.expect("path must be absolute"),
]),
write: Some(vec![
Some(vec![
AbsolutePathBuf::try_from(PathBuf::from(read_write_path))
.expect("path must be absolute"),
]),
}),
)),
}
);
}
@@ -6969,6 +7138,53 @@ mod tests {
);
}
#[test]
fn additional_file_system_permissions_preserves_canonical_entries() {
let core_permissions = CoreFileSystemPermissions {
entries: vec![
CoreFileSystemSandboxEntry {
path: CoreFileSystemPath::Special {
value: CoreFileSystemSpecialPath::Root,
},
access: CoreFileSystemAccessMode::Write,
},
CoreFileSystemSandboxEntry {
path: CoreFileSystemPath::GlobPattern {
pattern: "**/*.env".to_string(),
},
access: CoreFileSystemAccessMode::None,
},
],
};
let permissions = AdditionalFileSystemPermissions::from(core_permissions.clone());
assert_eq!(
permissions,
AdditionalFileSystemPermissions {
read: None,
write: None,
entries: Some(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Write,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: "**/*.env".to_string(),
},
access: FileSystemAccessMode::None,
},
]),
}
);
assert_eq!(
CoreFileSystemPermissions::from(permissions),
core_permissions
);
}
#[test]
fn permissions_request_approval_response_uses_granted_permission_profile_without_macos() {
let read_only_path = if cfg!(windows) {
@@ -7009,6 +7225,7 @@ mod tests {
AbsolutePathBuf::try_from(PathBuf::from(read_write_path))
.expect("path must be absolute"),
]),
entries: None,
}),
}
);
@@ -7019,16 +7236,16 @@ mod tests {
network: Some(CoreNetworkPermissions {
enabled: Some(true),
}),
file_system: Some(CoreFileSystemPermissions {
read: Some(vec![
file_system: Some(CoreFileSystemPermissions::from_read_write_roots(
Some(vec![
AbsolutePathBuf::try_from(PathBuf::from(read_only_path))
.expect("path must be absolute"),
]),
write: Some(vec![
Some(vec![
AbsolutePathBuf::try_from(PathBuf::from(read_write_path))
.expect("path must be absolute"),
]),
}),
)),
}
);
}
@@ -8890,6 +9107,40 @@ mod tests {
);
}
#[test]
fn marketplace_remove_response_serializes_nullable_installed_root() {
let installed_root = if cfg!(windows) {
r"C:\marketplaces\debug"
} else {
"/tmp/marketplaces/debug"
};
let installed_root = AbsolutePathBuf::try_from(PathBuf::from(installed_root)).unwrap();
let installed_root_json = installed_root.as_path().display().to_string();
assert_eq!(
serde_json::to_value(MarketplaceRemoveResponse {
marketplace_name: "debug".to_string(),
installed_root: Some(installed_root),
})
.unwrap(),
json!({
"marketplaceName": "debug",
"installedRoot": installed_root_json,
}),
);
assert_eq!(
serde_json::to_value(MarketplaceRemoveResponse {
marketplace_name: "debug".to_string(),
installed_root: None,
})
.unwrap(),
json!({
"marketplaceName": "debug",
"installedRoot": null,
}),
);
}
#[test]
fn codex_error_info_serializes_http_status_code_in_camel_case() {
let value = CodexErrorInfo::ResponseTooManyFailedAttempts {
+2
View File
@@ -185,6 +185,7 @@ Example with notification opt-out:
- `collaborationMode/list` — list available collaboration mode presets (experimental, no pagination). This response omits built-in developer instructions; clients should either pass `settings.developer_instructions: null` when setting a mode to use Codex's built-in instructions, or provide their own instructions explicitly.
- `skills/list` — list skills for one or more `cwd` values (optional `forceReload`).
- `marketplace/add` — add a remote plugin marketplace from an HTTP(S) Git URL, SSH Git URL, or GitHub `owner/repo` shorthand, then persist it into the user marketplace config. Returns the installed root path plus whether the marketplace was already present.
- `marketplace/remove` — remove a configured marketplace by name from the user marketplace config, and delete its installed marketplace root when one exists.
- `plugin/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. `interface.category` uses the marketplace category when present; otherwise it falls back to the plugin manifest category (**under development; do not call from production clients yet**).
- `plugin/read` — read one plugin by `marketplacePath` plus `pluginName`, returning marketplace info, a list-style `summary`, manifest descriptions/interface metadata, and bundled skills/apps/MCP server names. Returned plugin skills include their current `enabled` state after local config filtering. Plugin app summaries also include `needsAuth` when the server can determine connector accessibility (**under development; do not call from production clients yet**).
- `skills/changed` — notification emitted when watched local skill files change.
@@ -1068,6 +1069,7 @@ There are additional item-specific events:
#### fileChange
- `item/fileChange/patchUpdated` - when `features.apply_patch_streaming_events` is enabled, streams structured file-change snapshots parsed from the model-generated patch before it is executed.
- `item/fileChange/outputDelta` - contains the tool call response of the underlying `apply_patch` tool call.
### Errors
@@ -40,6 +40,7 @@ use codex_app_server_protocol::ExecCommandApprovalResponse;
use codex_app_server_protocol::ExecPolicyAmendment as V2ExecPolicyAmendment;
use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeOutputDeltaNotification;
use codex_app_server_protocol::FileChangePatchUpdatedNotification;
use codex_app_server_protocol::FileChangeRequestApprovalParams;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
use codex_app_server_protocol::FileUpdateChange;
@@ -1636,6 +1637,17 @@ pub(crate) async fn apply_bespoke_event_handling(
.await;
}
}
EventMsg::PatchApplyUpdated(event) => {
let notification = FileChangePatchUpdatedNotification {
thread_id: conversation_id.to_string(),
turn_id: event_turn_id.clone(),
item_id: event.call_id,
changes: convert_patch_changes(&event.changes),
};
outgoing
.send_server_notification(ServerNotification::FileChangePatchUpdated(notification))
.await;
}
EventMsg::PatchApplyEnd(patch_end_event) => {
// Until we migrate the core to be aware of a first class FileChangeItem
// and emit the corresponding EventMsg, we repurpose the call_id as the item_id.
@@ -3723,10 +3735,10 @@ mod tests {
network: Some(CoreNetworkPermissions {
enabled: Some(true),
}),
file_system: Some(CoreFileSystemPermissions {
read: Some(vec![absolute_path(input_path)]),
write: Some(vec![absolute_path(output_path)]),
}),
file_system: Some(CoreFileSystemPermissions::from_read_write_roots(
Some(vec![absolute_path(input_path)]),
Some(vec![absolute_path(output_path)]),
)),
};
let cases = vec![
(
@@ -3753,10 +3765,10 @@ mod tests {
},
}),
CoreRequestPermissionProfile {
file_system: Some(CoreFileSystemPermissions {
read: None,
write: Some(vec![absolute_path(output_path)]),
}),
file_system: Some(CoreFileSystemPermissions::from_read_write_roots(
/*read*/ None,
Some(vec![absolute_path(output_path)]),
)),
..CoreRequestPermissionProfile::default()
},
),
@@ -3771,10 +3783,10 @@ mod tests {
},
}),
CoreRequestPermissionProfile {
file_system: Some(CoreFileSystemPermissions {
read: Some(vec![absolute_path(input_path)]),
write: Some(vec![absolute_path(output_path)]),
}),
file_system: Some(CoreFileSystemPermissions::from_read_write_roots(
Some(vec![absolute_path(input_path)]),
Some(vec![absolute_path(output_path)]),
)),
..CoreRequestPermissionProfile::default()
},
),
+237 -211
View File
@@ -85,6 +85,8 @@ use codex_app_server_protocol::LogoutAccountResponse;
use codex_app_server_protocol::MarketplaceAddParams;
use codex_app_server_protocol::MarketplaceAddResponse;
use codex_app_server_protocol::MarketplaceInterface;
use codex_app_server_protocol::MarketplaceRemoveParams;
use codex_app_server_protocol::MarketplaceRemoveResponse;
use codex_app_server_protocol::McpResourceReadParams;
use codex_app_server_protocol::McpResourceReadResponse;
use codex_app_server_protocol::McpServerOauthLoginCompletedNotification;
@@ -220,7 +222,6 @@ use codex_core::SessionMeta;
use codex_core::SteerInputError;
use codex_core::ThreadConfigSnapshot;
use codex_core::ThreadManager;
use codex_core::append_thread_name;
use codex_core::clear_memory_roots_contents;
use codex_core::config::Config;
use codex_core::config::ConfigOverrides;
@@ -243,12 +244,15 @@ use codex_core::find_thread_names_by_ids;
use codex_core::find_thread_path_by_id_str;
use codex_core::path_utils;
use codex_core::plugins::MarketplaceAddError;
use codex_core::plugins::MarketplaceRemoveError;
use codex_core::plugins::MarketplaceRemoveRequest as CoreMarketplaceRemoveRequest;
use codex_core::plugins::OPENAI_CURATED_MARKETPLACE_NAME;
use codex_core::plugins::PluginInstallError as CorePluginInstallError;
use codex_core::plugins::PluginInstallRequest;
use codex_core::plugins::PluginReadRequest;
use codex_core::plugins::PluginUninstallError as CorePluginUninstallError;
use codex_core::plugins::add_marketplace as add_marketplace_to_codex_home;
use codex_core::plugins::remove_marketplace;
use codex_core::read_head_for_summary;
use codex_core::read_session_meta_line;
use codex_core::sandboxing::SandboxPermissions;
@@ -279,11 +283,12 @@ use codex_login::default_client::set_default_client_residency_requirement;
use codex_login::login_with_api_key;
use codex_login::request_device_code;
use codex_login::run_login_server;
use codex_mcp::McpRuntimeEnvironment;
use codex_mcp::McpServerStatusSnapshot;
use codex_mcp::McpSnapshotDetail;
use codex_mcp::collect_mcp_server_status_snapshot_with_detail;
use codex_mcp::collect_mcp_server_status_snapshot_with_detail_and_authorization_header;
use codex_mcp::discover_supported_scopes;
use codex_mcp::effective_mcp_servers;
use codex_mcp::effective_mcp_servers_with_authorization_header;
use codex_mcp::resolve_oauth_scopes;
use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig;
use codex_protocol::ThreadId;
@@ -316,13 +321,11 @@ use codex_protocol::protocol::ReviewTarget as CoreReviewTarget;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::SessionConfiguredEvent;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::ThreadNameUpdatedEvent;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
use codex_protocol::user_input::UserInput as CoreInputItem;
use codex_rmcp_client::perform_oauth_login_return_url;
use codex_rollout::append_rollout_item_to_path;
use codex_rollout::state_db::StateDbHandle;
use codex_rollout::state_db::get_state_db;
use codex_rollout::state_db::reconcile_rollout;
@@ -336,9 +339,11 @@ use codex_thread_store::LocalThreadStore;
use codex_thread_store::ReadThreadParams as StoreReadThreadParams;
use codex_thread_store::SortDirection as StoreSortDirection;
use codex_thread_store::StoredThread;
use codex_thread_store::ThreadMetadataPatch as StoreThreadMetadataPatch;
use codex_thread_store::ThreadSortKey as StoreThreadSortKey;
use codex_thread_store::ThreadStore;
use codex_thread_store::ThreadStoreError;
use codex_thread_store::UpdateThreadMetadataParams as StoreUpdateThreadMetadataParams;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_json_to_toml::json_to_toml;
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
@@ -979,6 +984,10 @@ impl CodexMessageProcessor {
self.marketplace_add(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::MarketplaceRemove { request_id, params } => {
self.marketplace_remove(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::PluginList { request_id, params } => {
self.plugin_list(to_connection_request_id(request_id), params)
.await;
@@ -2003,12 +2012,28 @@ impl CodexMessageProcessor {
});
}
let client = BackendClient::from_auth(self.config.chatgpt_base_url.clone(), &auth)
let authorization_header_value = self
.auth_manager
.chatgpt_authorization_header_for_auth(&auth)
.await;
let mut client = BackendClient::new(self.config.chatgpt_base_url.clone())
.map(|client| {
client.with_user_agent(codex_login::default_client::get_codex_user_agent())
})
.map_err(|err| JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
message: format!("failed to construct backend client: {err}"),
data: None,
})?;
if let Some(authorization_header_value) = authorization_header_value {
client = client.with_authorization_header_value(authorization_header_value);
}
if let Some(account_id) = auth.get_account_id() {
client = client.with_chatgpt_account_id(account_id);
}
if auth.is_fedramp_account() {
client = client.with_fedramp_routing_header();
}
let snapshots = client
.get_rate_limits_many()
@@ -2974,54 +2999,23 @@ impl CodexMessageProcessor {
return;
}
let rollout_path =
match find_thread_path_by_id_str(&self.config.codex_home, &thread_id.to_string()).await
{
Ok(Some(path)) => Some(path),
Ok(None) => None,
Err(err) => {
self.send_invalid_request_error(
request_id,
format!("failed to locate thread id {thread_id}: {err}"),
)
.await;
return;
}
};
let Some(rollout_path) = rollout_path else {
self.send_invalid_request_error(request_id, format!("thread not found: {thread_id}"))
.await;
return;
};
let msg = EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent {
thread_id,
thread_name: Some(name.clone()),
});
let item = RolloutItem::EventMsg(msg);
if let Err(err) = append_rollout_item_to_path(rollout_path.as_path(), &item).await {
self.send_internal_error(request_id, format!("failed to set thread name: {err}"))
if let Err(err) = self
.thread_store
.update_thread_metadata(StoreUpdateThreadMetadataParams {
thread_id,
patch: StoreThreadMetadataPatch {
name: Some(name.clone()),
..Default::default()
},
include_archived: false,
})
.await
{
self.outgoing
.send_error(request_id, thread_store_write_error("set thread name", err))
.await;
return;
}
if let Err(err) = append_thread_name(&self.config.codex_home, thread_id, &name).await {
self.send_internal_error(request_id, format!("failed to index thread name: {err}"))
.await;
return;
}
let state_db_ctx = open_state_db_for_direct_thread_lookup(&self.config).await;
reconcile_rollout(
state_db_ctx.as_deref(),
rollout_path.as_path(),
self.config.model_provider_id.as_str(),
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
self.outgoing
.send_response(request_id, ThreadSetNameResponse {})
@@ -3075,72 +3069,26 @@ impl CodexMessageProcessor {
return;
}
let rollout_path =
match find_thread_path_by_id_str(&self.config.codex_home, &thread_id.to_string()).await
{
Ok(Some(path)) => Some(path),
Ok(None) => None,
Err(err) => {
self.send_invalid_request_error(
request_id,
format!("failed to locate thread id {thread_id}: {err}"),
)
.await;
return;
}
};
let Some(rollout_path) = rollout_path else {
self.send_invalid_request_error(request_id, format!("thread not found: {thread_id}"))
.await;
return;
};
let mut session_meta = match read_session_meta_line(rollout_path.as_path()).await {
Ok(session_meta) => session_meta,
Err(err) => {
self.send_internal_error(
if let Err(err) = self
.thread_store
.update_thread_metadata(StoreUpdateThreadMetadataParams {
thread_id,
patch: StoreThreadMetadataPatch {
memory_mode: Some(mode.to_core()),
..Default::default()
},
include_archived: false,
})
.await
{
self.outgoing
.send_error(
request_id,
format!("failed to set thread memory mode: {err}"),
thread_store_write_error("set thread memory mode", err),
)
.await;
return;
}
};
if session_meta.meta.id != thread_id {
self.send_internal_error(
request_id,
format!(
"failed to set thread memory mode: rollout session metadata id mismatch: expected {thread_id}, found {}",
session_meta.meta.id
),
)
.await;
return;
}
session_meta.meta.memory_mode = Some(mode.as_str().to_string());
let item = RolloutItem::SessionMeta(session_meta);
if let Err(err) = append_rollout_item_to_path(rollout_path.as_path(), &item).await {
self.send_internal_error(
request_id,
format!("failed to set thread memory mode: {err}"),
)
.await;
return;
}
let state_db_ctx = open_state_db_for_direct_thread_lookup(&self.config).await;
reconcile_rollout(
state_db_ctx.as_deref(),
rollout_path.as_path(),
self.config.model_provider_id.as_str(),
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
self.outgoing
.send_response(request_id, ThreadMemoryModeSetResponse {})
@@ -5723,113 +5671,137 @@ impl CodexMessageProcessor {
let mcp_config = config
.to_mcp_config(self.thread_manager.plugins_manager().as_ref())
.await;
let auth = self.auth_manager.auth().await;
let auth_manager = Arc::clone(&self.auth_manager);
let auth = auth_manager.auth().await;
let runtime_environment = match self.thread_manager.environment_manager().current().await {
Ok(Some(environment)) => {
// Status listing has no turn cwd. This fallback is used only
// by executor-backed stdio MCPs whose config omits `cwd`.
McpRuntimeEnvironment::new(environment, config.cwd.to_path_buf())
}
Ok(None) => McpRuntimeEnvironment::new(
Arc::new(codex_exec_server::Environment::default()),
config.cwd.to_path_buf(),
),
Err(err) => {
// TODO(aibrahim): Investigate degrading MCP status listing when
// executor environment creation fails.
let error = JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
message: format!("failed to create environment: {err}"),
data: None,
};
self.outgoing.send_error(request, error).await;
return;
}
};
tokio::spawn(async move {
Self::list_mcp_server_status_task(outgoing, request, params, config, mcp_config, auth)
.await;
});
}
async fn list_mcp_server_status_task(
outgoing: Arc<OutgoingMessageSender>,
request_id: ConnectionRequestId,
params: ListMcpServerStatusParams,
config: Config,
mcp_config: codex_mcp::McpConfig,
auth: Option<CodexAuth>,
) {
let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) {
McpServerStatusDetail::Full => McpSnapshotDetail::Full,
McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly,
};
let snapshot = collect_mcp_server_status_snapshot_with_detail(
&mcp_config,
auth.as_ref(),
request_id.request_id.to_string(),
detail,
)
.await;
let effective_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
let McpServerStatusSnapshot {
tools_by_server,
resources,
resource_templates,
auth_statuses,
} = snapshot;
let mut server_names: Vec<String> = config
.mcp_servers
.keys()
.cloned()
// Include built-in/plugin MCP servers that are present in the
// effective runtime config even when they are not user-declared in
// `config.mcp_servers`.
.chain(effective_servers.keys().cloned())
.chain(auth_statuses.keys().cloned())
.chain(resources.keys().cloned())
.chain(resource_templates.keys().cloned())
.collect();
server_names.sort();
server_names.dedup();
let total = server_names.len();
let limit = params.limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = limit.min(total);
let start = match params.cursor {
Some(cursor) => match cursor.parse::<usize>() {
Ok(idx) => idx,
Err(_) => {
let error = JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!("invalid cursor: {cursor}"),
data: None,
};
outgoing.send_error(request_id, error).await;
return;
}
},
None => 0,
};
if start > total {
let error = JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!("cursor {start} exceeds total MCP servers {total}"),
data: None,
let detail = match params.detail.unwrap_or(McpServerStatusDetail::Full) {
McpServerStatusDetail::Full => McpSnapshotDetail::Full,
McpServerStatusDetail::ToolsAndAuthOnly => McpSnapshotDetail::ToolsAndAuthOnly,
};
outgoing.send_error(request_id, error).await;
return;
}
let end = start.saturating_add(effective_limit).min(total);
let background_authorization_header_value = if let Some(auth) = auth.as_ref() {
auth_manager
.chatgpt_authorization_header_for_auth(auth)
.await
} else {
None
};
let snapshot = collect_mcp_server_status_snapshot_with_detail_and_authorization_header(
&mcp_config,
auth.as_ref(),
request.request_id.to_string(),
runtime_environment,
detail,
background_authorization_header_value.as_deref(),
)
.await;
let data: Vec<McpServerStatus> = server_names[start..end]
.iter()
.map(|name| McpServerStatus {
name: name.clone(),
tools: tools_by_server.get(name).cloned().unwrap_or_default(),
resources: resources.get(name).cloned().unwrap_or_default(),
resource_templates: resource_templates.get(name).cloned().unwrap_or_default(),
auth_status: auth_statuses
.get(name)
.cloned()
.unwrap_or(CoreMcpAuthStatus::Unsupported)
.into(),
})
.collect();
let effective_servers = effective_mcp_servers_with_authorization_header(
&mcp_config,
auth.as_ref(),
background_authorization_header_value.as_deref(),
);
let McpServerStatusSnapshot {
tools_by_server,
resources,
resource_templates,
auth_statuses,
} = snapshot;
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
let mut server_names: Vec<String> = config
.mcp_servers
.keys()
.cloned()
// Include built-in/plugin MCP servers that are present in the
// effective runtime config even when they are not user-declared in
// `config.mcp_servers`.
.chain(effective_servers.keys().cloned())
.chain(auth_statuses.keys().cloned())
.chain(resources.keys().cloned())
.chain(resource_templates.keys().cloned())
.collect();
server_names.sort();
server_names.dedup();
let response = ListMcpServerStatusResponse { data, next_cursor };
let total = server_names.len();
let limit = params.limit.unwrap_or(total as u32).max(1) as usize;
let effective_limit = limit.min(total);
let start = match params.cursor {
Some(cursor) => match cursor.parse::<usize>() {
Ok(idx) => idx,
Err(_) => {
let error = JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!("invalid cursor: {cursor}"),
data: None,
};
outgoing.send_error(request, error).await;
return;
}
},
None => 0,
};
outgoing.send_response(request_id, response).await;
if start > total {
let error = JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!("cursor {start} exceeds total MCP servers {total}"),
data: None,
};
outgoing.send_error(request, error).await;
return;
}
let end = start.saturating_add(effective_limit).min(total);
let data: Vec<McpServerStatus> = server_names[start..end]
.iter()
.map(|name| McpServerStatus {
name: name.clone(),
tools: tools_by_server.get(name).cloned().unwrap_or_default(),
resources: resources.get(name).cloned().unwrap_or_default(),
resource_templates: resource_templates.get(name).cloned().unwrap_or_default(),
auth_status: auth_statuses
.get(name)
.cloned()
.unwrap_or(CoreMcpAuthStatus::Unsupported)
.into(),
})
.collect();
let next_cursor = if end < total {
Some(end.to_string())
} else {
None
};
let response = ListMcpServerStatusResponse { data, next_cursor };
outgoing.send_response(request, response).await;
});
}
async fn read_mcp_resource(
@@ -6504,6 +6476,40 @@ impl CodexMessageProcessor {
.await;
}
async fn marketplace_remove(
&self,
request_id: ConnectionRequestId,
params: MarketplaceRemoveParams,
) {
let result = remove_marketplace(
self.config.codex_home.to_path_buf(),
CoreMarketplaceRemoveRequest {
marketplace_name: params.marketplace_name,
},
)
.await;
match result {
Ok(outcome) => {
self.outgoing
.send_response(
request_id,
MarketplaceRemoveResponse {
marketplace_name: outcome.marketplace_name,
installed_root: outcome.removed_installed_root,
},
)
.await;
}
Err(MarketplaceRemoveError::InvalidRequest(message)) => {
self.send_invalid_request_error(request_id, message).await;
}
Err(MarketplaceRemoveError::Internal(message)) => {
self.send_internal_error(request_id, message).await;
}
}
}
async fn plugin_list(&self, request_id: ConnectionRequestId, params: PluginListParams) {
let plugins_manager = self.thread_manager.plugins_manager();
let PluginListParams { cwds } = params;
@@ -9525,6 +9531,26 @@ fn thread_store_list_error(err: ThreadStoreError) -> JSONRPCErrorError {
}
}
fn thread_store_write_error(operation: &str, err: ThreadStoreError) -> JSONRPCErrorError {
match err {
ThreadStoreError::ThreadNotFound { thread_id } => JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: format!("thread not found: {thread_id}"),
data: None,
},
ThreadStoreError::InvalidRequest { message } => JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message,
data: None,
},
err => JSONRPCErrorError {
code: INTERNAL_ERROR_CODE,
message: format!("failed to {operation}: {err}"),
data: None,
},
}
}
fn thread_from_stored_thread(
thread: StoredThread,
fallback_provider: &str,
+13 -11
View File
@@ -27,10 +27,11 @@ use crate::outgoing_message::QueuedOutgoingMessage;
use crate::transport::CHANNEL_CAPACITY;
use crate::transport::ConnectionState;
use crate::transport::OutboundConnectionState;
use crate::transport::RemoteControlStartOptions;
use crate::transport::TransportEvent;
use crate::transport::auth::policy_from_settings;
use crate::transport::route_outgoing_envelope;
use crate::transport::start_remote_control;
use crate::transport::start_remote_control_with_options;
use crate::transport::start_stdio_connection;
use crate::transport::start_websocket_acceptor;
use codex_analytics::AppServerRpcTransport;
@@ -575,16 +576,17 @@ pub async fn run_main_with_transport(
));
}
let (remote_control_accept_handle, remote_control_handle) = start_remote_control(
config.chatgpt_base_url.clone(),
state_db.clone(),
auth_manager.clone(),
transport_event_tx.clone(),
transport_shutdown_token.clone(),
app_server_client_name_rx,
remote_control_enabled,
)
.await?;
let (remote_control_accept_handle, remote_control_handle) =
start_remote_control_with_options(RemoteControlStartOptions {
remote_control_url: config.chatgpt_base_url.clone(),
state_db: state_db.clone(),
auth_manager: auth_manager.clone(),
transport_event_tx: transport_event_tx.clone(),
shutdown_token: transport_shutdown_token.clone(),
app_server_client_name_rx,
initial_enabled: remote_control_enabled,
})
.await?;
transport_accept_handles.push(remote_control_accept_handle);
let outbound_handle = tokio::spawn(async move {
+4 -1
View File
@@ -34,7 +34,8 @@ mod stdio;
mod websocket;
pub(crate) use remote_control::RemoteControlHandle;
pub(crate) use remote_control::start_remote_control;
pub(crate) use remote_control::RemoteControlStartOptions;
pub(crate) use remote_control::start_remote_control_with_options;
pub(crate) use stdio::start_stdio_connection;
pub(crate) use websocket::start_websocket_acceptor;
@@ -780,6 +781,7 @@ mod tests {
codex_app_server_protocol::AdditionalFileSystemPermissions {
read: Some(vec![absolute_path("/tmp/allowed")]),
write: None,
entries: None,
},
),
},
@@ -842,6 +844,7 @@ mod tests {
codex_app_server_protocol::AdditionalFileSystemPermissions {
read: Some(vec![absolute_path("/tmp/allowed")]),
write: None,
entries: None,
},
),
},
@@ -17,6 +17,7 @@ const REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES: usize = 4096;
const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
const CF_RAY_HEADER: &str = "cf-ray";
const REMOTE_CONTROL_FEDRAMP_HEADER: &str = "X-OpenAI-Fedramp";
pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id";
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -29,8 +30,9 @@ pub(super) struct RemoteControlEnrollment {
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct RemoteControlConnectionAuth {
pub(super) bearer_token: String,
pub(super) authorization_header_value: String,
pub(super) account_id: String,
pub(super) is_fedramp_account: bool,
}
pub(super) async fn load_persisted_remote_control_enrollment(
@@ -199,12 +201,15 @@ pub(super) async fn enroll_remote_control_server(
app_server_version: env!("CARGO_PKG_VERSION"),
};
let client = build_reqwest_client();
let http_request = client
let mut http_request = client
.post(enroll_url)
.timeout(REMOTE_CONTROL_ENROLL_TIMEOUT)
.bearer_auth(&auth.bearer_token)
.header(REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id)
.json(&request);
.header("authorization", &auth.authorization_header_value)
.header(REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id);
if auth.is_fedramp_account {
http_request = http_request.header(REMOTE_CONTROL_FEDRAMP_HEADER, "true");
}
let http_request = http_request.json(&request);
let response = http_request.send().await.map_err(|err| {
io::Error::other(format!(
@@ -445,8 +450,9 @@ mod tests {
let err = enroll_remote_control_server(
&remote_control_target,
&RemoteControlConnectionAuth {
bearer_token: "Access Token".to_string(),
authorization_header_value: "Bearer Access Token".to_string(),
account_id: "account_id".to_string(),
is_fedramp_account: false,
},
)
.await
@@ -4,6 +4,7 @@ mod protocol;
mod websocket;
use crate::transport::remote_control::websocket::RemoteControlWebsocket;
use crate::transport::remote_control::websocket::RemoteControlWebsocketOptions;
pub use self::protocol::ClientId;
use self::protocol::ServerEvent;
@@ -44,6 +45,17 @@ impl RemoteControlHandle {
}
}
pub(crate) struct RemoteControlStartOptions {
pub(crate) remote_control_url: String,
pub(crate) state_db: Option<Arc<StateRuntime>>,
pub(crate) auth_manager: Arc<AuthManager>,
pub(crate) transport_event_tx: mpsc::Sender<TransportEvent>,
pub(crate) shutdown_token: CancellationToken,
pub(crate) app_server_client_name_rx: Option<oneshot::Receiver<String>>,
pub(crate) initial_enabled: bool,
}
#[cfg(test)]
pub(crate) async fn start_remote_control(
remote_control_url: String,
state_db: Option<Arc<StateRuntime>>,
@@ -53,15 +65,38 @@ pub(crate) async fn start_remote_control(
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
initial_enabled: bool,
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
start_remote_control_with_options(RemoteControlStartOptions {
remote_control_url,
state_db,
auth_manager,
transport_event_tx,
shutdown_token,
app_server_client_name_rx,
initial_enabled,
})
.await
}
pub(crate) async fn start_remote_control_with_options(
options: RemoteControlStartOptions,
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
let RemoteControlStartOptions {
remote_control_url,
state_db,
auth_manager,
transport_event_tx,
shutdown_token,
app_server_client_name_rx,
initial_enabled,
} = options;
let remote_control_target = if initial_enabled {
Some(normalize_remote_control_url(&remote_control_url)?)
} else {
None
};
let (enabled_tx, enabled_rx) = watch::channel(initial_enabled);
let join_handle = tokio::spawn(async move {
RemoteControlWebsocket::new(
RemoteControlWebsocket::from_options(RemoteControlWebsocketOptions {
remote_control_url,
remote_control_target,
state_db,
@@ -69,7 +104,7 @@ pub(crate) async fn start_remote_control(
transport_event_tx,
shutdown_token,
enabled_rx,
)
})
.run(app_server_client_name_rx)
.await;
});
@@ -49,6 +49,7 @@ use tracing::warn;
pub(super) const REMOTE_CONTROL_PROTOCOL_VERSION: &str = "2";
pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id";
const REMOTE_CONTROL_FEDRAMP_HEADER: &str = "X-OpenAI-Fedramp";
const REMOTE_CONTROL_SUBSCRIBE_CURSOR_HEADER: &str = "x-codex-subscribe-cursor";
const REMOTE_CONTROL_WEBSOCKET_PING_INTERVAL: std::time::Duration =
std::time::Duration::from_secs(10);
@@ -128,6 +129,16 @@ pub(crate) struct RemoteControlWebsocket {
enabled_rx: watch::Receiver<bool>,
}
pub(crate) struct RemoteControlWebsocketOptions {
pub(crate) remote_control_url: String,
pub(crate) remote_control_target: Option<RemoteControlTarget>,
pub(crate) state_db: Option<Arc<StateRuntime>>,
pub(crate) auth_manager: Arc<AuthManager>,
pub(crate) transport_event_tx: mpsc::Sender<TransportEvent>,
pub(crate) shutdown_token: CancellationToken,
pub(crate) enabled_rx: watch::Receiver<bool>,
}
enum ConnectOutcome {
Connected(Box<WebSocketStream<MaybeTlsStream<TcpStream>>>),
Disabled,
@@ -135,6 +146,7 @@ enum ConnectOutcome {
}
impl RemoteControlWebsocket {
#[cfg(test)]
pub(crate) fn new(
remote_control_url: String,
remote_control_target: Option<RemoteControlTarget>,
@@ -144,6 +156,27 @@ impl RemoteControlWebsocket {
shutdown_token: CancellationToken,
enabled_rx: watch::Receiver<bool>,
) -> Self {
Self::from_options(RemoteControlWebsocketOptions {
remote_control_url,
remote_control_target,
state_db,
auth_manager,
transport_event_tx,
shutdown_token,
enabled_rx,
})
}
pub(crate) fn from_options(options: RemoteControlWebsocketOptions) -> Self {
let RemoteControlWebsocketOptions {
remote_control_url,
remote_control_target,
state_db,
auth_manager,
transport_event_tx,
shutdown_token,
enabled_rx,
} = options;
let shutdown_token = shutdown_token.child_token();
let (server_event_tx, server_event_rx) = mpsc::channel(super::CHANNEL_CAPACITY);
let client_tracker =
@@ -271,14 +304,16 @@ impl RemoteControlWebsocket {
}
return ConnectOutcome::Disabled;
}
connect_result = connect_remote_control_websocket(
&remote_control_target,
self.state_db.as_deref(),
&self.auth_manager,
&mut self.auth_recovery,
&mut self.enrollment,
subscribe_cursor.as_deref(),
app_server_client_name,
connect_result = connect_remote_control_websocket_with_options(
ConnectRemoteControlWebsocketOptions {
remote_control_target: &remote_control_target,
state_db: self.state_db.as_deref(),
auth_manager: &self.auth_manager,
auth_recovery: &mut self.auth_recovery,
enrollment: &mut self.enrollment,
subscribe_cursor: subscribe_cursor.as_deref(),
app_server_client_name,
},
) => connect_result,
};
@@ -668,12 +703,11 @@ fn build_remote_control_websocket_request(
"x-codex-protocol-version",
REMOTE_CONTROL_PROTOCOL_VERSION,
)?;
set_remote_control_header(
headers,
"authorization",
&format!("Bearer {}", auth.bearer_token),
)?;
set_remote_control_header(headers, "authorization", &auth.authorization_header_value)?;
set_remote_control_header(headers, REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id)?;
if auth.is_fedramp_account {
set_remote_control_header(headers, REMOTE_CONTROL_FEDRAMP_HEADER, "true")?;
}
if let Some(subscribe_cursor) = subscribe_cursor {
set_remote_control_header(
headers,
@@ -718,8 +752,19 @@ pub(crate) async fn load_remote_control_auth(
));
}
let authorization_header_value = auth_manager
.chatgpt_authorization_header_for_auth(&auth)
.await
.ok_or_else(|| {
io::Error::new(
ErrorKind::PermissionDenied,
"remote control requires ChatGPT authentication",
)
})?;
Ok(RemoteControlConnectionAuth {
bearer_token: auth.get_token().map_err(io::Error::other)?,
authorization_header_value,
is_fedramp_account: auth.is_fedramp_account(),
account_id: auth.get_account_id().ok_or_else(|| {
io::Error::new(
ErrorKind::WouldBlock,
@@ -729,6 +774,7 @@ pub(crate) async fn load_remote_control_auth(
})
}
#[cfg(test)]
pub(super) async fn connect_remote_control_websocket(
remote_control_target: &RemoteControlTarget,
state_db: Option<&StateRuntime>,
@@ -741,6 +787,44 @@ pub(super) async fn connect_remote_control_websocket(
WebSocketStream<MaybeTlsStream<TcpStream>>,
tungstenite::http::Response<()>,
)> {
connect_remote_control_websocket_with_options(ConnectRemoteControlWebsocketOptions {
remote_control_target,
state_db,
auth_manager,
auth_recovery,
enrollment,
subscribe_cursor,
app_server_client_name,
})
.await
}
struct ConnectRemoteControlWebsocketOptions<'a> {
remote_control_target: &'a RemoteControlTarget,
state_db: Option<&'a StateRuntime>,
auth_manager: &'a Arc<AuthManager>,
auth_recovery: &'a mut UnauthorizedRecovery,
enrollment: &'a mut Option<RemoteControlEnrollment>,
subscribe_cursor: Option<&'a str>,
app_server_client_name: Option<&'a str>,
}
async fn connect_remote_control_websocket_with_options(
options: ConnectRemoteControlWebsocketOptions<'_>,
) -> io::Result<(
WebSocketStream<MaybeTlsStream<TcpStream>>,
tungstenite::http::Response<()>,
)> {
let ConnectRemoteControlWebsocketOptions {
remote_control_target,
state_db,
auth_manager,
auth_recovery,
enrollment,
subscribe_cursor,
app_server_client_name,
} = options;
ensure_rustls_crypto_provider();
let auth = load_remote_control_auth(auth_manager).await?;
@@ -1003,6 +1087,34 @@ mod tests {
}
}
#[test]
fn build_remote_control_websocket_request_includes_fedramp_header() {
let request = build_remote_control_websocket_request(
"ws://127.0.0.1/backend-api/wham/remote/control/server",
&RemoteControlEnrollment {
account_id: "account_id".to_string(),
environment_id: "env_test".to_string(),
server_id: "srv_e_test".to_string(),
server_name: "test-server".to_string(),
},
&RemoteControlConnectionAuth {
authorization_header_value: "AgentAssertion assertion".to_string(),
account_id: "account_id".to_string(),
is_fedramp_account: true,
},
/*subscribe_cursor*/ None,
)
.expect("request should build");
assert_eq!(
request
.headers()
.get(REMOTE_CONTROL_FEDRAMP_HEADER)
.and_then(|value| value.to_str().ok()),
Some("true")
);
}
#[tokio::test]
async fn connect_remote_control_websocket_includes_http_error_details() {
let listener = TcpListener::bind("127.0.0.1:0")
@@ -48,6 +48,7 @@ use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::ListMcpServerStatusParams;
use codex_app_server_protocol::LoginAccountParams;
use codex_app_server_protocol::MarketplaceAddParams;
use codex_app_server_protocol::MarketplaceRemoveParams;
use codex_app_server_protocol::McpResourceReadParams;
use codex_app_server_protocol::McpServerToolCallParams;
use codex_app_server_protocol::MockExperimentalMethodParams;
@@ -555,6 +556,15 @@ impl McpProcess {
self.send_request("marketplace/add", params).await
}
/// Send a `marketplace/remove` JSON-RPC request.
pub async fn send_marketplace_remove_request(
&mut self,
params: MarketplaceRemoveParams,
) -> anyhow::Result<i64> {
let params = Some(serde_json::to_value(params)?);
self.send_request("marketplace/remove", params).await
}
/// Send a `plugin/install` JSON-RPC request.
pub async fn send_plugin_install_request(
&mut self,
@@ -24,7 +24,7 @@ use std::collections::BTreeMap;
use tempfile::TempDir;
use tokio::time::timeout;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
#[tokio::test]
async fn experimental_feature_list_returns_feature_metadata_with_stage() -> Result<()> {
@@ -24,7 +24,9 @@ use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
// This covers debug app-server process startup before the first JSON-RPC response,
// not expected steady-state request latency.
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
#[tokio::test]
async fn initialize_uses_client_info_name_as_originator() -> Result<()> {
@@ -0,0 +1,115 @@
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use app_test_support::McpProcess;
use app_test_support::to_response;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::MarketplaceRemoveParams;
use codex_app_server_protocol::MarketplaceRemoveResponse;
use codex_app_server_protocol::RequestId;
use codex_config::MarketplaceConfigUpdate;
use codex_config::record_user_marketplace;
use codex_core::plugins::marketplace_install_root;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::time::timeout;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
fn configured_marketplace_update() -> MarketplaceConfigUpdate<'static> {
MarketplaceConfigUpdate {
last_updated: "2026-04-13T00:00:00Z",
last_revision: None,
source_type: "git",
source: "https://github.com/owner/repo.git",
ref_name: Some("main"),
sparse_paths: &[],
}
}
fn write_installed_marketplace(codex_home: &std::path::Path, marketplace_name: &str) -> Result<()> {
let root = marketplace_install_root(codex_home).join(marketplace_name);
std::fs::create_dir_all(root.join(".agents/plugins"))?;
std::fs::write(root.join(".agents/plugins/marketplace.json"), "{}")?;
Ok(())
}
fn canonicalize_path_with_existing_parent(path: &std::path::Path) -> Result<std::path::PathBuf> {
let parent = path
.parent()
.with_context(|| format!("path {} should have a parent", path.display()))?;
let file_name = path
.file_name()
.with_context(|| format!("path {} should have a file name", path.display()))?;
Ok(parent.canonicalize()?.join(file_name))
}
#[tokio::test]
async fn marketplace_remove_deletes_config_and_installed_root() -> Result<()> {
let codex_home = TempDir::new()?;
record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?;
write_installed_marketplace(codex_home.path(), "debug")?;
let installed_root = marketplace_install_root(codex_home.path()).join("debug");
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_marketplace_remove_request(MarketplaceRemoveParams {
marketplace_name: "debug".to_string(),
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: MarketplaceRemoveResponse = to_response(response)?;
assert_eq!(response.marketplace_name, "debug");
let removed_installed_root = response
.installed_root
.context("marketplace/remove should return removed installed root")?;
assert_eq!(
canonicalize_path_with_existing_parent(removed_installed_root.as_path())?,
canonicalize_path_with_existing_parent(&installed_root)?,
);
let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
assert!(!config.contains("[marketplaces.debug]"));
assert!(
!marketplace_install_root(codex_home.path())
.join("debug")
.exists()
);
Ok(())
}
#[tokio::test]
async fn marketplace_remove_rejects_unknown_marketplace() -> Result<()> {
let codex_home = TempDir::new()?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_marketplace_remove_request(MarketplaceRemoveParams {
marketplace_name: "debug".to_string(),
})
.await?;
let err = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(err.error.code, -32600);
assert_eq!(
err.error.message,
"marketplace `debug` is not configured or installed",
);
Ok(())
}
@@ -17,6 +17,7 @@ mod external_agent_config;
mod fs;
mod initialize;
mod marketplace_add;
mod marketplace_remove;
mod mcp_resource;
mod mcp_server_elicitation;
mod mcp_server_status;
@@ -93,6 +93,7 @@ async fn request_permissions_round_trip() -> Result<()> {
file_system: Some(codex_app_server_protocol::AdditionalFileSystemPermissions {
read: None,
write: Some(vec![requested_writes[0].clone()]),
entries: None,
}),
},
scope: PermissionGrantScope::Turn,
@@ -21,8 +21,8 @@ use tempfile::TempDir;
use tokio::time::timeout;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const REQUESTED_MODEL: &str = "gpt-5.1-codex-max";
const SERVER_MODEL: &str = "gpt-5.2-codex";
const REQUESTED_MODEL: &str = "gpt-5.4";
const SERVER_MODEL: &str = "gpt-5.3-codex";
#[tokio::test]
async fn openai_model_header_mismatch_emits_model_rerouted_notification_v2() -> Result<()> {
@@ -125,7 +125,7 @@ stream_max_retries = 0
async fn start_thread(mcp: &mut McpProcess) -> Result<String> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1".to_string()),
model: Some("gpt-5.2".to_string()),
..Default::default()
})
.await?;
@@ -131,7 +131,7 @@ async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
// Start a thread.
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -207,7 +207,7 @@ async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> {
let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?;
let event = thread_initialized_event(&payload)?;
assert_basic_thread_initialized_event(event, &thread.id, "gpt-5.2-codex", "resumed");
assert_basic_thread_initialized_event(event, &thread.id, "gpt-5.3-codex", "resumed");
Ok(())
}
@@ -556,7 +556,7 @@ async fn thread_resume_prefers_persisted_git_metadata_for_local_threads() -> Res
&config_toml,
format!(
r#"
model = "gpt-5.2-codex"
model = "gpt-5.3-codex"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -922,7 +922,7 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1029,7 +1029,7 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1145,7 +1145,7 @@ async fn thread_resume_rejects_mismatched_path_when_thread_is_running() -> Resul
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1251,7 +1251,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1320,7 +1320,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R
.await??;
let ThreadResumeResponse { thread, model, .. } =
to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(model, "gpt-5.1-codex-max");
assert_eq!(model, "gpt-5.4");
// The running-thread resume response is queued onto the thread listener task.
// If the in-flight turn completes before that queued command runs, the response
// can legitimately observe the thread as idle.
@@ -1364,7 +1364,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1501,7 +1501,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result<
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
})
@@ -1851,7 +1851,7 @@ async fn thread_resume_prefers_path_over_thread_id() -> Result<()> {
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -1971,7 +1971,7 @@ async fn start_materialized_thread_and_restart(
let start_id = first_mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1-codex-max".to_string()),
model: Some("gpt-5.4".to_string()),
..Default::default()
})
.await?;
@@ -2045,7 +2045,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let start_id = primary
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
@@ -2083,7 +2083,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> {
let resume_id = secondary
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id,
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
personality: Some(Personality::Friendly),
..Default::default()
})
@@ -2145,7 +2145,7 @@ fn create_config_toml(codex_home: &std::path::Path, server_uri: &str) -> std::io
config_toml,
format!(
r#"
model = "gpt-5.2-codex"
model = "gpt-5.3-codex"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -2182,7 +2182,7 @@ fn create_config_toml_with_chatgpt_base_url(
config_toml,
format!(
r#"
model = "gpt-5.2-codex"
model = "gpt-5.3-codex"
approval_policy = "never"
sandbox_mode = "read-only"
chatgpt_base_url = "{chatgpt_base_url}"
@@ -2213,7 +2213,7 @@ fn create_config_toml_with_required_broken_mcp(
config_toml,
format!(
r#"
model = "gpt-5.2-codex"
model = "gpt-5.3-codex"
approval_policy = "never"
sandbox_mode = "read-only"
@@ -64,7 +64,7 @@ async fn thread_start_creates_thread_and_emits_started() -> Result<()> {
// Start a v2 thread with an explicit model override.
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1".to_string()),
model: Some("gpt-5.2".to_string()),
..Default::default()
})
.await?;
@@ -414,7 +414,7 @@ async fn thread_start_ephemeral_remains_pathless() -> Result<()> {
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.1".to_string()),
model: Some("gpt-5.2".to_string()),
ephemeral: Some(true),
..Default::default()
})
@@ -24,6 +24,7 @@ use codex_app_server_protocol::CommandExecutionRequestApprovalResponse;
use codex_app_server_protocol::CommandExecutionStatus;
use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeOutputDeltaNotification;
use codex_app_server_protocol::FileChangePatchUpdatedNotification;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
use codex_app_server_protocol::ItemCompletedNotification;
use codex_app_server_protocol::ItemStartedNotification;
@@ -894,7 +895,7 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
@@ -977,7 +978,7 @@ async fn turn_start_uses_thread_feature_overrides_for_collaboration_mode_instruc
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
config: Some(HashMap::from([(
"features.default_mode_request_user_input".to_string(),
json!(true),
@@ -1268,7 +1269,7 @@ async fn turn_start_uses_migrated_pragmatic_personality_without_override_v2() ->
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
@@ -2026,6 +2027,248 @@ async fn turn_start_file_change_approval_v2() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
let codex_home = tmp.path().join("codex_home");
std::fs::create_dir(&codex_home)?;
let workspace = tmp.path().join("workspace");
std::fs::create_dir(&workspace)?;
let call_id = "patch-call";
let item_id = "fc-patch-call";
let patch = "*** Begin Patch\n*** Add File: live.txt\n+live line\n*** End Patch\n";
let patch_delta_1 = "*** Begin Patch\n*** Add File: live.txt\n+live";
let patch_delta_2 = " line\n*** End Patch\n";
let responses = vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
serde_json::json!({
"type": "response.output_item.added",
"item": {
"type": "custom_tool_call",
"id": item_id,
"call_id": call_id,
"name": "apply_patch",
"input": "",
"status": "in_progress"
}
}),
serde_json::json!({
"type": "response.custom_tool_call_input.delta",
"item_id": item_id,
"call_id": call_id,
"delta": patch_delta_1,
}),
serde_json::json!({
"type": "response.custom_tool_call_input.delta",
"item_id": item_id,
"call_id": call_id,
"delta": patch_delta_2,
}),
responses::ev_apply_patch_custom_tool_call(call_id, patch),
responses::ev_completed("resp-1"),
]),
create_final_assistant_message_sse_response("patch applied")?,
];
let server = create_mock_responses_server_sequence(responses).await;
create_config_toml(&codex_home, &server.uri(), "never", &BTreeMap::default())?;
let mut mcp = McpProcess::new(&codex_home).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
input: vec![V2UserInput::Text {
text: "apply patch".into(),
text_elements: Vec::new(),
}],
cwd: Some(workspace),
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_req)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
assert!(
!mcp.pending_notification_methods()
.iter()
.any(|method| method == "item/fileChange/patchUpdated")
);
Ok(())
}
#[tokio::test]
async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
let tmp = TempDir::new()?;
let codex_home = tmp.path().join("codex_home");
std::fs::create_dir(&codex_home)?;
let workspace = tmp.path().join("workspace");
std::fs::create_dir(&workspace)?;
let call_id = "patch-call";
let item_id = "fc-patch-call";
let patch = "*** Begin Patch\n*** Add File: live.txt\n+live line\n*** End Patch\n";
let patch_delta_1 = "*** Begin Patch\n*** Add File: live.txt\n+live";
let patch_delta_2 = " line\n*** End Patch\n";
let responses = vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
serde_json::json!({
"type": "response.output_item.added",
"item": {
"type": "function_call",
"id": "fc-other-call",
"call_id": "other-call",
"name": "not_apply_patch",
"arguments": "",
"status": "in_progress"
}
}),
serde_json::json!({
"type": "response.function_call_arguments.delta",
"item_id": "fc-other-call",
"delta": r#"{"input":"*** Begin Patch\n*** Add File: ignored.txt\n+ignored"#,
}),
serde_json::json!({
"type": "response.output_item.added",
"item": {
"type": "custom_tool_call",
"id": item_id,
"call_id": call_id,
"name": "apply_patch",
"input": "",
"status": "in_progress"
}
}),
serde_json::json!({
"type": "response.custom_tool_call_input.delta",
"item_id": item_id,
"call_id": call_id,
"delta": patch_delta_1,
}),
serde_json::json!({
"type": "response.custom_tool_call_input.delta",
"item_id": item_id,
"call_id": call_id,
"delta": patch_delta_2,
}),
responses::ev_apply_patch_custom_tool_call(call_id, patch),
responses::ev_completed("resp-1"),
]),
create_final_assistant_message_sse_response("patch applied")?,
];
let server = create_mock_responses_server_sequence(responses).await;
create_config_toml(
&codex_home,
&server.uri(),
"never",
&BTreeMap::from([
(Feature::ApplyPatchFreeform, true),
(Feature::ApplyPatchStreamingEvents, true),
(Feature::Plugins, false),
(Feature::RemoteModels, false),
(Feature::ShellSnapshot, false),
]),
)?;
let mut mcp = McpProcess::new(&codex_home).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
cwd: Some(workspace.to_string_lossy().into_owned()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: "apply patch".into(),
text_elements: Vec::new(),
}],
cwd: Some(workspace.clone()),
..Default::default()
})
.await?;
let turn_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_req)),
)
.await??;
let TurnStartResponse { turn } = to_response::<TurnStartResponse>(turn_resp)?;
let mut streamed_content = String::new();
while streamed_content != "live line\n" {
let delta_notif = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("item/fileChange/patchUpdated"),
)
.await??;
let delta: FileChangePatchUpdatedNotification = serde_json::from_value(
delta_notif
.params
.clone()
.expect("item/fileChange/patchUpdated params"),
)?;
assert_eq!(delta.thread_id, thread.id);
assert_eq!(delta.turn_id, turn.id);
assert_eq!(delta.item_id, call_id);
let change = delta
.changes
.iter()
.find(|change| change.path == "live.txt")
.expect("live.txt change");
assert!(matches!(change.kind, PatchChangeKind::Add));
streamed_content = change.diff.clone();
}
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
Ok(())
}
#[tokio::test]
async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -2033,7 +2276,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
const CHILD_PROMPT: &str = "child: do work";
const PARENT_PROMPT: &str = "spawn a child and continue";
const SPAWN_CALL_ID: &str = "spawn-call-1";
const REQUESTED_MODEL: &str = "gpt-5.1";
const REQUESTED_MODEL: &str = "gpt-5.2";
const REQUESTED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Low;
let server = responses::start_mock_server().await;
@@ -2088,7 +2331,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
@@ -2227,9 +2470,9 @@ async fn turn_start_emits_spawn_agent_item_with_effective_role_model_metadata_v2
const CHILD_PROMPT: &str = "child: do work";
const PARENT_PROMPT: &str = "spawn a child and continue";
const SPAWN_CALL_ID: &str = "spawn-call-1";
const REQUESTED_MODEL: &str = "gpt-5.1";
const REQUESTED_MODEL: &str = "gpt-5.2";
const REQUESTED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Low;
const ROLE_MODEL: &str = "gpt-5.1-codex-max";
const ROLE_MODEL: &str = "gpt-5.4";
const ROLE_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::High;
let server = responses::start_mock_server().await;
@@ -2302,7 +2545,7 @@ config_file = "./custom-role.toml"
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
+14 -10
View File
@@ -116,7 +116,7 @@ impl PathStyle {
pub struct Client {
base_url: String,
http: reqwest::Client,
bearer_token: Option<String>,
authorization_header_value: Option<String>,
user_agent: Option<HeaderValue>,
chatgpt_account_id: Option<String>,
chatgpt_account_is_fedramp: bool,
@@ -142,7 +142,7 @@ impl Client {
Ok(Self {
base_url,
http,
bearer_token: None,
authorization_header_value: None,
user_agent: None,
chatgpt_account_id: None,
chatgpt_account_is_fedramp: false,
@@ -165,7 +165,12 @@ impl Client {
}
pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
self.bearer_token = Some(token.into());
self.authorization_header_value = Some(format!("Bearer {}", token.into()));
self
}
pub fn with_authorization_header_value(mut self, value: impl Into<String>) -> Self {
self.authorization_header_value = Some(value.into());
self
}
@@ -198,11 +203,10 @@ impl Client {
} else {
h.insert(USER_AGENT, HeaderValue::from_static("codex-cli"));
}
if let Some(token) = &self.bearer_token {
let value = format!("Bearer {token}");
if let Ok(hv) = HeaderValue::from_str(&value) {
h.insert(AUTHORIZATION, hv);
}
if let Some(value) = &self.authorization_header_value
&& let Ok(hv) = HeaderValue::from_str(value)
{
h.insert(AUTHORIZATION, hv);
}
if let Some(acc) = &self.chatgpt_account_id
&& let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id")
@@ -816,7 +820,7 @@ mod tests {
let codex_client = Client {
base_url: "https://example.test".to_string(),
http: reqwest::Client::new(),
bearer_token: None,
authorization_header_value: None,
user_agent: None,
chatgpt_account_id: None,
chatgpt_account_is_fedramp: false,
@@ -830,7 +834,7 @@ mod tests {
let chatgpt_client = Client {
base_url: "https://chatgpt.com/backend-api".to_string(),
http: reqwest::Client::new(),
bearer_token: None,
authorization_header_value: None,
user_agent: None,
chatgpt_account_id: None,
chatgpt_account_is_fedramp: false,
+20 -3
View File
@@ -1,4 +1,5 @@
use codex_core::config::Config;
use codex_login::AuthManager;
use codex_login::default_client::create_client;
use crate::chatgpt_token::get_chatgpt_token_data;
@@ -31,16 +32,32 @@ pub(crate) async fn chatgpt_get_request_with_timeout<T: DeserializeOwned>(
let token =
get_chatgpt_token_data().ok_or_else(|| anyhow::anyhow!("ChatGPT token not available"))?;
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false);
let auth = auth_manager.auth().await;
let is_fedramp_account = auth
.as_ref()
.is_some_and(codex_login::CodexAuth::is_fedramp_account);
let authorization_header_value = match auth.as_ref() {
Some(auth) if auth.is_chatgpt_auth() => auth_manager
.chatgpt_authorization_header_for_auth(auth)
.await
.unwrap_or_else(|| format!("Bearer {}", token.access_token)),
_ => format!("Bearer {}", token.access_token),
};
let account_id = token.account_id.ok_or_else(|| {
anyhow::anyhow!("ChatGPT account ID not available, please re-run `codex login`")
});
})?;
let mut request = client
.get(&url)
.bearer_auth(&token.access_token)
.header("chatgpt-account-id", account_id?)
.header("authorization", authorization_header_value)
.header("chatgpt-account-id", account_id)
.header("Content-Type", "application/json");
if is_fedramp_account {
request = request.header("X-OpenAI-Fedramp", "true");
}
if let Some(timeout) = timeout {
request = request.timeout(timeout);
+1
View File
@@ -37,6 +37,7 @@ codex-features = { workspace = true }
codex-login = { workspace = true }
codex-mcp = { workspace = true }
codex-mcp-server = { workspace = true }
codex-models-manager = { workspace = true }
codex-model-provider = { workspace = true }
codex-protocol = { workspace = true }
codex-responses-api-proxy = { workspace = true }
+11 -7
View File
@@ -1,21 +1,25 @@
use clap::Parser;
use std::path::PathBuf;
const DEFAULT_CODEX_DMG_URL: &str = "https://persistent.oaistatic.com/codex-app-prod/Codex.dmg";
#[derive(Debug, Parser)]
pub struct AppCommand {
/// Workspace path to open in Codex Desktop.
#[arg(value_name = "PATH", default_value = ".")]
pub path: PathBuf,
/// Override the macOS DMG download URL (advanced).
#[arg(long, default_value = DEFAULT_CODEX_DMG_URL)]
pub download_url: String,
/// Override the app installer download URL (advanced).
#[arg(long = "download-url")]
pub download_url_override: Option<String>,
}
#[cfg(target_os = "macos")]
pub async fn run_app(cmd: AppCommand) -> anyhow::Result<()> {
let workspace = std::fs::canonicalize(&cmd.path).unwrap_or(cmd.path);
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url).await
#[cfg(target_os = "macos")]
{
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
}
#[cfg(target_os = "windows")]
{
crate::desktop_app::run_app_open_or_install(workspace, cmd.download_url_override).await
}
}
+36 -1
View File
@@ -1,12 +1,17 @@
use anyhow::Context as _;
use std::ffi::CString;
use std::path::Path;
use std::path::PathBuf;
use tempfile::Builder;
use tokio::process::Command;
const CODEX_DMG_URL_ARM64: &str = "https://persistent.oaistatic.com/codex-app-prod/Codex.dmg";
const CODEX_DMG_URL_X64: &str =
"https://persistent.oaistatic.com/codex-app-prod/Codex-latest-x64.dmg";
pub async fn run_mac_app_open_or_install(
workspace: PathBuf,
download_url: String,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
if let Some(app_path) = find_existing_codex_app_path() {
eprintln!(
@@ -17,6 +22,14 @@ pub async fn run_mac_app_open_or_install(
return Ok(());
}
eprintln!("Codex Desktop not found; downloading installer...");
let download_url = download_url_override.unwrap_or_else(|| {
let default_url = if is_apple_silicon_mac() {
CODEX_DMG_URL_ARM64
} else {
CODEX_DMG_URL_X64
};
default_url.to_string()
});
let installed_app = download_and_install_codex_to_user_applications(&download_url)
.await
.context("failed to download/install Codex Desktop")?;
@@ -28,6 +41,28 @@ pub async fn run_mac_app_open_or_install(
Ok(())
}
fn is_apple_silicon_mac() -> bool {
fn macos_sysctl_flag(name: &str) -> Option<bool> {
let name = CString::new(name).ok()?;
let mut value: libc::c_int = 0;
let mut size = std::mem::size_of_val(&value);
let result = unsafe {
libc::sysctlbyname(
name.as_ptr(),
(&mut value as *mut libc::c_int).cast::<libc::c_void>(),
&mut size,
std::ptr::null_mut(),
0,
)
};
(result == 0).then_some(value != 0)
}
std::env::consts::ARCH == "aarch64"
|| macos_sysctl_flag("sysctl.proc_translated").unwrap_or(false)
|| macos_sysctl_flag("hw.optional.arm64").unwrap_or(false)
}
fn find_existing_codex_app_path() -> Option<PathBuf> {
candidate_codex_app_paths()
.into_iter()
+13 -2
View File
@@ -1,11 +1,22 @@
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "windows")]
mod windows;
/// Run the app install/open logic for the current OS.
#[cfg(target_os = "macos")]
pub async fn run_app_open_or_install(
workspace: std::path::PathBuf,
download_url: String,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
mac::run_mac_app_open_or_install(workspace, download_url).await
mac::run_mac_app_open_or_install(workspace, download_url_override).await
}
/// Run the app install/open logic for the current OS.
#[cfg(target_os = "windows")]
pub async fn run_app_open_or_install(
workspace: std::path::PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
windows::run_windows_app_open_or_install(workspace, download_url_override).await
}
+132
View File
@@ -0,0 +1,132 @@
use anyhow::Context as _;
use std::path::Path;
use std::path::PathBuf;
use tokio::process::Command;
const CODEX_WINDOWS_INSTALLER_URL: &str =
"https://get.microsoft.com/installer/download/9PLM9XGG6VKS?cid=website_cta_psi";
const CODEX_MICROSOFT_STORE_WEB_URL: &str = "https://apps.microsoft.com/detail/9plm9xgg6vks";
pub async fn run_windows_app_open_or_install(
workspace: PathBuf,
download_url_override: Option<String>,
) -> anyhow::Result<()> {
if let Some(app_id) = find_codex_app_id().await? {
eprintln!("Opening Codex Desktop...");
open_installed_codex_app(&app_id).await?;
eprintln!(
"In Codex Desktop, open workspace {workspace}.",
workspace = display_workspace_path(&workspace)
);
return Ok(());
}
eprintln!("Codex Desktop not found; opening Windows installer...");
let download_url = download_url_override
.as_deref()
.unwrap_or(CODEX_WINDOWS_INSTALLER_URL);
if open_url(download_url).await.is_err() && download_url_override.is_none() {
open_url(CODEX_MICROSOFT_STORE_WEB_URL).await?;
}
eprintln!(
"After installing Codex Desktop, open workspace {workspace}.",
workspace = display_workspace_path(&workspace)
);
Ok(())
}
async fn find_codex_app_id() -> anyhow::Result<Option<String>> {
let output = Command::new("powershell.exe")
.arg("-NoProfile")
.arg("-Command")
.arg("Get-StartApps -Name 'Codex' | Select-Object -First 1 -ExpandProperty AppID")
.output()
.await
.context("failed to invoke `powershell.exe`")?;
if !output.status.success() {
return Ok(None);
}
let app_id = String::from_utf8_lossy(&output.stdout).trim().to_string();
if app_id.is_empty() {
Ok(None)
} else {
Ok(Some(app_id))
}
}
async fn open_installed_codex_app(app_id: &str) -> anyhow::Result<()> {
let target = format!("shell:AppsFolder\\{app_id}");
open_shell_target(&target).await
}
async fn open_url(url: &str) -> anyhow::Result<()> {
let status = Command::new("powershell.exe")
.arg("-NoProfile")
.arg("-Command")
.arg("& { param($target) Start-Process -FilePath $target }")
.arg(url)
.status()
.await
.with_context(|| format!("failed to open {url}"))?;
if status.success() {
Ok(())
} else {
anyhow::bail!("failed to open {url} with {status}");
}
}
async fn open_shell_target(target: &str) -> anyhow::Result<()> {
// Explorer can successfully hand off shell targets and still return exit code 1.
let _status = Command::new("explorer.exe")
.arg(target)
.status()
.await
.with_context(|| format!("failed to open {target}"))?;
Ok(())
}
fn display_workspace_path(workspace: &Path) -> String {
let path = workspace.display().to_string();
if let Some(path) = path.strip_prefix(r"\\?\UNC\") {
format!(r"\\{path}")
} else if let Some(path) = path.strip_prefix(r"\\?\") {
path.to_string()
} else {
path
}
}
#[cfg(test)]
mod tests {
use super::display_workspace_path;
use pretty_assertions::assert_eq;
use std::path::Path;
#[test]
fn display_workspace_path_removes_windows_extended_prefix() {
assert_eq!(
display_workspace_path(Path::new(r"\\?\C:\Users\fcoury\code\codex")),
r"C:\Users\fcoury\code\codex"
);
}
#[test]
fn display_workspace_path_preserves_unc_prefix() {
assert_eq!(
display_workspace_path(Path::new(r"\\?\UNC\server\share\codex")),
r"\\server\share\codex"
);
}
#[test]
fn display_workspace_path_leaves_regular_paths_unchanged() {
assert_eq!(
display_workspace_path(Path::new(r"C:\Users\fcoury\code\codex")),
r"C:\Users\fcoury\code\codex"
);
}
}
+72 -9
View File
@@ -34,9 +34,9 @@ use std::io::IsTerminal;
use std::path::PathBuf;
use supports_color::Stream;
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod app_cmd;
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod desktop_app;
mod marketplace_cmd;
mod mcp_cmd;
@@ -49,6 +49,7 @@ use crate::mcp_cmd::McpCli;
use crate::responses_cmd::ResponsesCommand;
use crate::responses_cmd::run_responses_command;
use codex_core::build_models_manager;
use codex_core::clear_memory_roots_contents;
use codex_core::config::Config;
use codex_core::config::ConfigOverrides;
@@ -57,6 +58,10 @@ use codex_core::config::find_codex_home;
use codex_features::FEATURES;
use codex_features::Stage;
use codex_features::is_known_feature_key;
use codex_models_manager::AuthManager;
use codex_models_manager::bundled_models_response;
use codex_models_manager::collaboration_mode_presets::CollaborationModesConfig;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::user_input::UserInput;
use codex_terminal_detection::TerminalName;
@@ -120,8 +125,8 @@ enum Subcommand {
/// [experimental] Run the app server or related tooling.
AppServer(AppServerCommand),
/// Launch the Codex desktop app (downloads the macOS installer if missing).
#[cfg(target_os = "macos")]
/// Launch the Codex desktop app (opens the app installer if missing).
#[cfg(any(target_os = "macos", target_os = "windows"))]
App(app_cmd::AppCommand),
/// Generate shell completion scripts.
@@ -200,6 +205,9 @@ struct DebugCommand {
#[derive(Debug, clap::Subcommand)]
enum DebugSubcommand {
/// Render the raw model catalog as JSON.
Models(DebugModelsCommand),
/// Tooling: helps debug the app server.
AppServer(DebugAppServerCommand),
@@ -240,6 +248,13 @@ struct DebugPromptInputCommand {
images: Vec<PathBuf>,
}
#[derive(Debug, Parser)]
struct DebugModelsCommand {
/// Skip refresh and dump only the bundled catalog shipped with this binary.
#[arg(long = "bundled", default_value_t = false)]
bundled: bool,
}
#[derive(Debug, Parser)]
struct ResumeCommand {
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
@@ -476,7 +491,6 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
let AppExitInfo {
token_usage,
thread_id: conversation_id,
thread_name,
..
} = exit_info;
@@ -489,7 +503,7 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
}
if let Some(resume_cmd) =
codex_core::util::resume_command(thread_name.as_deref(), conversation_id)
codex_core::util::resume_command(/*thread_name*/ None, conversation_id)
{
let command = if color_enabled {
resume_cmd.cyan().to_string()
@@ -808,7 +822,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
}
}
}
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "windows"))]
Some(Subcommand::App(app_cli)) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
@@ -991,6 +1005,14 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
}
},
Some(Subcommand::Debug(DebugCommand { subcommand })) => match subcommand {
DebugSubcommand::Models(cmd) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
"debug models",
)?;
run_debug_models_command(cmd, root_config_overrides).await?;
}
DebugSubcommand::AppServer(cmd) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
@@ -1280,6 +1302,31 @@ async fn run_debug_prompt_input_command(
Ok(())
}
async fn run_debug_models_command(
cmd: DebugModelsCommand,
root_config_overrides: CliConfigOverrides,
) -> anyhow::Result<()> {
let catalog = if cmd.bundled {
bundled_models_response()?
} else {
let cli_overrides = root_config_overrides
.parse_overrides()
.map_err(anyhow::Error::msg)?;
let config = Config::load_with_cli_overrides(cli_overrides).await?;
let auth_manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ true);
let models_manager =
build_models_manager(&config, auth_manager, CollaborationModesConfig::default());
models_manager
.raw_model_catalog(RefreshStrategy::OnlineIfUncached)
.await
};
serde_json::to_writer(std::io::stdout(), &catalog)?;
println!();
Ok(())
}
async fn run_debug_clear_memories_command(
root_config_overrides: &CliConfigOverrides,
interactive: &TuiCli,
@@ -1702,6 +1749,21 @@ mod tests {
);
}
#[test]
fn debug_models_parses_bundled_flag() {
let cli =
MultitoolCli::try_parse_from(["codex", "debug", "models", "--bundled"]).expect("parse");
let Some(Subcommand::Debug(DebugCommand {
subcommand: DebugSubcommand::Models(cmd),
})) = cli.subcommand
else {
panic!("expected debug models subcommand");
};
assert!(cmd.bundled);
}
#[test]
fn responses_subcommand_is_hidden_from_help_but_parses() {
let help = MultitoolCli::command().render_help().to_string();
@@ -1812,7 +1874,7 @@ mod tests {
}
#[test]
fn format_exit_messages_prefers_thread_name() {
fn format_exit_messages_uses_id_even_when_thread_has_name() {
let exit_info = sample_exit_info(
Some("123e4567-e89b-12d3-a456-426614174000"),
Some("my-thread"),
@@ -1822,7 +1884,8 @@ mod tests {
lines,
vec![
"Token usage: total=2 input=0 output=2".to_string(),
"To continue this session, run codex resume my-thread".to_string(),
"To continue this session, run codex resume 123e4567-e89b-12d3-a456-426614174000"
.to_string(),
]
);
}
+40
View File
@@ -0,0 +1,40 @@
use std::path::Path;
use anyhow::Result;
use tempfile::TempDir;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home);
Ok(cmd)
}
#[test]
fn debug_models_bundled_prints_json() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models", "--bundled"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}
#[test]
fn debug_models_default_prints_json_without_auth() -> Result<()> {
let codex_home = TempDir::new()?;
let mut cmd = codex_command(codex_home.path())?;
let output = cmd.args(["debug", "models"]).output()?;
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout)?;
let value: serde_json::Value = serde_json::from_str(&stdout)?;
assert!(value["models"].is_array());
assert!(!value["models"].as_array().unwrap_or(&Vec::new()).is_empty());
Ok(())
}
+1 -1
View File
@@ -55,7 +55,7 @@ async fn list_and_get_render_expected_output() -> Result<()> {
.expect("docs server should exist after add");
match &mut docs_entry.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => {
*env_vars = vec!["APP_TOKEN".to_string(), "WORKSPACE_ID".to_string()];
*env_vars = vec!["APP_TOKEN".into(), "WORKSPACE_ID".into()];
}
other => panic!("unexpected transport: {other:?}"),
}
+28 -5
View File
@@ -195,11 +195,15 @@ trait RequirementsFetcher: Send + Sync {
struct BackendRequirementsFetcher {
base_url: String,
auth_manager: Arc<AuthManager>,
}
impl BackendRequirementsFetcher {
fn new(base_url: String) -> Self {
Self { base_url }
fn new(auth_manager: Arc<AuthManager>, base_url: String) -> Self {
Self {
base_url,
auth_manager,
}
}
}
@@ -209,7 +213,14 @@ impl RequirementsFetcher for BackendRequirementsFetcher {
&self,
auth: &CodexAuth,
) -> Result<Option<String>, FetchAttemptError> {
let client = BackendClient::from_auth(self.base_url.clone(), auth)
let authorization_header_value = self
.auth_manager
.chatgpt_authorization_header_for_auth(auth)
.await;
let mut client = BackendClient::new(self.base_url.clone())
.map(|client| {
client.with_user_agent(codex_login::default_client::get_codex_user_agent())
})
.inspect_err(|err| {
tracing::warn!(
error = %err,
@@ -217,6 +228,15 @@ impl RequirementsFetcher for BackendRequirementsFetcher {
);
})
.map_err(|_| FetchAttemptError::Retryable(RetryableFailureKind::BackendClientInit))?;
if let Some(authorization_header_value) = authorization_header_value {
client = client.with_authorization_header_value(authorization_header_value);
}
if let Some(account_id) = auth.get_account_id() {
client = client.with_chatgpt_account_id(account_id);
}
if auth.is_fedramp_account() {
client = client.with_fedramp_routing_header();
}
let response = client
.get_config_requirements_file()
@@ -693,8 +713,11 @@ pub fn cloud_requirements_loader(
codex_home: PathBuf,
) -> CloudRequirementsLoader {
let service = CloudRequirementsService::new(
auth_manager,
Arc::new(BackendRequirementsFetcher::new(chatgpt_base_url)),
auth_manager.clone(),
Arc::new(BackendRequirementsFetcher::new(
auth_manager,
chatgpt_base_url,
)),
codex_home,
CLOUD_REQUIREMENTS_TIMEOUT,
);
+10
View File
@@ -37,6 +37,11 @@ impl HttpClient {
self
}
pub fn with_authorization_header_value(mut self, value: impl Into<String>) -> Self {
self.backend = self.backend.clone().with_authorization_header_value(value);
self
}
pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
self.backend = self.backend.clone().with_user_agent(ua);
self
@@ -47,6 +52,11 @@ impl HttpClient {
self
}
pub fn with_fedramp_routing_header(mut self) -> Self {
self.backend = self.backend.clone().with_fedramp_routing_header();
self
}
fn tasks_api(&self) -> api::Tasks<'_> {
api::Tasks::new(self)
}
+27 -25
View File
@@ -68,43 +68,45 @@ async fn init_backend(user_agent_suffix: &str) -> anyhow::Result<BackendContext>
};
append_error_log(format!("startup: base_url={base_url} path_style={style}"));
let auth_manager = util::load_auth_manager().await;
let auth = match auth_manager.as_ref() {
Some(manager) => manager.auth().await,
None => None,
let Some(auth_manager) = util::load_auth_manager(Some(base_url.clone())).await else {
eprintln!(
"Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'."
);
std::process::exit(1);
};
let auth = match auth {
Some(auth) => auth,
None => {
eprintln!(
"Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'."
);
std::process::exit(1);
}
let Some(auth) = auth_manager.auth().await else {
eprintln!(
"Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'."
);
std::process::exit(1);
};
if let Some(acc) = auth.get_account_id() {
append_error_log(format!("auth: mode=ChatGPT account_id={acc}"));
}
let token = match auth.get_token() {
Ok(t) if !t.is_empty() => t,
_ => {
eprintln!(
"Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'."
);
std::process::exit(1);
}
let authorization_header_value = auth_manager
.chatgpt_authorization_header_for_auth(&auth)
.await;
let Some(authorization_header_value) = authorization_header_value else {
eprintln!(
"Not signed in. Please run 'codex login' to sign in with ChatGPT, then re-run 'codex cloud'."
);
std::process::exit(1);
};
http = http.with_bearer_token(token.clone());
if let Some(acc) = auth
.get_account_id()
.or_else(|| util::extract_chatgpt_account_id(&token))
{
http = http.with_authorization_header_value(authorization_header_value);
if let Some(acc) = auth.get_account_id().or_else(|| {
auth.get_token()
.ok()
.and_then(|token| util::extract_chatgpt_account_id(&token))
}) {
append_error_log(format!("auth: set ChatGPT-Account-Id header: {acc}"));
http = http.with_chatgpt_account_id(acc);
}
if auth.is_fedramp_account() {
http = http.with_fedramp_routing_header();
}
Ok(BackendContext {
backend: Arc::new(http),
+30 -18
View File
@@ -3,6 +3,7 @@ use chrono::DateTime;
use chrono::Local;
use chrono::Utc;
use reqwest::header::HeaderMap;
use std::sync::Arc;
use codex_core::config::Config;
use codex_login::AuthManager;
@@ -59,18 +60,18 @@ pub fn extract_chatgpt_account_id(token: &str) -> Option<String> {
.map(str::to_string)
}
pub async fn load_auth_manager() -> Option<AuthManager> {
pub async fn load_auth_manager(chatgpt_base_url: Option<String>) -> Option<Arc<AuthManager>> {
// TODO: pass in cli overrides once cloud tasks properly support them.
let config = Config::load_with_cli_overrides(Vec::new()).await.ok()?;
Some(AuthManager::new(
config.codex_home.to_path_buf(),
/*enable_codex_api_key_env*/ false,
config.cli_auth_credentials_store_mode,
))
let auth_manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false);
if let Some(chatgpt_base_url) = chatgpt_base_url {
auth_manager.set_chatgpt_backend_base_url(Some(chatgpt_base_url));
}
Some(auth_manager)
}
/// Build headers for ChatGPT-backed requests: `User-Agent`, optional `Authorization`,
/// and optional `ChatGPT-Account-Id`.
/// Build headers for ChatGPT-backed requests.
pub async fn build_chatgpt_headers() -> HeaderMap {
use reqwest::header::AUTHORIZATION;
use reqwest::header::HeaderName;
@@ -84,23 +85,34 @@ pub async fn build_chatgpt_headers() -> HeaderMap {
USER_AGENT,
HeaderValue::from_str(&ua).unwrap_or(HeaderValue::from_static("codex-cli")),
);
if let Some(am) = load_auth_manager().await
&& let Some(auth) = am.auth().await
&& let Ok(tok) = auth.get_token()
&& !tok.is_empty()
let base_url = normalize_base_url(
&std::env::var("CODEX_CLOUD_TASKS_BASE_URL")
.unwrap_or_else(|_| "https://chatgpt.com/backend-api".to_string()),
);
if let Some(auth_manager) = load_auth_manager(Some(base_url)).await
&& let Some(auth) = auth_manager.auth().await
{
let v = format!("Bearer {tok}");
if let Ok(hv) = HeaderValue::from_str(&v) {
if let Some(authorization_header_value) = auth_manager
.chatgpt_authorization_header_for_auth(&auth)
.await
&& let Ok(hv) = HeaderValue::from_str(&authorization_header_value)
{
headers.insert(AUTHORIZATION, hv);
}
if let Some(acc) = auth
.get_account_id()
.or_else(|| extract_chatgpt_account_id(&tok))
&& let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id")
if let Some(acc) = auth.get_account_id().or_else(|| {
auth.get_token()
.ok()
.and_then(|token| extract_chatgpt_account_id(&token))
}) && let Ok(name) = HeaderName::from_bytes(b"ChatGPT-Account-Id")
&& let Ok(hv) = HeaderValue::from_str(&acc)
{
headers.insert(name, hv);
}
if auth.is_fedramp_account()
&& let Ok(name) = HeaderName::from_bytes(b"X-OpenAI-Fedramp")
{
headers.insert(name, HeaderValue::from_static("true"));
}
}
headers
}
+61
View File
@@ -308,6 +308,18 @@ mod tests {
ChatGptTestAuth
}
#[derive(Clone, Copy)]
struct AgentAssertionTestAuth;
impl AuthProvider for AgentAssertionTestAuth {
fn add_auth_headers(&self, headers: &mut reqwest::header::HeaderMap) {
headers.insert(
reqwest::header::AUTHORIZATION,
HeaderValue::from_static("AgentAssertion test-assertion"),
);
}
}
fn base_url_for(server: &MockServer) -> String {
format!("{}/backend-api", server.uri())
}
@@ -317,6 +329,7 @@ mod tests {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/backend-api/files"))
.and(header("authorization", "Bearer token"))
.and(header("chatgpt-account-id", "account_id"))
.and(body_json(serde_json::json!({
"file_name": "hello.txt",
@@ -377,4 +390,52 @@ mod tests {
assert_eq!(uploaded.mime_type, Some("text/plain".to_string()));
assert_eq!(finalize_attempts.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn upload_local_file_uses_authorization_header_value() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/backend-api/files"))
.and(header("authorization", "AgentAssertion test-assertion"))
.and(body_json(serde_json::json!({
"file_name": "hello.txt",
"file_size": 5,
"use_case": "codex",
})))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(serde_json::json!({"file_id": "file_123", "upload_url": format!("{}/upload/file_123", server.uri())})),
)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/upload/file_123"))
.and(header("content-length", "5"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/files/file_123/uploaded"))
.and(header("authorization", "AgentAssertion test-assertion"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"status": "success",
"download_url": format!("{}/download/file_123", server.uri()),
"file_name": "hello.txt",
"mime_type": "text/plain",
"file_size_bytes": 5
})))
.mount(&server)
.await;
let base_url = base_url_for(&server);
let dir = TempDir::new().expect("temp dir");
let path = dir.path().join("hello.txt");
tokio::fs::write(&path, b"hello").await.expect("write file");
let uploaded = upload_local_file(&base_url, &AgentAssertionTestAuth, &path)
.await
.expect("upload succeeds");
assert_eq!(uploaded.file_id, "file_123");
}
}
+1
View File
@@ -16,6 +16,7 @@ anyhow = { workspace = true }
async-channel = { workspace = true }
codex-async-utils = { workspace = true }
codex-config = { workspace = true }
codex-exec-server = { workspace = true }
codex-login = { workspace = true }
codex-otel = { workspace = true }
codex-plugin = { workspace = true }
+5
View File
@@ -16,15 +16,18 @@ pub use mcp::ToolPluginProvenance;
pub use mcp::canonical_mcp_server_key;
pub use mcp::collect_mcp_server_status_snapshot;
pub use mcp::collect_mcp_server_status_snapshot_with_detail;
pub use mcp::collect_mcp_server_status_snapshot_with_detail_and_authorization_header;
pub use mcp::collect_mcp_snapshot;
pub use mcp::collect_mcp_snapshot_from_manager;
pub use mcp::collect_mcp_snapshot_from_manager_with_detail;
pub use mcp::collect_mcp_snapshot_with_detail;
pub use mcp::collect_mcp_snapshot_with_detail_and_authorization_header;
pub use mcp::collect_missing_mcp_dependencies;
pub use mcp::compute_auth_statuses;
pub use mcp::configured_mcp_servers;
pub use mcp::discover_supported_scopes;
pub use mcp::effective_mcp_servers;
pub use mcp::effective_mcp_servers_with_authorization_header;
pub use mcp::group_tools_by_server;
pub use mcp::mcp_permission_prompt_is_auto_approved;
pub use mcp::oauth_login_support;
@@ -34,10 +37,12 @@ pub use mcp::should_retry_without_scopes;
pub use mcp::split_qualified_tool_name;
pub use mcp::tool_plugin_provenance;
pub use mcp::with_codex_apps_mcp;
pub use mcp::with_codex_apps_mcp_with_authorization_header;
pub use mcp_connection_manager::CodexAppsToolsCacheKey;
pub use mcp_connection_manager::DEFAULT_STARTUP_TIMEOUT;
pub use mcp_connection_manager::MCP_SANDBOX_STATE_META_CAPABILITY;
pub use mcp_connection_manager::McpConnectionManager;
pub use mcp_connection_manager::McpRuntimeEnvironment;
pub use mcp_connection_manager::SandboxState;
pub use mcp_connection_manager::ToolInfo;
pub use mcp_connection_manager::codex_apps_tools_cache_key;
+107 -11
View File
@@ -35,6 +35,7 @@ use codex_protocol::protocol::SandboxPolicy;
use serde_json::Value;
use crate::mcp_connection_manager::McpConnectionManager;
use crate::mcp_connection_manager::McpRuntimeEnvironment;
use crate::mcp_connection_manager::codex_apps_tools_cache_key;
pub type McpManager = McpConnectionManager;
@@ -212,14 +213,25 @@ fn codex_apps_mcp_bearer_token(auth: Option<&CodexAuth>) -> Option<String> {
}
}
fn codex_apps_mcp_http_headers(auth: Option<&CodexAuth>) -> Option<HashMap<String, String>> {
fn codex_apps_mcp_http_headers(
auth: Option<&CodexAuth>,
authorization_header_value: Option<&str>,
) -> Option<HashMap<String, String>> {
let mut headers = HashMap::new();
if let Some(token) = codex_apps_mcp_bearer_token(auth) {
if let Some(authorization_header_value) = authorization_header_value {
headers.insert(
"Authorization".to_string(),
authorization_header_value.to_string(),
);
} else if let Some(token) = codex_apps_mcp_bearer_token(auth) {
headers.insert("Authorization".to_string(), format!("Bearer {token}"));
}
if let Some(account_id) = auth.and_then(CodexAuth::get_account_id) {
headers.insert("ChatGPT-Account-ID".to_string(), account_id);
}
if auth.is_some_and(CodexAuth::is_fedramp_account) {
headers.insert("X-OpenAI-Fedramp".to_string(), "true".to_string());
}
if headers.is_empty() {
None
} else {
@@ -253,12 +265,16 @@ pub(crate) fn codex_apps_mcp_url(config: &McpConfig) -> String {
codex_apps_mcp_url_for_base_url(&config.chatgpt_base_url)
}
fn codex_apps_mcp_server_config(config: &McpConfig, auth: Option<&CodexAuth>) -> McpServerConfig {
fn codex_apps_mcp_server_config(
config: &McpConfig,
auth: Option<&CodexAuth>,
authorization_header_value: Option<&str>,
) -> McpServerConfig {
let bearer_token_env_var = codex_apps_mcp_bearer_token_env_var();
let http_headers = if bearer_token_env_var.is_some() {
None
} else {
codex_apps_mcp_http_headers(auth)
codex_apps_mcp_http_headers(auth, authorization_header_value)
};
let url = codex_apps_mcp_url(config);
@@ -286,14 +302,25 @@ fn codex_apps_mcp_server_config(config: &McpConfig, auth: Option<&CodexAuth>) ->
}
pub fn with_codex_apps_mcp(
servers: HashMap<String, McpServerConfig>,
auth: Option<&CodexAuth>,
config: &McpConfig,
) -> HashMap<String, McpServerConfig> {
with_codex_apps_mcp_with_authorization_header(
servers, auth, config, /*authorization_header_value*/ None,
)
}
pub fn with_codex_apps_mcp_with_authorization_header(
mut servers: HashMap<String, McpServerConfig>,
auth: Option<&CodexAuth>,
config: &McpConfig,
authorization_header_value: Option<&str>,
) -> HashMap<String, McpServerConfig> {
if config.apps_enabled && auth.is_some_and(CodexAuth::is_chatgpt_auth) {
servers.insert(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
codex_apps_mcp_server_config(config, auth),
codex_apps_mcp_server_config(config, auth, authorization_header_value),
);
} else {
servers.remove(CODEX_APPS_MCP_SERVER_NAME);
@@ -308,9 +335,19 @@ pub fn configured_mcp_servers(config: &McpConfig) -> HashMap<String, McpServerCo
pub fn effective_mcp_servers(
config: &McpConfig,
auth: Option<&CodexAuth>,
) -> HashMap<String, McpServerConfig> {
effective_mcp_servers_with_authorization_header(
config, auth, /*authorization_header_value*/ None,
)
}
pub fn effective_mcp_servers_with_authorization_header(
config: &McpConfig,
auth: Option<&CodexAuth>,
authorization_header_value: Option<&str>,
) -> HashMap<String, McpServerConfig> {
let servers = configured_mcp_servers(config);
with_codex_apps_mcp(servers, auth, config)
with_codex_apps_mcp_with_authorization_header(servers, auth, config, authorization_header_value)
}
pub fn tool_plugin_provenance(config: &McpConfig) -> ToolPluginProvenance {
@@ -321,17 +358,46 @@ pub async fn collect_mcp_snapshot(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
) -> McpListToolsResponseEvent {
collect_mcp_snapshot_with_detail(config, auth, submit_id, McpSnapshotDetail::Full).await
collect_mcp_snapshot_with_detail(
config,
auth,
submit_id,
runtime_environment,
McpSnapshotDetail::Full,
)
.await
}
pub async fn collect_mcp_snapshot_with_detail(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
detail: McpSnapshotDetail,
) -> McpListToolsResponseEvent {
let mcp_servers = effective_mcp_servers(config, auth);
collect_mcp_snapshot_with_detail_and_authorization_header(
config,
auth,
submit_id,
runtime_environment,
detail,
/*authorization_header_value*/ None,
)
.await
}
pub async fn collect_mcp_snapshot_with_detail_and_authorization_header(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
detail: McpSnapshotDetail,
authorization_header_value: Option<&str>,
) -> McpListToolsResponseEvent {
let mcp_servers =
effective_mcp_servers_with_authorization_header(config, auth, authorization_header_value);
let tool_plugin_provenance = tool_plugin_provenance(config);
if mcp_servers.is_empty() {
return McpListToolsResponseEvent {
@@ -356,6 +422,7 @@ pub async fn collect_mcp_snapshot_with_detail(
submit_id,
tx_event,
SandboxPolicy::new_read_only_policy(),
runtime_environment,
config.codex_home.clone(),
codex_apps_tools_cache_key(auth),
tool_plugin_provenance,
@@ -386,18 +453,46 @@ pub async fn collect_mcp_server_status_snapshot(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
) -> McpServerStatusSnapshot {
collect_mcp_server_status_snapshot_with_detail(config, auth, submit_id, McpSnapshotDetail::Full)
.await
collect_mcp_server_status_snapshot_with_detail(
config,
auth,
submit_id,
runtime_environment,
McpSnapshotDetail::Full,
)
.await
}
pub async fn collect_mcp_server_status_snapshot_with_detail(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
detail: McpSnapshotDetail,
) -> McpServerStatusSnapshot {
let mcp_servers = effective_mcp_servers(config, auth);
collect_mcp_server_status_snapshot_with_detail_and_authorization_header(
config,
auth,
submit_id,
runtime_environment,
detail,
/*authorization_header_value*/ None,
)
.await
}
pub async fn collect_mcp_server_status_snapshot_with_detail_and_authorization_header(
config: &McpConfig,
auth: Option<&CodexAuth>,
submit_id: String,
runtime_environment: McpRuntimeEnvironment,
detail: McpSnapshotDetail,
authorization_header_value: Option<&str>,
) -> McpServerStatusSnapshot {
let mcp_servers =
effective_mcp_servers_with_authorization_header(config, auth, authorization_header_value);
let tool_plugin_provenance = tool_plugin_provenance(config);
if mcp_servers.is_empty() {
return McpServerStatusSnapshot {
@@ -422,6 +517,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail(
submit_id,
tx_event,
SandboxPolicy::new_read_only_policy(),
runtime_environment,
config.codex_home.clone(),
codex_apps_tools_cache_key(auth),
tool_plugin_provenance,
@@ -36,6 +36,7 @@ use codex_async_utils::CancelErr;
use codex_async_utils::OrCancelExt;
use codex_config::Constrained;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::Environment;
use codex_protocol::ToolName;
use codex_protocol::approvals::ElicitationRequest;
use codex_protocol::approvals::ElicitationRequestEvent;
@@ -50,6 +51,7 @@ use codex_protocol::protocol::McpStartupStatus;
use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_protocol::protocol::SandboxPolicy;
use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::ExecutorStdioServerLauncher;
use codex_rmcp_client::LocalStdioServerLauncher;
use codex_rmcp_client::RmcpClient;
use codex_rmcp_client::SendElicitation;
@@ -493,6 +495,7 @@ impl AsyncManagedClient {
elicitation_requests: ElicitationRequestManager,
codex_apps_tools_cache_context: Option<CodexAppsToolsCacheContext>,
tool_plugin_provenance: Arc<ToolPluginProvenance>,
runtime_environment: McpRuntimeEnvironment,
) -> Self {
let tool_filter = ToolFilter::from_config(&config);
let startup_snapshot = load_startup_cached_codex_apps_tools_snapshot(
@@ -509,8 +512,15 @@ impl AsyncManagedClient {
return Err(error.into());
}
let client =
Arc::new(make_rmcp_client(&server_name, config.transport, store_mode).await?);
let client = Arc::new(
make_rmcp_client(
&server_name,
config.clone(),
store_mode,
runtime_environment,
)
.await?,
);
match start_server_task(
server_name,
client,
@@ -650,6 +660,37 @@ pub struct McpConnectionManager {
elicitation_requests: ElicitationRequestManager,
}
/// Runtime placement information used when starting MCP server transports.
///
/// `McpConfig` describes what servers exist. This value describes where those
/// servers should run for the current caller. Keep it explicit at manager
/// construction time so status/snapshot paths and real sessions make the same
/// local-vs-remote decision. `fallback_cwd` is not a per-server override; it is
/// used only when an executor-backed stdio server omits `cwd` and the executor
/// API still needs a concrete process working directory.
#[derive(Clone)]
pub struct McpRuntimeEnvironment {
environment: Arc<Environment>,
fallback_cwd: PathBuf,
}
impl McpRuntimeEnvironment {
pub fn new(environment: Arc<Environment>, fallback_cwd: PathBuf) -> Self {
Self {
environment,
fallback_cwd,
}
}
fn environment(&self) -> Arc<Environment> {
Arc::clone(&self.environment)
}
fn fallback_cwd(&self) -> PathBuf {
self.fallback_cwd.clone()
}
}
impl McpConnectionManager {
pub fn configured_servers(&self, config: &McpConfig) -> HashMap<String, McpServerConfig> {
configured_mcp_servers(config)
@@ -710,6 +751,7 @@ impl McpConnectionManager {
submit_id: String,
tx_event: Sender<Event>,
initial_sandbox_policy: SandboxPolicy,
runtime_environment: McpRuntimeEnvironment,
codex_home: PathBuf,
codex_apps_tools_cache_key: CodexAppsToolsCacheKey,
tool_plugin_provenance: ToolPluginProvenance,
@@ -754,6 +796,7 @@ impl McpConnectionManager {
elicitation_requests.clone(),
codex_apps_tools_cache_context,
Arc::clone(&tool_plugin_provenance),
runtime_environment.clone(),
);
clients.insert(server_name.clone(), async_managed_client.clone());
let tx_event = tx_event.clone();
@@ -1484,9 +1527,25 @@ struct StartServerTaskParams {
async fn make_rmcp_client(
server_name: &str,
transport: McpServerTransportConfig,
config: McpServerConfig,
store_mode: OAuthCredentialsStoreMode,
runtime_environment: McpRuntimeEnvironment,
) -> Result<RmcpClient, StartupOutcomeError> {
let McpServerConfig {
transport,
experimental_environment,
..
} = config;
let remote_environment = match experimental_environment.as_deref() {
None | Some("local") => false,
Some("remote") => true,
Some(environment) => {
return Err(StartupOutcomeError::from(anyhow!(
"unsupported experimental_environment `{environment}` for MCP server `{server_name}`"
)));
}
};
match transport {
McpServerTransportConfig::Stdio {
command,
@@ -1502,7 +1561,24 @@ async fn make_rmcp_client(
.map(|(key, value)| (key.into(), value.into()))
.collect::<HashMap<_, _>>()
});
let launcher = Arc::new(LocalStdioServerLauncher) as Arc<dyn StdioServerLauncher>;
let launcher = if remote_environment {
let exec_environment = runtime_environment.environment();
if !exec_environment.is_remote() {
return Err(StartupOutcomeError::from(anyhow!(
"remote MCP server `{server_name}` requires a remote executor environment"
)));
}
Arc::new(ExecutorStdioServerLauncher::new(
exec_environment.get_exec_backend(),
runtime_environment.fallback_cwd(),
))
} else {
Arc::new(LocalStdioServerLauncher) as Arc<dyn StdioServerLauncher>
};
// `RmcpClient` always sees a launched MCP stdio server. The
// launcher hides whether that means a local child process or an
// executor process whose stdin/stdout bytes cross the process API.
RmcpClient::new_stdio_client(command_os, args_os, env_os, &env_vars, cwd, launcher)
.await
.map_err(|err| StartupOutcomeError::from(anyhow!(err)))
@@ -1513,6 +1589,23 @@ async fn make_rmcp_client(
env_http_headers,
bearer_token_env_var,
} => {
if remote_environment {
if !runtime_environment.environment().is_remote() {
return Err(StartupOutcomeError::from(anyhow!(
"remote MCP server `{server_name}` requires a remote executor environment"
)));
}
return Err(StartupOutcomeError::from(anyhow!(
// Remote HTTP needs the future low-level executor
// `network/request` API so reqwest runs on the executor side.
// Do not fall back to local HTTP here; the config explicitly
// asked for remote placement.
"remote streamable HTTP MCP server `{server_name}` is not implemented yet"
)));
}
// Local streamable HTTP remains the existing reqwest path from
// the orchestrator process.
let resolved_bearer_token =
match resolve_bearer_token(server_name, bearer_token_env_var.as_deref()) {
Ok(token) => token,
+1
View File
@@ -72,6 +72,7 @@ pub use mcp_edit::load_global_mcp_servers;
pub use mcp_types::AppToolApproval;
pub use mcp_types::McpServerConfig;
pub use mcp_types::McpServerDisabledReason;
pub use mcp_types::McpServerEnvVar;
pub use mcp_types::McpServerToolConfig;
pub use mcp_types::McpServerTransportConfig;
pub use mcp_types::RawMcpServerConfig;
+20 -1
View File
@@ -14,6 +14,7 @@ use toml_edit::value;
use crate::AppToolApproval;
use crate::CONFIG_TOML_FILE;
use crate::McpServerConfig;
use crate::McpServerEnvVar;
use crate::McpServerTransportConfig;
pub async fn load_global_mcp_servers(
@@ -142,7 +143,7 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem {
entry["env"] = table_from_pairs(env.iter());
}
if !env_vars.is_empty() {
entry["env_vars"] = array_from_strings(env_vars);
entry["env_vars"] = array_from_env_vars(env_vars);
}
if let Some(cwd) = cwd {
entry["cwd"] = value(cwd.to_string_lossy().to_string());
@@ -247,6 +248,24 @@ fn array_from_strings(values: &[String]) -> TomlItem {
TomlItem::Value(array.into())
}
fn array_from_env_vars(env_vars: &[McpServerEnvVar]) -> TomlItem {
let mut array = toml_edit::Array::new();
for env_var in env_vars {
match env_var {
McpServerEnvVar::Name(name) => array.push(name.clone()),
McpServerEnvVar::Config { name, source } => {
let mut table = toml_edit::InlineTable::new();
table.insert("name", name.clone().into());
if let Some(source) = source {
table.insert("source", source.clone().into());
}
array.push(table);
}
}
}
TomlItem::Value(array.into())
}
fn table_from_pairs<'a, I>(pairs: I) -> TomlItem
where
I: IntoIterator<Item = (&'a String, &'a String)>,
+65 -3
View File
@@ -56,6 +56,64 @@ pub struct McpServerToolConfig {
pub approval_mode: Option<AppToolApproval>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[serde(untagged, deny_unknown_fields)]
pub enum McpServerEnvVar {
Name(String),
Config {
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
source: Option<String>,
},
}
impl McpServerEnvVar {
pub fn name(&self) -> &str {
match self {
McpServerEnvVar::Name(name) => name,
McpServerEnvVar::Config { name, .. } => name,
}
}
pub fn source(&self) -> Option<&str> {
match self {
McpServerEnvVar::Name(_) => None,
McpServerEnvVar::Config { source, .. } => source.as_deref(),
}
}
pub fn is_remote_source(&self) -> bool {
self.source() == Some("remote")
}
pub fn validate_source(&self) -> Result<(), String> {
match self.source() {
None | Some("local") | Some("remote") => Ok(()),
Some(source) => Err(format!(
"unsupported env_vars source `{source}`; expected `local` or `remote`"
)),
}
}
}
impl From<String> for McpServerEnvVar {
fn from(value: String) -> Self {
Self::Name(value)
}
}
impl From<&str> for McpServerEnvVar {
fn from(value: &str) -> Self {
Self::Name(value.to_string())
}
}
impl AsRef<str> for McpServerEnvVar {
fn as_ref(&self) -> &str {
self.name()
}
}
#[derive(Serialize, Debug, Clone, PartialEq)]
pub struct McpServerConfig {
#[serde(flatten)]
@@ -133,7 +191,7 @@ pub struct RawMcpServerConfig {
#[serde(default)]
pub env: Option<HashMap<String, String>>,
#[serde(default)]
pub env_vars: Option<Vec<String>>,
pub env_vars: Option<Vec<McpServerEnvVar>>,
#[serde(default)]
pub cwd: Option<PathBuf>,
pub http_headers: Option<HashMap<String, String>>,
@@ -235,11 +293,15 @@ impl TryFrom<RawMcpServerConfig> for McpServerConfig {
throw_if_set("stdio", "http_headers", http_headers.as_ref())?;
throw_if_set("stdio", "env_http_headers", env_http_headers.as_ref())?;
throw_if_set("stdio", "oauth_resource", oauth_resource.as_ref())?;
let env_vars = env_vars.unwrap_or_default();
for env_var in &env_vars {
env_var.validate_source()?;
}
McpServerTransportConfig::Stdio {
command,
args: args.unwrap_or_default(),
env,
env_vars: env_vars.unwrap_or_default(),
env_vars,
cwd,
}
} else if let Some(url) = url {
@@ -303,7 +365,7 @@ pub enum McpServerTransportConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
env: Option<HashMap<String, String>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
env_vars: Vec<String>,
env_vars: Vec<McpServerEnvVar>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cwd: Option<PathBuf>,
},
+54 -1
View File
@@ -91,12 +91,65 @@ fn deserialize_stdio_command_server_config_with_env_vars() {
command: "echo".to_string(),
args: vec![],
env: None,
env_vars: vec!["FOO".to_string(), "BAR".to_string()],
env_vars: vec!["FOO".into(), "BAR".into()],
cwd: None,
}
);
}
#[test]
fn deserialize_stdio_command_server_config_with_env_var_sources() {
let cfg: McpServerConfig = toml::from_str(
r#"
command = "echo"
env_vars = [
"LEGACY_TOKEN",
{ name = "LOCAL_TOKEN", source = "local" },
{ name = "REMOTE_TOKEN", source = "remote" },
]
"#,
)
.expect("should deserialize command config with sourced env_vars");
assert_eq!(
cfg.transport,
McpServerTransportConfig::Stdio {
command: "echo".to_string(),
args: vec![],
env: None,
env_vars: vec![
McpServerEnvVar::Name("LEGACY_TOKEN".to_string()),
McpServerEnvVar::Config {
name: "LOCAL_TOKEN".to_string(),
source: Some("local".to_string()),
},
McpServerEnvVar::Config {
name: "REMOTE_TOKEN".to_string(),
source: Some("remote".to_string()),
},
],
cwd: None,
}
);
}
#[test]
fn deserialize_stdio_command_server_config_rejects_unknown_env_var_source() {
let err = toml::from_str::<McpServerConfig>(
r#"
command = "echo"
env_vars = [{ name = "TOKEN", source = "elsewhere" }]
"#,
)
.expect_err("unsupported env var source should be rejected");
assert!(
err.to_string()
.contains("unsupported env_vars source `elsewhere`"),
"unexpected error: {err}"
);
}
#[test]
fn deserialize_stdio_command_server_config_with_cwd() {
let cfg: McpServerConfig = toml::from_str(
+4
View File
@@ -27,6 +27,10 @@ pub struct SkillsConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bundled: Option<BundledSkillsConfig>,
/// Whether turns receive the automatic skills instructions block.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub include_instructions: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config: Vec<SkillConfig>,
}
+24
View File
@@ -18,6 +18,8 @@ use toml::Value as TomlValue;
#[derive(Debug, Default, Clone)]
pub struct LoaderOverrides {
pub managed_config_path: Option<PathBuf>,
pub ignore_user_config: bool,
pub ignore_user_and_project_exec_policy_rules: bool,
//TODO(gt): Add a macos_ prefix to this field and remove the target_os check.
#[cfg(target_os = "macos")]
pub managed_preferences_base64: Option<String>,
@@ -42,6 +44,8 @@ impl LoaderOverrides {
pub fn with_managed_config_path_for_tests(managed_config_path: PathBuf) -> Self {
Self {
managed_config_path: Some(managed_config_path),
ignore_user_config: false,
ignore_user_and_project_exec_policy_rules: false,
#[cfg(target_os = "macos")]
managed_preferences_base64: Some(String::new()),
macos_managed_config_requirements_base64: Some(String::new()),
@@ -157,6 +161,9 @@ pub struct ConfigLayerStack {
/// sources. This preserves the original allow-lists so they can be
/// surfaced via APIs.
requirements_toml: ConfigRequirementsToml,
/// Whether execpolicy should skip `.rules` files from user and project config-layer folders.
ignore_user_and_project_exec_policy_rules: bool,
}
impl ConfigLayerStack {
@@ -171,9 +178,22 @@ impl ConfigLayerStack {
user_layer_index,
requirements,
requirements_toml,
ignore_user_and_project_exec_policy_rules: false,
})
}
pub fn with_user_and_project_exec_policy_rules_ignored(
mut self,
ignore_user_and_project_exec_policy_rules: bool,
) -> Self {
self.ignore_user_and_project_exec_policy_rules = ignore_user_and_project_exec_policy_rules;
self
}
pub fn ignore_user_and_project_exec_policy_rules(&self) -> bool {
self.ignore_user_and_project_exec_policy_rules
}
/// Returns the raw user config layer, if any.
///
/// This does not merge other config layers or apply any requirements.
@@ -211,6 +231,8 @@ impl ConfigLayerStack {
user_layer_index: self.user_layer_index,
requirements: self.requirements.clone(),
requirements_toml: self.requirements_toml.clone(),
ignore_user_and_project_exec_policy_rules: self
.ignore_user_and_project_exec_policy_rules,
}
}
None => {
@@ -232,6 +254,8 @@ impl ConfigLayerStack {
user_layer_index: Some(user_layer_index),
requirements: self.requirements.clone(),
requirements_toml: self.requirements_toml.clone(),
ignore_user_and_project_exec_policy_rules: self
.ignore_user_and_project_exec_policy_rules,
}
}
}
+1
View File
@@ -6,6 +6,7 @@
pub use crate::mcp_types::AppToolApproval;
pub use crate::mcp_types::McpServerConfig;
pub use crate::mcp_types::McpServerDisabledReason;
pub use crate::mcp_types::McpServerEnvVar;
pub use crate::mcp_types::McpServerToolConfig;
pub use crate::mcp_types::McpServerTransportConfig;
pub use crate::mcp_types::RawMcpServerConfig;
+7
View File
@@ -418,6 +418,9 @@ mod tests {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
static ALL_CONNECTORS_CACHE_TEST_LOCK: LazyLock<tokio::sync::Mutex<()>> =
LazyLock::new(|| tokio::sync::Mutex::new(()));
fn cache_key(id: &str) -> AllConnectorsCacheKey {
AllConnectorsCacheKey::new(
"https://chatgpt.example".to_string(),
@@ -444,6 +447,8 @@ mod tests {
#[tokio::test]
async fn list_all_connectors_uses_shared_cache() -> anyhow::Result<()> {
let _cache_guard = ALL_CONNECTORS_CACHE_TEST_LOCK.lock().await;
let calls = Arc::new(AtomicUsize::new(0));
let call_counter = Arc::clone(&calls);
let key = cache_key("shared");
@@ -482,6 +487,8 @@ mod tests {
#[tokio::test]
async fn list_all_connectors_merges_and_normalizes_directory_apps() -> anyhow::Result<()> {
let _cache_guard = ALL_CONNECTORS_CACHE_TEST_LOCK.lock().await;
let key = cache_key("merged");
let calls = Arc::new(AtomicUsize::new(0));
let call_counter = Arc::clone(&calls);
+25 -6
View File
@@ -6,7 +6,9 @@ use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use codex_login::BackgroundAgentTaskAuthMode;
use codex_login::CodexAuth;
use codex_login::cached_background_agent_task_authorization_header_value;
use codex_login::default_client::build_reqwest_client;
const REMOTE_SKILLS_API_TIMEOUT: Duration = Duration::from_secs(30);
@@ -112,13 +114,15 @@ pub async fn list_remote_skills(
.get(&url)
.timeout(REMOTE_SKILLS_API_TIMEOUT)
.query(&query_params);
let token = auth
.get_token()
let authorization_header_value = authorization_header_value_for_auth(auth)
.context("Failed to read auth token for remote skills")?;
request = request.bearer_auth(token);
request = request.header("authorization", authorization_header_value);
if let Some(account_id) = auth.get_account_id() {
request = request.header("chatgpt-account-id", account_id);
}
if auth.is_fedramp_account() {
request = request.header("X-OpenAI-Fedramp", "true");
}
let response = request
.send()
.await
@@ -157,13 +161,15 @@ pub async fn export_remote_skill(
let url = format!("{base_url}/hazelnuts/{skill_id}/export");
let mut request = client.get(&url).timeout(REMOTE_SKILLS_API_TIMEOUT);
let token = auth
.get_token()
let authorization_header_value = authorization_header_value_for_auth(auth)
.context("Failed to read auth token for remote skills")?;
request = request.bearer_auth(token);
request = request.header("authorization", authorization_header_value);
if let Some(account_id) = auth.get_account_id() {
request = request.header("chatgpt-account-id", account_id);
}
if auth.is_fedramp_account() {
request = request.header("X-OpenAI-Fedramp", "true");
}
let response = request
.send()
@@ -201,6 +207,19 @@ pub async fn export_remote_skill(
})
}
fn authorization_header_value_for_auth(auth: &CodexAuth) -> std::io::Result<String> {
if let Ok(Some(authorization_header_value)) =
cached_background_agent_task_authorization_header_value(
auth,
BackgroundAgentTaskAuthMode::Disabled,
)
{
Ok(authorization_header_value)
} else {
auth.get_token().map(|token| format!("Bearer {token}"))
}
}
fn safe_join(base: &Path, name: &str) -> Result<PathBuf> {
let path = Path::new(name);
for component in path.components() {
+39 -1
View File
@@ -344,6 +344,9 @@
"child_agents_md": {
"type": "boolean"
},
"chronicle": {
"type": "boolean"
},
"code_mode": {
"type": "boolean"
},
@@ -538,6 +541,9 @@
},
"workspace_dependencies": {
"type": "boolean"
},
"workspace_owner_usage_nudge": {
"type": "boolean"
}
},
"type": "object"
@@ -876,6 +882,28 @@
],
"type": "string"
},
"McpServerEnvVar": {
"anyOf": [
{
"type": "string"
},
{
"additionalProperties": false,
"properties": {
"name": {
"type": "string"
},
"source": {
"type": "string"
}
},
"required": [
"name"
],
"type": "object"
}
]
},
"McpServerToolConfig": {
"additionalProperties": false,
"description": "Per-tool approval settings for a single MCP server tool.",
@@ -1570,7 +1598,7 @@
"env_vars": {
"default": null,
"items": {
"type": "string"
"$ref": "#/definitions/McpServerEnvVar"
},
"type": "array"
},
@@ -1880,6 +1908,10 @@
"$ref": "#/definitions/SkillConfig"
},
"type": "array"
},
"include_instructions": {
"description": "Whether turns receive the automatic skills instructions block.",
"type": "boolean"
}
},
"type": "object"
@@ -2290,6 +2322,9 @@
"child_agents_md": {
"type": "boolean"
},
"chronicle": {
"type": "boolean"
},
"code_mode": {
"type": "boolean"
},
@@ -2484,6 +2519,9 @@
},
"workspace_dependencies": {
"type": "boolean"
},
"workspace_owner_usage_nudge": {
"type": "boolean"
}
},
"type": "object"
File diff suppressed because one or more lines are too long
+10
View File
@@ -116,6 +116,7 @@ fn keep_forked_rollout_item(item: &RolloutItem) -> bool {
| ResponseItem::Compaction { .. }
| ResponseItem::Other,
) => false,
RolloutItem::SessionState(_) => false,
RolloutItem::Compacted(_)
| RolloutItem::EventMsg(_)
| RolloutItem::SessionMeta(_)
@@ -147,6 +148,15 @@ impl AgentControl {
}
}
/// Create a control-plane handle over the same thread manager with an independent live-agent
/// registry.
pub(crate) fn detached_registry(&self) -> Self {
Self {
manager: self.manager.clone(),
..Default::default()
}
}
/// Spawn a new agent thread and submit the initial prompt.
pub(crate) async fn spawn_agent(
&self,
+1 -1
View File
@@ -83,7 +83,7 @@ async fn apply_explorer_role_sets_model_and_adds_session_flags_layer() {
.await
.expect("explorer role should apply");
assert_eq!(config.model.as_deref(), Some("gpt-5.1-codex-mini"));
assert_eq!(config.model.as_deref(), Some("gpt-5.4-mini"));
assert_eq!(config.model_reasoning_effort, Some(ReasoningEffort::Medium));
assert_eq!(session_flags_layer_count(&config), before_layers + 1);
}
+54 -16
View File
@@ -22,17 +22,17 @@ use rand::TryRngCore;
use rand::rngs::OsRng;
use serde::Deserialize;
use serde::Serialize;
use tokio::sync::Mutex;
use tokio::sync::Semaphore;
use tracing::debug;
use tracing::info;
use tracing::warn;
use crate::config::Config;
mod task_registration;
pub(crate) use task_registration::RegisteredAgentTask;
use crate::config::Config;
const AGENT_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15);
const AGENT_IDENTITY_BISCUIT_TIMEOUT: Duration = Duration::from_secs(15);
@@ -42,7 +42,7 @@ pub(crate) struct AgentIdentityManager {
chatgpt_base_url: String,
feature_enabled: bool,
abom: AgentBillOfMaterials,
ensure_lock: Arc<Mutex<()>>,
ensure_lock: Arc<Semaphore>,
}
impl std::fmt::Debug for AgentIdentityManager {
@@ -110,7 +110,7 @@ impl AgentIdentityManager {
chatgpt_base_url: config.chatgpt_base_url.clone(),
feature_enabled: config.features.enabled(Feature::UseAgentIdentity),
abom: build_abom(session_source),
ensure_lock: Arc::new(Mutex::new(())),
ensure_lock: Arc::new(Semaphore::new(/*permits*/ 1)),
}
}
@@ -137,7 +137,11 @@ impl AgentIdentityManager {
auth: &CodexAuth,
binding: &AgentIdentityBinding,
) -> Result<StoredAgentIdentity> {
let _guard = self.ensure_lock.lock().await;
let _guard = self
.ensure_lock
.acquire()
.await
.map_err(|_| anyhow::anyhow!("agent identity ensure semaphore closed"))?;
if let Some(stored_identity) = self.load_stored_identity(auth, binding)? {
info!(
@@ -153,14 +157,16 @@ impl AgentIdentityManager {
Ok(stored_identity)
}
pub(crate) async fn task_matches_current_binding(&self, task: &RegisteredAgentTask) -> bool {
pub(crate) async fn task_matches_current_identity(&self, task: &RegisteredAgentTask) -> bool {
if !self.feature_enabled {
return false;
}
self.current_auth_binding()
self.current_stored_identity()
.await
.is_some_and(|(_, binding)| task.matches_binding(&binding))
.is_some_and(|stored_identity| {
stored_identity.agent_runtime_id == task.agent_runtime_id
})
}
async fn current_auth_binding(&self) -> Option<(CodexAuth, AgentIdentityBinding)> {
@@ -177,6 +183,11 @@ impl AgentIdentityManager {
binding.map(|binding| (auth, binding))
}
async fn current_stored_identity(&self) -> Option<StoredAgentIdentity> {
let (auth, binding) = self.current_auth_binding().await?;
self.load_stored_identity(&auth, &binding).ok().flatten()
}
async fn register_agent_identity(
&self,
binding: &AgentIdentityBinding,
@@ -328,7 +339,7 @@ impl AgentIdentityManager {
}
#[cfg(test)]
fn new_for_tests(
pub(crate) fn new_for_tests(
auth_manager: Arc<AuthManager>,
feature_enabled: bool,
chatgpt_base_url: String,
@@ -339,9 +350,33 @@ impl AgentIdentityManager {
chatgpt_base_url,
feature_enabled,
abom: build_abom(session_source),
ensure_lock: Arc::new(Mutex::new(())),
ensure_lock: Arc::new(Semaphore::new(/*permits*/ 1)),
}
}
#[cfg(test)]
pub(crate) async fn seed_generated_identity_for_tests(
&self,
agent_runtime_id: &str,
) -> Result<StoredAgentIdentity> {
let (auth, binding) = self
.current_auth_binding()
.await
.context("test agent identity requires ChatGPT auth")?;
let key_material = generate_agent_key_material()?;
let stored_identity = StoredAgentIdentity {
binding_id: binding.binding_id.clone(),
chatgpt_account_id: binding.chatgpt_account_id.clone(),
chatgpt_user_id: binding.chatgpt_user_id,
agent_runtime_id: agent_runtime_id.to_string(),
private_key_pkcs8_base64: key_material.private_key_pkcs8_base64,
public_key_ssh: key_material.public_key_ssh,
registered_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
abom: self.abom.clone(),
};
self.store_identity(&auth, &stored_identity)?;
Ok(stored_identity)
}
}
impl StoredAgentIdentity {
@@ -377,6 +412,7 @@ impl StoredAgentIdentity {
agent_runtime_id: self.agent_runtime_id.clone(),
agent_private_key: self.private_key_pkcs8_base64.clone(),
registered_at: self.registered_at.clone(),
background_task_id: None,
}
}
@@ -572,7 +608,7 @@ mod tests {
.and(path("/v1/agent/register"))
.and(header("x-openai-authorization", "human-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"agent_runtime_id": "agent_123",
"agent_runtime_id": "agent-123",
})))
.expect(1)
.mount(&server)
@@ -598,7 +634,7 @@ mod tests {
.unwrap()
.expect("identity should be reused");
assert_eq!(first.agent_runtime_id, "agent_123");
assert_eq!(first.agent_runtime_id, "agent-123");
assert_eq!(first, second);
assert_eq!(first.abom.agent_harness_id, "codex-cli");
assert_eq!(first.chatgpt_account_id, "account-123");
@@ -614,7 +650,7 @@ mod tests {
.and(path("/v1/agent/register"))
.and(header("x-openai-authorization", "human-biscuit"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"agent_runtime_id": "agent_456",
"agent_runtime_id": "agent-456",
})))
.expect(1)
.mount(&server)
@@ -637,6 +673,7 @@ mod tests {
agent_runtime_id: "agent_invalid".to_string(),
agent_private_key: "not-valid-base64".to_string(),
registered_at: "2026-01-01T00:00:00Z".to_string(),
background_task_id: None,
})
.expect("seed invalid identity");
@@ -646,11 +683,11 @@ mod tests {
.unwrap()
.expect("identity should be registered");
assert_eq!(stored.agent_runtime_id, "agent_456");
assert_eq!(stored.agent_runtime_id, "agent-456");
let persisted = auth
.get_agent_identity(&binding.chatgpt_account_id)
.expect("stored identity");
assert_eq!(persisted.agent_runtime_id, "agent_456");
assert_eq!(persisted.agent_runtime_id, "agent-456");
}
#[tokio::test]
@@ -676,6 +713,7 @@ mod tests {
agent_runtime_id: "agent_old".to_string(),
agent_private_key: stale_key.private_key_pkcs8_base64,
registered_at: "2026-01-01T00:00:00Z".to_string(),
background_task_id: None,
})
.expect("seed stale identity");
@@ -2,6 +2,8 @@ use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use codex_login::AgentTaskAuthorizationTarget;
use codex_protocol::protocol::SessionAgentTask;
use crypto_box::SecretKey as Curve25519SecretKey;
use ed25519_dalek::Signer as _;
use serde::Deserialize;
@@ -16,9 +18,6 @@ const AGENT_TASK_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RegisteredAgentTask {
pub(crate) binding_id: String,
pub(crate) chatgpt_account_id: String,
pub(crate) chatgpt_user_id: Option<String>,
pub(crate) agent_runtime_id: String,
pub(crate) task_id: String,
pub(crate) registered_at: String,
@@ -82,9 +81,6 @@ impl AgentIdentityManager {
.await
.with_context(|| format!("failed to parse agent task response from {url}"))?;
let registered_task = RegisteredAgentTask {
binding_id: stored_identity.binding_id.clone(),
chatgpt_account_id: stored_identity.chatgpt_account_id.clone(),
chatgpt_user_id: stored_identity.chatgpt_user_id.clone(),
agent_runtime_id: stored_identity.agent_runtime_id.clone(),
task_id: decrypt_task_id_response(
&stored_identity,
@@ -107,18 +103,27 @@ impl AgentIdentityManager {
}
impl RegisteredAgentTask {
pub(super) fn matches_binding(&self, binding: &AgentIdentityBinding) -> bool {
binding.matches_parts(
&self.binding_id,
&self.chatgpt_account_id,
self.chatgpt_user_id.as_deref(),
)
pub(crate) fn authorization_target(&self) -> AgentTaskAuthorizationTarget<'_> {
AgentTaskAuthorizationTarget {
agent_runtime_id: &self.agent_runtime_id,
task_id: &self.task_id,
}
}
pub(crate) fn has_same_binding(&self, other: &Self) -> bool {
self.binding_id == other.binding_id
&& self.chatgpt_account_id == other.chatgpt_account_id
&& self.chatgpt_user_id == other.chatgpt_user_id
pub(crate) fn to_session_agent_task(&self) -> SessionAgentTask {
SessionAgentTask {
agent_runtime_id: self.agent_runtime_id.clone(),
task_id: self.task_id.clone(),
registered_at: self.registered_at.clone(),
}
}
pub(crate) fn from_session_agent_task(task: SessionAgentTask) -> Self {
Self {
agent_runtime_id: task.agent_runtime_id,
task_id: task.task_id,
registered_at: task.registered_at,
}
}
}
@@ -242,9 +247,6 @@ mod tests {
assert_eq!(
task,
RegisteredAgentTask {
binding_id: "chatgpt-account-account-123".to_string(),
chatgpt_account_id: "account-123".to_string(),
chatgpt_user_id: Some("user-123".to_string()),
agent_runtime_id: "agent-123".to_string(),
task_id: "task_123".to_string(),
registered_at: task.registered_at.clone(),
@@ -331,9 +333,6 @@ mod tests {
assert_eq!(
task,
RegisteredAgentTask {
binding_id: "chatgpt-account-account-123".to_string(),
chatgpt_account_id: "account-123".to_string(),
chatgpt_user_id: Some("user-123".to_string()),
agent_runtime_id: "agent-123".to_string(),
task_id: "task_123".to_string(),
registered_at: task.registered_at.clone(),
@@ -342,7 +341,7 @@ mod tests {
}
#[tokio::test]
async fn task_matches_current_binding_rejects_stale_auth_binding() {
async fn task_matches_current_identity_rejects_stale_registered_identity() {
let auth_manager =
AuthManager::from_auth_for_testing(make_chatgpt_auth("account-456", Some("user-456")));
let manager = AgentIdentityManager::new_for_tests(
@@ -352,15 +351,12 @@ mod tests {
SessionSource::Cli,
);
let task = RegisteredAgentTask {
binding_id: "chatgpt-account-account-123".to_string(),
chatgpt_account_id: "account-123".to_string(),
chatgpt_user_id: Some("user-123".to_string()),
agent_runtime_id: "agent-123".to_string(),
task_id: "task_123".to_string(),
registered_at: "2026-03-23T12:00:00Z".to_string(),
};
assert!(!manager.task_matches_current_binding(&task).await);
assert!(!manager.task_matches_current_identity(&task).await);
}
async fn mount_human_biscuit(
+26 -6
View File
@@ -13,6 +13,7 @@ use codex_login::CodexAuth;
use codex_login::default_client::build_reqwest_client;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::ResponseItem;
use reqwest::header::AUTHORIZATION;
const ARC_MONITOR_TIMEOUT: Duration = Duration::from_secs(30);
const CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE: &str = "CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE";
@@ -109,13 +110,31 @@ pub(crate) async fn monitor_action(
},
None => None,
};
let token = if let Some(token) = read_non_empty_env_var(CODEX_ARC_MONITOR_TOKEN) {
token
let (authorization_header_value, account_id) = if let Some(token) =
read_non_empty_env_var(CODEX_ARC_MONITOR_TOKEN)
{
(
format!("Bearer {token}"),
auth.as_ref().and_then(CodexAuth::get_account_id),
)
} else if let Some(authorization_header_value) =
match sess.authorization_header_for_current_agent_task().await {
Ok(authorization_header_value) => authorization_header_value,
Err(err) => {
warn!(
error = %err,
"skipping safety monitor because agent assertion authorization is unavailable"
);
return ArcMonitorOutcome::Ok;
}
}
{
(authorization_header_value, None)
} else {
let Some(auth) = auth.as_ref() else {
return ArcMonitorOutcome::Ok;
};
match auth.get_token() {
let token = match auth.get_token() {
Ok(token) => token,
Err(err) => {
warn!(
@@ -124,7 +143,8 @@ pub(crate) async fn monitor_action(
);
return ArcMonitorOutcome::Ok;
}
}
};
(format!("Bearer {token}"), auth.get_account_id())
};
let url = read_non_empty_env_var(CODEX_ARC_MONITOR_ENDPOINT_OVERRIDE).unwrap_or_else(|| {
@@ -147,8 +167,8 @@ pub(crate) async fn monitor_action(
.post(&url)
.timeout(ARC_MONITOR_TIMEOUT)
.json(&body)
.bearer_auth(token);
if let Some(account_id) = auth.as_ref().and_then(CodexAuth::get_account_id) {
.header(AUTHORIZATION, authorization_header_value);
if let Some(account_id) = account_id {
request = request.header("chatgpt-account-id", account_id);
}
+146
View File
@@ -9,17 +9,37 @@ use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::header_regex;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::agent_identity::AgentIdentityManager;
use crate::agent_identity::RegisteredAgentTask;
use crate::session::tests::make_session_and_context;
use chrono::Utc;
use codex_login::AuthCredentialsStoreMode;
use codex_login::AuthDotJson;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::save_auth;
use codex_login::token_data::IdTokenInfo;
use codex_login::token_data::TokenData;
use codex_protocol::models::ContentItem;
use codex_protocol::models::LocalShellAction;
use codex_protocol::models::LocalShellExecAction;
use codex_protocol::models::LocalShellStatus;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::SessionSource;
use tempfile::tempdir;
const TEST_ID_TOKEN: &str = concat!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.",
"eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lk",
"IjpudWxsLCJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2NvdW50X2lkIn19.",
"c2ln",
);
struct EnvVarGuard {
key: &'static str,
@@ -49,6 +69,58 @@ impl Drop for EnvVarGuard {
}
}
async fn install_cached_agent_task_auth(
session: &mut Session,
turn_context: &mut TurnContext,
chatgpt_base_url: String,
) {
let auth_dir = tempdir().expect("temp auth dir");
let auth_json = AuthDotJson {
auth_mode: Some(codex_app_server_protocol::AuthMode::Chatgpt),
openai_api_key: None,
tokens: Some(TokenData {
id_token: IdTokenInfo {
email: None,
chatgpt_plan_type: None,
chatgpt_user_id: None,
chatgpt_account_id: Some("account_id".to_string()),
chatgpt_account_is_fedramp: false,
raw_jwt: TEST_ID_TOKEN.to_string(),
},
access_token: "Access Token".to_string(),
refresh_token: "test".to_string(),
account_id: Some("account_id".to_string()),
}),
last_refresh: Some(Utc::now()),
agent_identity: None,
};
save_auth(auth_dir.path(), &auth_json, AuthCredentialsStoreMode::File).expect("save test auth");
let auth = CodexAuth::from_auth_storage(auth_dir.path(), AuthCredentialsStoreMode::File)
.expect("load test auth")
.expect("test auth");
let auth_manager = AuthManager::from_auth_for_testing(auth);
let agent_identity_manager = Arc::new(AgentIdentityManager::new_for_tests(
Arc::clone(&auth_manager),
/*feature_enabled*/ true,
chatgpt_base_url,
SessionSource::Exec,
));
let stored_identity = agent_identity_manager
.seed_generated_identity_for_tests("agent-123")
.await
.expect("seed test identity");
session.services.auth_manager = Arc::clone(&auth_manager);
session.services.agent_identity_manager = agent_identity_manager;
turn_context.auth_manager = Some(auth_manager);
session
.cache_agent_task_for_tests(RegisteredAgentTask {
agent_runtime_id: stored_identity.agent_runtime_id,
task_id: "task-123".to_string(),
registered_at: "2026-04-15T00:00:00Z".to_string(),
})
.await;
}
#[tokio::test]
async fn build_arc_monitor_request_includes_relevant_history_and_null_policies() {
let (session, mut turn_context) = make_session_and_context().await;
@@ -247,6 +319,80 @@ async fn build_arc_monitor_request_includes_relevant_history_and_null_policies()
);
}
#[tokio::test]
#[serial(arc_monitor_env)]
async fn monitor_action_uses_agent_assertion_for_cached_task() {
let server = MockServer::start().await;
let (mut session, mut turn_context) = make_session_and_context().await;
install_cached_agent_task_auth(&mut session, &mut turn_context, server.uri()).await;
let mut config = (*turn_context.config).clone();
config.chatgpt_base_url = server.uri();
turn_context.config = Arc::new(config);
session
.record_into_history(
&[ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "please run the tool".to_string(),
}],
end_turn: None,
phase: None,
}],
&turn_context,
)
.await;
Mock::given(method("POST"))
.and(path("/codex/safety/arc"))
.and(header_regex("authorization", r"^AgentAssertion .+"))
.and(body_json(serde_json::json!({
"metadata": {
"codex_thread_id": session.conversation_id.to_string(),
"codex_turn_id": turn_context.sub_id.clone(),
"conversation_id": session.conversation_id.to_string(),
"protection_client_callsite": "normal",
},
"messages": [{
"role": "user",
"content": [{
"type": "input_text",
"text": "please run the tool",
}],
}],
"policies": {
"developer": null,
"user": null,
},
"action": {
"tool": "mcp_tool_call",
},
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"outcome": "ok",
"short_reason": "",
"rationale": "",
"risk_score": 1,
"risk_level": "low",
"evidence": [],
})))
.expect(1)
.mount(&server)
.await;
let outcome = monitor_action(
&session,
&turn_context,
serde_json::json!({ "tool": "mcp_tool_call" }),
"normal",
)
.await;
assert_eq!(outcome, ArcMonitorOutcome::Ok);
}
#[tokio::test]
#[serial(arc_monitor_env)]
async fn monitor_action_posts_expected_arc_request() {
+98 -15
View File
@@ -31,6 +31,7 @@ use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::agent_identity::RegisteredAgentTask;
use codex_api::ApiError;
use codex_api::AuthProvider;
use codex_api::CompactClient as ApiCompactClient;
@@ -95,6 +96,7 @@ use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;
use tokio_tungstenite::tungstenite::Error;
use tokio_tungstenite::tungstenite::Message;
use tracing::debug;
use tracing::instrument;
use tracing::trace;
use tracing::warn;
@@ -109,6 +111,7 @@ use codex_feedback::FeedbackRequestTags;
use codex_feedback::emit_feedback_request_tags_with_auth_env;
use codex_login::auth_env_telemetry::AuthEnvTelemetry;
use codex_login::auth_env_telemetry::collect_auth_env_telemetry;
use codex_model_provider::AuthorizationHeaderAuthProvider;
use codex_model_provider::SharedModelProvider;
use codex_model_provider::create_model_provider;
#[cfg(test)]
@@ -128,6 +131,7 @@ pub const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state";
pub const X_CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata";
pub const X_CODEX_PARENT_THREAD_ID_HEADER: &str = "x-codex-parent-thread-id";
pub const X_CODEX_WINDOW_ID_HEADER: &str = "x-codex-window-id";
pub const X_OPENAI_MEMGEN_REQUEST_HEADER: &str = "x-openai-memgen-request";
pub const X_OPENAI_SUBAGENT_HEADER: &str = "x-openai-subagent";
pub const X_RESPONSESAPI_INCLUDE_TIMING_METRICS_HEADER: &str =
"x-responsesapi-include-timing-metrics";
@@ -212,6 +216,8 @@ pub struct ModelClient {
pub struct ModelClientSession {
client: ModelClient,
websocket_session: WebsocketSession,
agent_task: Option<RegisteredAgentTask>,
cache_websocket_session_on_drop: bool,
/// Turn state for sticky routing.
///
/// This is an `OnceLock` that stores the turn state value received from the server
@@ -329,9 +335,25 @@ impl ModelClient {
/// This constructor does not perform network I/O itself; the session opens a websocket lazily
/// when the first stream request is issued.
pub fn new_session(&self) -> ModelClientSession {
self.new_session_with_agent_task(/*agent_task*/ None)
}
pub(crate) fn new_session_with_agent_task(
&self,
agent_task: Option<RegisteredAgentTask>,
) -> ModelClientSession {
let cache_websocket_session_on_drop = agent_task.is_none();
let websocket_session = if agent_task.is_some() {
drop(self.take_cached_websocket_session());
WebsocketSession::default()
} else {
self.take_cached_websocket_session()
};
ModelClientSession {
client: self.clone(),
websocket_session: self.take_cached_websocket_session(),
websocket_session,
agent_task,
cache_websocket_session_on_drop,
turn_state: Arc::new(OnceLock::new()),
}
}
@@ -414,7 +436,7 @@ impl ModelClient {
if prompt.input.is_empty() {
return Ok(Vec::new());
}
let client_setup = self.current_client_setup().await?;
let client_setup = self.current_client_setup(/*agent_task*/ None).await?;
let transport = ReqwestTransport::new(build_reqwest_client());
let request_telemetry = Self::build_request_telemetry(
session_telemetry,
@@ -478,7 +500,7 @@ impl ModelClient {
) -> Result<RealtimeWebrtcCallStart> {
// Create the media call over HTTP first, then retain matching auth so realtime can attach
// the server-side control WebSocket to the call id from that HTTP response.
let client_setup = self.current_client_setup().await?;
let client_setup = self.current_client_setup(/*agent_task*/ None).await?;
let mut sideband_headers = extra_headers.clone();
sideband_headers.extend(sideband_websocket_auth_headers(
client_setup.api_auth.as_ref(),
@@ -513,7 +535,7 @@ impl ModelClient {
return Ok(Vec::new());
}
let client_setup = self.current_client_setup().await?;
let client_setup = self.current_client_setup(/*agent_task*/ None).await?;
let transport = ReqwestTransport::new(build_reqwest_client());
let request_telemetry = Self::build_request_telemetry(
session_telemetry,
@@ -551,6 +573,15 @@ impl ModelClient {
{
extra_headers.insert(X_OPENAI_SUBAGENT_HEADER, val);
}
if matches!(
self.state.session_source,
SessionSource::SubAgent(SubAgentSource::MemoryConsolidation)
) {
extra_headers.insert(
X_OPENAI_MEMGEN_REQUEST_HEADER,
HeaderValue::from_static("true"),
);
}
extra_headers
}
@@ -654,10 +685,46 @@ impl ModelClient {
///
/// This centralizes setup used by both prewarm and normal request paths so they stay in
/// lockstep when auth/provider resolution changes.
async fn current_client_setup(&self) -> Result<CurrentClientSetup> {
async fn current_client_setup(
&self,
agent_task: Option<&RegisteredAgentTask>,
) -> Result<CurrentClientSetup> {
let auth = self.state.provider.auth().await;
let api_provider = self.state.provider.api_provider().await?;
let api_auth = self.state.provider.api_auth().await?;
let auth_manager = self.state.provider.auth_manager();
let api_auth = match (agent_task, auth_manager.as_ref(), auth.as_ref()) {
(Some(agent_task), Some(auth_manager), Some(auth)) => {
if let Some(authorization_header_value) = auth_manager
.chatgpt_agent_task_authorization_header_for_auth(
auth,
agent_task.authorization_target(),
)
.map_err(|err| {
CodexErr::Stream(
format!("failed to build agent assertion authorization: {err}"),
None,
)
})?
{
debug!(
agent_runtime_id = %agent_task.agent_runtime_id,
task_id = %agent_task.task_id,
"using agent assertion authorization for downstream request"
);
let mut auth_provider = AuthorizationHeaderAuthProvider::new(
Some(authorization_header_value),
/*account_id*/ None,
);
if auth.is_fedramp_account() {
auth_provider = auth_provider.with_fedramp_routing_header();
}
Arc::new(auth_provider)
} else {
self.state.provider.api_auth().await?
}
}
_ => self.state.provider.api_auth().await?,
};
Ok(CurrentClientSetup {
auth,
api_provider,
@@ -791,12 +858,18 @@ impl ModelClient {
impl Drop for ModelClientSession {
fn drop(&mut self) {
let websocket_session = std::mem::take(&mut self.websocket_session);
self.client
.store_cached_websocket_session(websocket_session);
if self.cache_websocket_session_on_drop {
self.client
.store_cached_websocket_session(websocket_session);
}
}
}
impl ModelClientSession {
pub(crate) fn disable_cached_websocket_session_on_drop(&mut self) {
self.cache_websocket_session_on_drop = false;
}
pub(crate) fn reset_websocket_session(&mut self) {
self.websocket_session.connection = None;
self.websocket_session.last_request = None;
@@ -998,11 +1071,15 @@ impl ModelClientSession {
return Ok(());
}
let client_setup = self.client.current_client_setup().await.map_err(|err| {
ApiError::Stream(format!(
"failed to build websocket prewarm client setup: {err}"
))
})?;
let client_setup = self
.client
.current_client_setup(self.agent_task.as_ref())
.await
.map_err(|err| {
ApiError::Stream(format!(
"failed to build websocket prewarm client setup: {err}"
))
})?;
let auth_context = AuthRequestTelemetryContext::new(
client_setup.auth.as_ref().map(CodexAuth::auth_mode),
client_setup.api_auth.as_ref(),
@@ -1156,7 +1233,10 @@ impl ModelClientSession {
.map(AuthManager::unauthorized_recovery);
let mut pending_retry = PendingUnauthorizedRetry::default();
loop {
let client_setup = self.client.current_client_setup().await?;
let client_setup = self
.client
.current_client_setup(self.agent_task.as_ref())
.await?;
let transport = ReqwestTransport::new(build_reqwest_client());
let request_auth_context = AuthRequestTelemetryContext::new(
client_setup.auth.as_ref().map(CodexAuth::auth_mode),
@@ -1245,7 +1325,10 @@ impl ModelClientSession {
.map(AuthManager::unauthorized_recovery);
let mut pending_retry = PendingUnauthorizedRetry::default();
loop {
let client_setup = self.client.current_client_setup().await?;
let client_setup = self
.client
.current_client_setup(self.agent_task.as_ref())
.await?;
let request_auth_context = AuthRequestTelemetryContext::new(
client_setup.auth.as_ref().map(CodexAuth::auth_mode),
client_setup.api_auth.as_ref(),
+4 -4
View File
@@ -13,7 +13,7 @@ fn serializes_text_verbosity_when_set() {
let input: Vec<ResponseItem> = vec![];
let tools: Vec<serde_json::Value> = vec![];
let req = ResponsesApiRequest {
model: "gpt-5.1".to_string(),
model: "gpt-5.4".to_string(),
instructions: "i".to_string(),
input,
tools,
@@ -57,7 +57,7 @@ fn serializes_text_schema_with_strict_format() {
.expect("text controls");
let req = ResponsesApiRequest {
model: "gpt-5.1".to_string(),
model: "gpt-5.4".to_string(),
instructions: "i".to_string(),
input,
tools,
@@ -95,7 +95,7 @@ fn omits_text_when_not_set() {
let input: Vec<ResponseItem> = vec![];
let tools: Vec<serde_json::Value> = vec![];
let req = ResponsesApiRequest {
model: "gpt-5.1".to_string(),
model: "gpt-5.4".to_string(),
instructions: "i".to_string(),
input,
tools,
@@ -118,7 +118,7 @@ fn omits_text_when_not_set() {
#[test]
fn serializes_flex_service_tier_when_set() {
let req = ResponsesApiRequest {
model: "gpt-5.1".to_string(),
model: "gpt-5.4".to_string(),
instructions: "i".to_string(),
input: vec![],
tools: vec![],
+260
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use super::AuthRequestTelemetryContext;
use super::ModelClient;
use super::PendingUnauthorizedRetry;
@@ -7,17 +9,36 @@ use super::X_CODEX_PARENT_THREAD_ID_HEADER;
use super::X_CODEX_TURN_METADATA_HEADER;
use super::X_CODEX_WINDOW_ID_HEADER;
use super::X_OPENAI_SUBAGENT_HEADER;
use crate::Prompt;
use crate::ResponseEvent;
use crate::agent_identity::AgentIdentityManager;
use crate::agent_identity::RegisteredAgentTask;
use crate::agent_identity::StoredAgentIdentity;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_app_server_protocol::AuthMode;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_model_provider::BearerAuthProvider;
use codex_model_provider_info::ModelProviderInfo;
use codex_model_provider_info::WireApi;
use codex_model_provider_info::create_oss_provider_with_base_url;
use codex_otel::SessionTelemetry;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use core_test_support::responses;
use ed25519_dalek::Signature;
use ed25519_dalek::Verifier as _;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use serde_json::json;
use tempfile::TempDir;
fn test_model_client(session_source: SessionSource) -> ModelClient {
let provider = create_oss_provider_with_base_url("https://example.com/v1", WireApi::Responses);
@@ -79,6 +100,118 @@ fn test_session_telemetry() -> SessionTelemetry {
)
}
fn test_prompt(text: &str) -> Prompt {
Prompt {
input: vec![ResponseItem::Message {
id: None,
role: "user".into(),
content: vec![ContentItem::InputText {
text: text.to_string(),
}],
end_turn: None,
phase: None,
}],
..Prompt::default()
}
}
async fn drain_stream_to_completion(stream: &mut crate::ResponseStream) -> anyhow::Result<()> {
while let Some(event) = stream.next().await {
if matches!(event?, ResponseEvent::Completed { .. }) {
break;
}
}
Ok(())
}
async fn model_client_with_agent_task(
provider: ModelProviderInfo,
) -> (
TempDir,
ModelClient,
RegisteredAgentTask,
StoredAgentIdentity,
) {
let codex_home = tempfile::tempdir().expect("tempdir");
let auth_manager =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let agent_identity_manager = Arc::new(AgentIdentityManager::new_for_tests(
Arc::clone(&auth_manager),
/*feature_enabled*/ true,
"https://chatgpt.com/backend-api/".to_string(),
SessionSource::Cli,
));
let stored_identity = agent_identity_manager
.seed_generated_identity_for_tests("agent-123")
.await
.expect("seed test identity");
let agent_task = RegisteredAgentTask {
agent_runtime_id: stored_identity.agent_runtime_id.clone(),
task_id: "task-123".to_string(),
registered_at: "2026-03-23T12:00:00Z".to_string(),
};
let client = ModelClient::new(
Some(auth_manager),
ThreadId::new(),
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
provider,
SessionSource::Cli,
/*model_verbosity*/ None,
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
);
(codex_home, client, agent_task, stored_identity)
}
#[derive(Debug, Deserialize)]
struct AgentAssertionEnvelope {
agent_runtime_id: String,
task_id: String,
timestamp: String,
signature: String,
}
fn assert_agent_assertion_header(
authorization_header: &str,
stored_identity: &StoredAgentIdentity,
expected_agent_runtime_id: &str,
expected_task_id: &str,
) {
let token = authorization_header
.strip_prefix("AgentAssertion ")
.expect("agent assertion authorization scheme");
let envelope: AgentAssertionEnvelope = serde_json::from_slice(
&URL_SAFE_NO_PAD
.decode(token)
.expect("base64url-encoded agent assertion"),
)
.expect("valid agent assertion envelope");
assert_eq!(envelope.agent_runtime_id, expected_agent_runtime_id);
assert_eq!(envelope.task_id, expected_task_id);
let signature = Signature::from_slice(
&base64::engine::general_purpose::STANDARD
.decode(&envelope.signature)
.expect("base64 signature"),
)
.expect("signature bytes");
stored_identity
.signing_key()
.expect("signing key")
.verifying_key()
.verify(
format!(
"{}:{}:{}",
envelope.agent_runtime_id, envelope.task_id, envelope.timestamp
)
.as_bytes(),
&signature,
)
.expect("signature should verify");
}
#[test]
fn build_subagent_headers_sets_other_subagent_label() {
let client = test_model_client(SessionSource::SubAgent(SubAgentSource::Other(
@@ -169,3 +302,130 @@ fn auth_request_telemetry_context_tracks_attached_auth_and_retry_phase() {
assert_eq!(auth_context.recovery_mode, Some("managed"));
assert_eq!(auth_context.recovery_phase, Some("refresh_token"));
}
#[tokio::test]
async fn responses_http_uses_agent_assertion_when_agent_task_is_present() {
core_test_support::skip_if_no_network!();
let server = responses::start_mock_server().await;
let request_recorder = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_completed("resp-1"),
]),
)
.await;
let provider =
create_oss_provider_with_base_url(&format!("{}/v1", server.uri()), WireApi::Responses);
let (_codex_home, client, agent_task, stored_identity) =
model_client_with_agent_task(provider).await;
let model_info = test_model_info();
let session_telemetry = test_session_telemetry();
let mut client_session = client.new_session_with_agent_task(Some(agent_task.clone()));
let mut stream = client_session
.stream(
&test_prompt("hello"),
&model_info,
&session_telemetry,
/*effort*/ None,
ReasoningSummary::Auto,
/*service_tier*/ None,
/*turn_metadata_header*/ None,
)
.await
.expect("stream request should succeed");
drain_stream_to_completion(&mut stream)
.await
.expect("stream should complete");
let request = request_recorder.single_request();
let authorization = request
.header("authorization")
.expect("authorization header should be present");
assert_agent_assertion_header(
&authorization,
&stored_identity,
&agent_task.agent_runtime_id,
&agent_task.task_id,
);
assert_eq!(request.header("chatgpt-account-id"), None);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn websocket_agent_task_bypasses_cached_bearer_prewarm() {
core_test_support::skip_if_no_network!();
let server = responses::start_websocket_server(vec![
vec![vec![
responses::ev_response_created("resp-prewarm"),
responses::ev_completed("resp-prewarm"),
]],
vec![vec![
responses::ev_response_created("resp-1"),
responses::ev_completed("resp-1"),
]],
])
.await;
let mut provider =
create_oss_provider_with_base_url(&format!("{}/v1", server.uri()), WireApi::Responses);
provider.supports_websockets = true;
provider.websocket_connect_timeout_ms = Some(5_000);
let (_codex_home, client, agent_task, stored_identity) =
model_client_with_agent_task(provider).await;
let model_info = test_model_info();
let session_telemetry = test_session_telemetry();
let prompt = test_prompt("hello");
let mut prewarm_session = client.new_session();
prewarm_session
.prewarm_websocket(
&prompt,
&model_info,
&session_telemetry,
/*effort*/ None,
ReasoningSummary::Auto,
/*service_tier*/ None,
/*turn_metadata_header*/ None,
)
.await
.expect("bearer prewarm should succeed");
drop(prewarm_session);
let mut agent_task_session = client.new_session_with_agent_task(Some(agent_task.clone()));
let mut stream = agent_task_session
.stream(
&prompt,
&model_info,
&session_telemetry,
/*effort*/ None,
ReasoningSummary::Auto,
/*service_tier*/ None,
/*turn_metadata_header*/ None,
)
.await
.expect("agent task stream should succeed");
drain_stream_to_completion(&mut stream)
.await
.expect("agent task websocket stream should complete");
let handshakes = server.handshakes();
assert_eq!(handshakes.len(), 2);
assert_eq!(
handshakes[0].header("authorization"),
Some("Bearer Access Token".to_string())
);
let agent_authorization = handshakes[1]
.header("authorization")
.expect("agent handshake should include authorization");
assert_agent_assertion_header(
&agent_authorization,
&stored_identity,
&agent_task.agent_runtime_id,
&agent_task.task_id,
);
assert_eq!(handshakes[1].header("chatgpt-account-id"), None);
server.shutdown().await;
}
+95 -26
View File
@@ -32,6 +32,7 @@ use codex_config::types::ApprovalsReviewer;
use codex_config::types::BundledSkillsConfig;
use codex_config::types::FeedbackConfigToml;
use codex_config::types::HistoryPersistence;
use codex_config::types::McpServerEnvVar;
use codex_config::types::McpServerToolConfig;
use codex_config::types::McpServerTransportConfig;
use codex_config::types::MemoriesConfig;
@@ -231,7 +232,7 @@ max_rollout_age_days = 42
max_rollouts_per_startup = 9
min_rollout_idle_hours = 24
extract_model = "gpt-5-mini"
consolidation_model = "gpt-5"
consolidation_model = "gpt-5.2"
"#;
let memories_cfg =
toml::from_str::<ConfigToml>(memories).expect("TOML deserialization should succeed");
@@ -246,7 +247,7 @@ consolidation_model = "gpt-5"
max_rollouts_per_startup: Some(9),
min_rollout_idle_hours: Some(24),
extract_model: Some("gpt-5-mini".to_string()),
consolidation_model: Some("gpt-5".to_string()),
consolidation_model: Some("gpt-5.2".to_string()),
}),
memories_cfg.memories
);
@@ -270,7 +271,7 @@ consolidation_model = "gpt-5"
max_rollouts_per_startup: 9,
min_rollout_idle_hours: 24,
extract_model: Some("gpt-5-mini".to_string()),
consolidation_model: Some("gpt-5".to_string()),
consolidation_model: Some("gpt-5.2".to_string()),
}
);
@@ -291,6 +292,9 @@ consolidation_model = "gpt-5"
fn parses_bundled_skills_config() {
let cfg: ConfigToml = toml::from_str(
r#"
[skills]
include_instructions = false
[skills.bundled]
enabled = false
"#,
@@ -301,6 +305,7 @@ enabled = false
cfg.skills,
Some(SkillsConfig {
bundled: Some(BundledSkillsConfig { enabled: false }),
include_instructions: Some(false),
config: Vec::new(),
})
);
@@ -2490,7 +2495,7 @@ async fn replace_mcp_servers_serializes_env_vars() -> anyhow::Result<()> {
command: "docs-server".to_string(),
args: Vec::new(),
env: None,
env_vars: vec!["ALPHA".to_string(), "BETA".to_string()],
env_vars: vec!["ALPHA".into(), "BETA".into()],
cwd: None,
},
experimental_environment: None,
@@ -2526,7 +2531,7 @@ async fn replace_mcp_servers_serializes_env_vars() -> anyhow::Result<()> {
let docs = loaded.get("docs").expect("docs entry");
match &docs.transport {
McpServerTransportConfig::Stdio { env_vars, .. } => {
assert_eq!(env_vars, &vec!["ALPHA".to_string(), "BETA".to_string()]);
assert_eq!(env_vars, &vec!["ALPHA".into(), "BETA".into()]);
}
other => panic!("unexpected transport {other:?}"),
}
@@ -2534,6 +2539,62 @@ async fn replace_mcp_servers_serializes_env_vars() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test]
async fn replace_mcp_servers_serializes_sourced_env_vars() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let servers = BTreeMap::from([(
"docs".to_string(),
McpServerConfig {
transport: McpServerTransportConfig::Stdio {
command: "docs-server".to_string(),
args: Vec::new(),
env: None,
env_vars: vec![
"LEGACY".into(),
McpServerEnvVar::Config {
name: "REMOTE_TOKEN".to_string(),
source: Some("remote".to_string()),
},
],
cwd: None,
},
experimental_environment: None,
enabled: true,
required: false,
supports_parallel_tool_calls: false,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth_resource: None,
tools: HashMap::new(),
},
)]);
apply_blocking(
codex_home.path(),
/*profile*/ None,
&[ConfigEdit::ReplaceMcpServers(servers.clone())],
)?;
let config_path = codex_home.path().join(CONFIG_TOML_FILE);
let serialized = std::fs::read_to_string(&config_path)?;
assert!(
serialized
.contains(r#"env_vars = ["LEGACY", { name = "REMOTE_TOKEN", source = "remote" }]"#),
"serialized config missing sourced env_vars field:\n{serialized}"
);
let loaded = load_global_mcp_servers(codex_home.path()).await?;
assert_eq!(loaded, servers);
Ok(())
}
#[tokio::test]
async fn replace_mcp_servers_serializes_cwd() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
@@ -3168,14 +3229,14 @@ async fn set_model_updates_defaults() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
ConfigEditsBuilder::new(codex_home.path())
.set_model(Some("gpt-5.1-codex"), Some(ReasoningEffort::High))
.set_model(Some("gpt-5.4"), Some(ReasoningEffort::High))
.apply()
.await?;
let serialized = tokio::fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).await?;
let parsed: ConfigToml = toml::from_str(&serialized)?;
assert_eq!(parsed.model.as_deref(), Some("gpt-5.1-codex"));
assert_eq!(parsed.model.as_deref(), Some("gpt-5.4"));
assert_eq!(parsed.model_reasoning_effort, Some(ReasoningEffort::High));
Ok(())
@@ -3189,7 +3250,7 @@ async fn set_model_overwrites_existing_model() -> anyhow::Result<()> {
tokio::fs::write(
&config_path,
r#"
model = "gpt-5.1-codex"
model = "gpt-5.4"
model_reasoning_effort = "medium"
[profiles.dev]
@@ -3225,7 +3286,7 @@ async fn set_model_updates_profile() -> anyhow::Result<()> {
ConfigEditsBuilder::new(codex_home.path())
.with_profile(Some("dev"))
.set_model(Some("gpt-5.1-codex"), Some(ReasoningEffort::Medium))
.set_model(Some("gpt-5.4"), Some(ReasoningEffort::Medium))
.apply()
.await?;
@@ -3236,7 +3297,7 @@ async fn set_model_updates_profile() -> anyhow::Result<()> {
.get("dev")
.expect("profile should be created");
assert_eq!(profile.model.as_deref(), Some("gpt-5.1-codex"));
assert_eq!(profile.model.as_deref(), Some("gpt-5.4"));
assert_eq!(
profile.model_reasoning_effort,
Some(ReasoningEffort::Medium)
@@ -3258,7 +3319,7 @@ model = "gpt-4"
model_reasoning_effort = "medium"
[profiles.prod]
model = "gpt-5.1-codex"
model = "gpt-5.4"
"#,
)
.await?;
@@ -3287,7 +3348,7 @@ model = "gpt-5.1-codex"
.profiles
.get("prod")
.and_then(|profile| profile.model.as_deref()),
Some("gpt-5.1-codex"),
Some("gpt-5.4"),
);
Ok(())
@@ -3652,7 +3713,7 @@ async fn agent_role_file_metadata_overrides_config_toml_metadata() -> std::io::R
description = "Role metadata from file"
nickname_candidates = ["Hypatia"]
developer_instructions = "Research carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -3714,7 +3775,7 @@ trust_level = "trusted"
r#"
name = "researcher"
description = "Role metadata from file"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -3724,7 +3785,7 @@ model = "gpt-5"
name = "reviewer"
description = "Review role"
developer_instructions = "Review carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -3769,7 +3830,7 @@ async fn legacy_agent_role_config_file_allows_missing_developer_instructions() -
tokio::fs::write(
&role_config_path,
r#"
model = "gpt-5"
model = "gpt-5.2"
model_reasoning_effort = "high"
"#,
)
@@ -3821,7 +3882,7 @@ async fn agent_role_without_description_after_merge_is_dropped_with_warning() ->
&role_config_path,
r#"
developer_instructions = "Research carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -3940,7 +4001,7 @@ async fn agent_role_file_name_takes_precedence_over_config_key() -> std::io::Res
name = "archivist"
description = "Role metadata from file"
developer_instructions = "Research carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -4225,7 +4286,7 @@ nickname_candidates = ["Ada"]
home_agents_dir.join("researcher.toml"),
r#"
developer_instructions = "Research carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -4258,7 +4319,7 @@ name = "writer"
description = "Writer role from file"
nickname_candidates = ["Sagan"]
developer_instructions = "Write carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -4365,7 +4426,7 @@ config_file = "./agents/researcher.toml"
home_agents_dir.join("researcher.toml"),
r#"
developer_instructions = "Research carefully"
model = "gpt-5"
model = "gpt-5.2"
"#,
)
.await?;
@@ -4664,7 +4725,7 @@ approval_policy = "on-failure"
enabled = false
[profiles.gpt5]
model = "gpt-5.1"
model = "gpt-5.4"
model_provider = "openai"
approval_policy = "on-failure"
model_reasoning_effort = "high"
@@ -4831,6 +4892,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> {
guardian_policy_config: None,
include_permissions_instructions: true,
include_apps_instructions: true,
include_skill_instructions: true,
include_environment_context: true,
compact_prompt: None,
commit_attribution: None,
@@ -4981,6 +5043,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> {
guardian_policy_config: None,
include_permissions_instructions: true,
include_apps_instructions: true,
include_skill_instructions: true,
include_environment_context: true,
compact_prompt: None,
commit_attribution: None,
@@ -5129,6 +5192,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> {
guardian_policy_config: None,
include_permissions_instructions: true,
include_apps_instructions: true,
include_skill_instructions: true,
include_environment_context: true,
compact_prompt: None,
commit_attribution: None,
@@ -5184,7 +5248,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
)
.await?;
let expected_gpt5_profile_config = Config {
model: Some("gpt-5.1".to_string()),
model: Some("gpt-5.4".to_string()),
review_model: None,
model_context_window: None,
model_auto_compact_token_limit: None,
@@ -5262,6 +5326,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
guardian_policy_config: None,
include_permissions_instructions: true,
include_apps_instructions: true,
include_skill_instructions: true,
include_environment_context: true,
compact_prompt: None,
commit_attribution: None,
@@ -5833,7 +5898,7 @@ fn config_toml_deserializes_mcp_oauth_callback_url() {
async fn config_loads_mcp_oauth_callback_port_from_toml() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
let toml = r#"
model = "gpt-5.1"
model = "gpt-5.4"
mcp_oauth_callback_port = 5678
"#;
let cfg: ConfigToml =
@@ -5855,7 +5920,7 @@ async fn config_loads_allow_login_shell_from_toml() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
let cfg: ConfigToml = toml::from_str(
r#"
model = "gpt-5.1"
model = "gpt-5.4"
allow_login_shell = false
"#,
)
@@ -5876,7 +5941,7 @@ allow_login_shell = false
async fn config_loads_mcp_oauth_callback_url_from_toml() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
let toml = r#"
model = "gpt-5.1"
model = "gpt-5.4"
mcp_oauth_callback_url = "https://example.com/callback"
"#;
let cfg: ConfigToml =
@@ -6213,6 +6278,9 @@ include_apps_instructions = false
include_environment_context = false
profile = "chatty"
[skills]
include_instructions = false
[profiles.chatty]
include_permissions_instructions = true
include_environment_context = true
@@ -6227,6 +6295,7 @@ include_environment_context = true
assert!(config.include_permissions_instructions);
assert!(!config.include_apps_instructions);
assert!(!config.include_skill_instructions);
assert!(config.include_environment_context);
Ok(())
}
+20 -1
View File
@@ -136,6 +136,7 @@ pub fn model_availability_nux_count_edits(shown_count: &HashMap<String, u32>) ->
mod document_helpers {
use codex_config::types::AppToolApproval;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerEnvVar;
use codex_config::types::McpServerToolConfig;
use codex_config::types::McpServerTransportConfig;
use toml_edit::Array as TomlArray;
@@ -198,7 +199,7 @@ mod document_helpers {
entry["env"] = table_from_pairs(env.iter());
}
if !env_vars.is_empty() {
entry["env_vars"] = array_from_iter(env_vars.iter().cloned());
entry["env_vars"] = array_from_env_vars(env_vars);
}
if let Some(cwd) = cwd {
entry["cwd"] = value(cwd.to_string_lossy().to_string());
@@ -348,6 +349,24 @@ mod document_helpers {
TomlItem::Value(array.into())
}
fn array_from_env_vars(env_vars: &[McpServerEnvVar]) -> TomlItem {
let mut array = TomlArray::new();
for env_var in env_vars {
match env_var {
McpServerEnvVar::Name(name) => array.push(name.clone()),
McpServerEnvVar::Config { name, source } => {
let mut table = InlineTable::new();
table.insert("name", name.clone().into());
if let Some(source) = source {
table.insert("source", source.clone().into());
}
array.push(table);
}
}
}
TomlItem::Value(array.into())
}
fn table_from_pairs<'a, I>(pairs: I) -> TomlItem
where
I: IntoIterator<Item = (&'a String, &'a String)>,
+15 -15
View File
@@ -18,14 +18,14 @@ fn blocking_set_model_top_level() {
codex_home,
/*profile*/ None,
&[ConfigEdit::SetModel {
model: Some("gpt-5.1-codex".to_string()),
model: Some("gpt-5.4".to_string()),
effort: Some(ReasoningEffort::High),
}],
)
.expect("persist");
let contents = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config");
let expected = r#"model = "gpt-5.1-codex"
let expected = r#"model = "gpt-5.4"
model_reasoning_effort = "high"
"#;
assert_eq!(contents, expected);
@@ -197,7 +197,7 @@ fn blocking_set_model_writes_through_symlink_chain() {
codex_home,
/*profile*/ None,
&[ConfigEdit::SetModel {
model: Some("gpt-5.1-codex".to_string()),
model: Some("gpt-5.4".to_string()),
effort: Some(ReasoningEffort::High),
}],
)
@@ -207,7 +207,7 @@ fn blocking_set_model_writes_through_symlink_chain() {
assert!(meta.file_type().is_symlink());
let contents = std::fs::read_to_string(&target_path).expect("read target");
let expected = r#"model = "gpt-5.1-codex"
let expected = r#"model = "gpt-5.4"
model_reasoning_effort = "high"
"#;
assert_eq!(contents, expected);
@@ -230,7 +230,7 @@ fn blocking_set_model_replaces_symlink_on_cycle() {
codex_home,
/*profile*/ None,
&[ConfigEdit::SetModel {
model: Some("gpt-5.1-codex".to_string()),
model: Some("gpt-5.4".to_string()),
effort: None,
}],
)
@@ -240,7 +240,7 @@ fn blocking_set_model_replaces_symlink_on_cycle() {
assert!(!meta.file_type().is_symlink());
let contents = std::fs::read_to_string(&config_path).expect("read config");
let expected = r#"model = "gpt-5.1-codex"
let expected = r#"model = "gpt-5.4"
"#;
assert_eq!(contents, expected);
}
@@ -381,7 +381,7 @@ fn blocking_set_model_with_explicit_profile() {
std::fs::write(
codex_home.join(CONFIG_TOML_FILE),
r#"[profiles."team a"]
model = "gpt-5.1-codex"
model = "gpt-5.4"
"#,
)
.expect("seed");
@@ -536,8 +536,8 @@ existing = "value"
codex_home,
/*profile*/ None,
&[ConfigEdit::RecordModelMigrationSeen {
from: "gpt-5".to_string(),
to: "gpt-5.1".to_string(),
from: "gpt-5.2".to_string(),
to: "gpt-5.4".to_string(),
}],
)
.expect("persist");
@@ -547,7 +547,7 @@ existing = "value"
existing = "value"
[notice.model_migrations]
gpt-5 = "gpt-5.1"
gpt-5 = "gpt-5.4"
"#;
assert_eq!(contents, expected);
}
@@ -696,7 +696,7 @@ fn blocking_replace_mcp_servers_round_trips() {
.into_iter()
.collect(),
),
env_vars: vec!["FOO".to_string()],
env_vars: vec!["FOO".into()],
cwd: None,
},
experimental_environment: None,
@@ -1102,13 +1102,13 @@ async fn async_builder_set_model_persists() {
let codex_home = tmp.path().to_path_buf();
ConfigEditsBuilder::new(&codex_home)
.set_model(Some("gpt-5.1-codex"), Some(ReasoningEffort::High))
.set_model(Some("gpt-5.4"), Some(ReasoningEffort::High))
.apply()
.await
.expect("persist");
let contents = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config");
let expected = r#"model = "gpt-5.1-codex"
let expected = r#"model = "gpt-5.4"
model_reasoning_effort = "high"
"#;
assert_eq!(contents, expected);
@@ -1130,11 +1130,11 @@ model_reasoning_effort = "low"
std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config");
assert_eq!(contents, initial_expected);
let updated_expected = r#"model = "gpt-5.1-codex"
let updated_expected = r#"model = "gpt-5.4"
model_reasoning_effort = "high"
"#;
ConfigEditsBuilder::new(codex_home)
.set_model(Some("gpt-5.1-codex"), Some(ReasoningEffort::High))
.set_model(Some("gpt-5.4"), Some(ReasoningEffort::High))
.apply_blocking()
.expect("persist update");
contents = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config");
+37 -2
View File
@@ -49,7 +49,7 @@ use codex_config::types::UriBasedFileOpener;
use codex_config::types::WindowsSandboxModeToml;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::LOCAL_FS;
use codex_features::Feature;
pub use codex_features::Feature;
use codex_features::FeatureConfigSource;
use codex_features::FeatureOverrides;
use codex_features::FeatureToml;
@@ -58,6 +58,7 @@ use codex_features::FeaturesToml;
use codex_features::MultiAgentV2ConfigToml;
use codex_git_utils::resolve_root_git_project_for_trust;
use codex_login::AuthManagerConfig;
use codex_login::BackgroundAgentTaskAuthMode;
use codex_mcp::McpConfig;
use codex_model_provider_info::LEGACY_OLLAMA_CHAT_PROVIDER_ID;
use codex_model_provider_info::ModelProviderInfo;
@@ -292,6 +293,9 @@ pub struct Config {
/// Whether to inject the `<apps_instructions>` developer block.
pub include_apps_instructions: bool,
/// Whether to inject the `<skills_instructions>` developer block.
pub include_skill_instructions: bool,
/// Whether to inject the `<environment_context>` user block.
pub include_environment_context: bool,
@@ -626,6 +630,16 @@ impl AuthManagerConfig for Config {
fn forced_chatgpt_workspace_id(&self) -> Option<String> {
self.forced_chatgpt_workspace_id.clone()
}
fn chatgpt_base_url(&self) -> Option<String> {
Some(self.chatgpt_base_url.clone())
}
fn background_agent_task_auth_mode(&self) -> BackgroundAgentTaskAuthMode {
BackgroundAgentTaskAuthMode::from_feature_enabled(
self.features.enabled(Feature::UseAgentIdentity),
)
}
}
#[derive(Debug, Clone, Default)]
@@ -853,13 +867,28 @@ pub async fn load_config_as_toml_with_cli_overrides(
codex_home: &Path,
cwd: Option<&AbsolutePathBuf>,
cli_overrides: Vec<(String, TomlValue)>,
) -> std::io::Result<ConfigToml> {
load_config_as_toml_with_cli_and_loader_overrides(
codex_home,
cwd,
cli_overrides,
LoaderOverrides::default(),
)
.await
}
pub async fn load_config_as_toml_with_cli_and_loader_overrides(
codex_home: &Path,
cwd: Option<&AbsolutePathBuf>,
cli_overrides: Vec<(String, TomlValue)>,
loader_overrides: LoaderOverrides,
) -> std::io::Result<ConfigToml> {
let config_layer_stack = load_config_layers_state(
LOCAL_FS.as_ref(),
codex_home,
cwd.cloned(),
&cli_overrides,
LoaderOverrides::default(),
loader_overrides,
CloudRequirementsLoader::default(),
)
.await?;
@@ -1929,6 +1958,11 @@ impl Config {
.include_apps_instructions
.or(cfg.include_apps_instructions)
.unwrap_or(true);
let include_skill_instructions = cfg
.skills
.as_ref()
.and_then(|skills| skills.include_instructions)
.unwrap_or(true);
let include_environment_context = config_profile
.include_environment_context
.or(cfg.include_environment_context)
@@ -2143,6 +2177,7 @@ impl Config {
commit_attribution,
include_permissions_instructions,
include_apps_instructions,
include_skill_instructions,
include_environment_context,
// The config.toml omits "_mode" because it's a config file. However, "_mode"
// is important in code to differentiate the mode from the store implementation.
+3 -3
View File
@@ -62,7 +62,7 @@ X-Doc = "42"
async fn write_value_preserves_comments_and_order() -> Result<()> {
let tmp = tempdir().expect("tempdir");
let original = r#"# Codex user configuration
model = "gpt-5"
model = "gpt-5.2"
approval_policy = "on-request"
[notice]
@@ -88,7 +88,7 @@ unified_exec = true
let updated = std::fs::read_to_string(tmp.path().join(CONFIG_TOML_FILE)).expect("read config");
let expected = r#"# Codex user configuration
model = "gpt-5"
model = "gpt-5.2"
approval_policy = "on-request"
[notice]
@@ -390,7 +390,7 @@ async fn version_conflict_rejected() {
.write_value(ConfigValueWriteParams {
file_path: Some(tmp.path().join(CONFIG_TOML_FILE).display().to_string()),
key_path: "model".to_string(),
value: serde_json::json!("gpt-5"),
value: serde_json::json!("gpt-5.2"),
merge_strategy: MergeStrategy::Replace,
expected_version: Some("sha256:bogus".to_string()),
})
+22 -9
View File
@@ -128,6 +128,9 @@ pub async fn load_config_layers_state(
overrides: LoaderOverrides,
cloud_requirements: CloudRequirementsLoader,
) -> io::Result<ConfigLayerStack> {
let ignore_user_config = overrides.ignore_user_config;
let ignore_user_and_project_exec_policy_rules =
overrides.ignore_user_and_project_exec_policy_rules;
let mut config_requirements_toml = ConfigRequirementsWithSources::default();
if let Some(requirements) = cloud_requirements.get().await.map_err(io::Error::other)? {
@@ -189,19 +192,28 @@ pub async fn load_config_layers_state(
.await?;
layers.push(system_layer);
// Add a layer for $CODEX_HOME/config.toml if it exists. Note if the file
// exists, but is malformed, then this error should be propagated to the
// user.
// Add a layer for $CODEX_HOME/config.toml so folder-derived resources such
// as rules/ can still be discovered. When user config is ignored, preserve
// the layer metadata without reading config.toml.
let user_file = AbsolutePathBuf::resolve_path_against_base(CONFIG_TOML_FILE, codex_home);
let user_layer = load_config_toml_for_required_layer(fs, &user_file, |config_toml| {
let user_layer = if ignore_user_config {
ConfigLayerEntry::new(
ConfigLayerSource::User {
file: user_file.clone(),
},
config_toml,
TomlValue::Table(toml::map::Map::new()),
)
})
.await?;
} else {
load_config_toml_for_required_layer(fs, &user_file, |config_toml| {
ConfigLayerEntry::new(
ConfigLayerSource::User {
file: user_file.clone(),
},
config_toml,
)
})
.await?
};
layers.push(user_layer);
if let Some(cwd) = cwd {
@@ -312,11 +324,12 @@ pub async fn load_config_layers_state(
));
}
ConfigLayerStack::new(
Ok(ConfigLayerStack::new(
layers,
config_requirements_toml.clone().try_into()?,
config_requirements_toml.into_toml(),
)
)?
.with_user_and_project_exec_policy_rules_ignored(ignore_user_and_project_exec_policy_rules))
}
/// Attempts to load a config.toml file from `config_toml`.
+57
View File
@@ -111,6 +111,63 @@ async fn returns_config_error_for_invalid_user_config_toml() {
assert_eq!(config_error, &expected_config_error);
}
#[tokio::test]
async fn ignore_user_config_keeps_empty_user_layer() -> std::io::Result<()> {
let tmp = tempdir().expect("tempdir");
std::fs::write(
tmp.path().join(CONFIG_TOML_FILE),
"model = \"from-user-config\"\ninvalid = [",
)
.expect("write config");
let cwd = AbsolutePathBuf::try_from(tmp.path()).expect("cwd");
let layers = load_config_layers_state(
LOCAL_FS.as_ref(),
tmp.path(),
Some(cwd),
&[] as &[(String, TomlValue)],
LoaderOverrides {
ignore_user_config: true,
..Default::default()
},
CloudRequirementsLoader::default(),
)
.await?;
let user_layer = layers
.get_user_layer()
.expect("expected a user layer even when CODEX_HOME/config.toml is ignored");
assert_eq!(
user_layer.config,
TomlValue::Table(toml::map::Map::new()),
"expected ignored user config to preserve only layer metadata"
);
assert_eq!(layers.effective_config().get("model"), None);
Ok(())
}
#[tokio::test]
async fn ignore_rules_marks_config_stack_for_exec_policy_rule_skip() -> std::io::Result<()> {
let tmp = tempdir().expect("tempdir");
let cwd = AbsolutePathBuf::try_from(tmp.path()).expect("cwd");
let layers = load_config_layers_state(
LOCAL_FS.as_ref(),
tmp.path(),
Some(cwd),
&[] as &[(String, TomlValue)],
LoaderOverrides {
ignore_user_and_project_exec_policy_rules: true,
..Default::default()
},
CloudRequirementsLoader::default(),
)
.await?;
assert!(layers.ignore_user_and_project_exec_policy_rules());
Ok(())
}
#[tokio::test]
async fn returns_config_error_for_invalid_managed_config_toml() {
let tmp = tempdir().expect("tempdir");
+43 -13
View File
@@ -13,6 +13,7 @@ pub use codex_app_server_protocol::AppInfo;
pub use codex_app_server_protocol::AppMetadata;
use codex_connectors::AllConnectorsCacheKey;
use codex_connectors::DirectoryListResponse;
use codex_exec_server::Environment;
use codex_login::token_data::TokenData;
use codex_protocol::protocol::SandboxPolicy;
use codex_tools::DiscoverableTool;
@@ -37,11 +38,12 @@ use codex_login::default_client::create_client;
use codex_login::default_client::originator;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::McpConnectionManager;
use codex_mcp::McpRuntimeEnvironment;
use codex_mcp::ToolInfo;
use codex_mcp::ToolPluginProvenance;
use codex_mcp::codex_apps_tools_cache_key;
use codex_mcp::compute_auth_statuses;
use codex_mcp::with_codex_apps_mcp;
use codex_mcp::with_codex_apps_mcp_with_authorization_header;
const CONNECTORS_READY_TIMEOUT_ON_EMPTY_TOOLS: Duration = Duration::from_secs(30);
const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60);
@@ -218,8 +220,20 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options_and_status(
});
}
let background_authorization_header_value = if let Some(auth) = auth.as_ref() {
auth_manager
.chatgpt_authorization_header_for_auth(auth)
.await
} else {
None
};
let mcp_config = config.to_mcp_config(plugins_manager.as_ref()).await;
let mcp_servers = with_codex_apps_mcp(HashMap::new(), auth.as_ref(), &mcp_config);
let mcp_servers = with_codex_apps_mcp_with_authorization_header(
HashMap::new(),
auth.as_ref(),
&mcp_config,
background_authorization_header_value.as_deref(),
);
if mcp_servers.is_empty() {
return Ok(AccessibleConnectorsStatus {
connectors: Vec::new(),
@@ -241,6 +255,7 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_options_and_status(
INITIAL_SUBMIT_ID.to_owned(),
tx_event,
SandboxPolicy::new_read_only_policy(),
McpRuntimeEnvironment::new(Arc::new(Environment::default()), config.cwd.to_path_buf()),
config.codex_home.to_path_buf(),
codex_apps_tools_cache_key(auth.as_ref()),
ToolPluginProvenance::default(),
@@ -420,6 +435,18 @@ async fn list_directory_connectors_for_tool_suggest_with_auth(
};
let access_token = token_data.access_token.clone();
let account_id = account_id.to_string();
let is_fedramp_account = token_data.id_token.is_fedramp_account();
let authorization_header_value = {
let auth_manager =
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false);
match auth {
Some(auth) if auth.is_chatgpt_auth() => auth_manager
.chatgpt_authorization_header_for_auth(auth)
.await
.unwrap_or_else(|| format!("Bearer {access_token}")),
_ => format!("Bearer {access_token}"),
}
};
let is_workspace_account = token_data.id_token.is_workspace_account();
let cache_key = AllConnectorsCacheKey::new(
config.chatgpt_base_url.clone(),
@@ -433,14 +460,15 @@ async fn list_directory_connectors_for_tool_suggest_with_auth(
is_workspace_account,
/*force_refetch*/ false,
|path| {
let access_token = access_token.clone();
let authorization_header_value = authorization_header_value.clone();
let account_id = account_id.clone();
async move {
chatgpt_get_request_with_token::<DirectoryListResponse>(
chatgpt_get_request_with_authorization_header::<DirectoryListResponse>(
config,
path,
access_token.as_str(),
authorization_header_value.as_str(),
account_id.as_str(),
is_fedramp_account,
)
.await
}
@@ -449,23 +477,25 @@ async fn list_directory_connectors_for_tool_suggest_with_auth(
.await
}
async fn chatgpt_get_request_with_token<T: DeserializeOwned>(
async fn chatgpt_get_request_with_authorization_header<T: DeserializeOwned>(
config: &Config,
path: String,
access_token: &str,
authorization_header_value: &str,
account_id: &str,
is_fedramp_account: bool,
) -> anyhow::Result<T> {
let client = create_client();
let url = format!("{}{}", config.chatgpt_base_url, path);
let response = client
let mut request = client
.get(&url)
.bearer_auth(access_token)
.header("authorization", authorization_header_value)
.header("chatgpt-account-id", account_id)
.header("Content-Type", "application/json")
.timeout(DIRECTORY_CONNECTORS_TIMEOUT)
.send()
.await
.context("failed to send request")?;
.timeout(DIRECTORY_CONNECTORS_TIMEOUT);
if is_fedramp_account {
request = request.header("X-OpenAI-Fedramp", "true");
}
let response = request.send().await.context("failed to send request")?;
if response.status().is_success() {
response
+36 -4
View File
@@ -7,6 +7,7 @@ use arc_swap::ArcSwap;
use crate::config_loader::ConfigLayerStack;
use crate::config_loader::ConfigLayerStackOrdering;
use codex_app_server_protocol::ConfigLayerSource;
use codex_execpolicy::AmendError;
use codex_execpolicy::Decision;
use codex_execpolicy::Error as ExecPolicyRuleError;
@@ -27,6 +28,7 @@ use codex_shell_command::is_dangerous_command::command_might_be_dangerous;
use codex_shell_command::is_safe_command::is_known_safe_command;
use thiserror::Error;
use tokio::fs;
use tokio::sync::Semaphore;
use tokio::task::spawn_blocking;
use tracing::instrument;
@@ -110,6 +112,12 @@ pub(crate) fn child_uses_parent_exec_policy(parent_config: &Config, child_config
}
exec_policy_config_folders(parent_config) == exec_policy_config_folders(child_config)
&& parent_config
.config_layer_stack
.ignore_user_and_project_exec_policy_rules()
== child_config
.config_layer_stack
.ignore_user_and_project_exec_policy_rules()
&& parent_config.config_layer_stack.requirements().exec_policy
== child_config.config_layer_stack.requirements().exec_policy
}
@@ -190,7 +198,7 @@ pub enum ExecPolicyUpdateError {
pub(crate) struct ExecPolicyManager {
policy: ArcSwap<Policy>,
update_lock: tokio::sync::Mutex<()>,
update_lock: Semaphore,
}
pub(crate) struct ExecApprovalRequest<'a> {
@@ -206,7 +214,7 @@ impl ExecPolicyManager {
pub(crate) fn new(policy: Arc<Policy>) -> Self {
Self {
policy: ArcSwap::from(policy),
update_lock: tokio::sync::Mutex::new(()),
update_lock: Semaphore::new(/*permits*/ 1),
}
}
@@ -324,7 +332,15 @@ impl ExecPolicyManager {
codex_home: &Path,
amendment: &ExecPolicyAmendment,
) -> Result<(), ExecPolicyUpdateError> {
let _update_guard = self.update_lock.lock().await;
let _update_guard =
self.update_lock
.acquire()
.await
.map_err(|_| ExecPolicyUpdateError::AddRule {
source: ExecPolicyRuleError::InvalidRule(
"exec policy update semaphore closed".to_string(),
),
})?;
let policy_path = default_policy_path(codex_home);
spawn_blocking({
let policy_path = policy_path.clone();
@@ -369,7 +385,15 @@ impl ExecPolicyManager {
decision: Decision,
justification: Option<String>,
) -> Result<(), ExecPolicyUpdateError> {
let _update_guard = self.update_lock.lock().await;
let _update_guard =
self.update_lock
.acquire()
.await
.map_err(|_| ExecPolicyUpdateError::AddRule {
source: ExecPolicyRuleError::InvalidRule(
"exec policy update semaphore closed".to_string(),
),
})?;
let policy_path = default_policy_path(codex_home);
let host = host.to_string();
spawn_blocking({
@@ -505,6 +529,14 @@ pub async fn load_exec_policy(config_stack: &ConfigLayerStack) -> Result<Policy,
ConfigLayerStackOrdering::LowestPrecedenceFirst,
/*include_disabled*/ false,
) {
if config_stack.ignore_user_and_project_exec_policy_rules()
&& matches!(
layer.name,
ConfigLayerSource::User { .. } | ConfigLayerSource::Project { .. }
)
{
continue;
}
if let Some(config_folder) = layer.config_folder() {
let policy_dir = config_folder.join(RULES_DIR_NAME);
let layer_policy_paths = collect_policy_files(&policy_dir).await?;
+124
View File
@@ -6,9 +6,11 @@ use crate::config_loader::ConfigLayerStack;
use crate::config_loader::ConfigLayerStackOrdering;
use crate::config_loader::ConfigRequirements;
use crate::config_loader::ConfigRequirementsToml;
use crate::config_loader::LoaderOverrides;
use crate::config_loader::RequirementSource;
use crate::config_loader::Sourced;
use codex_app_server_protocol::ConfigLayerSource;
use codex_config::CONFIG_TOML_FILE;
use codex_config::RequirementsExecPolicy;
use codex_config::config_toml::ConfigToml;
use codex_config::config_toml::ProjectConfig;
@@ -159,6 +161,22 @@ async fn child_uses_parent_exec_policy_when_non_exec_policy_layers_differ() {
assert!(child_uses_parent_exec_policy(&parent_config, &child_config));
}
#[tokio::test]
async fn child_does_not_use_parent_exec_policy_when_ignore_rules_differs() {
let (_home, parent_config) = test_config().await;
let mut child_config = parent_config.clone();
child_config.config_layer_stack = child_config
.config_layer_stack
.with_user_and_project_exec_policy_rules_ignored(
/*ignore_user_and_project_exec_policy_rules*/ true,
);
assert!(!child_uses_parent_exec_policy(
&parent_config,
&child_config
));
}
#[tokio::test]
async fn child_does_not_use_parent_exec_policy_when_requirements_exec_policy_differs() {
let (_home, parent_config) = test_config().await;
@@ -424,6 +442,73 @@ async fn ignores_policies_outside_policy_dir() {
);
}
#[tokio::test]
async fn ignores_policy_files_when_config_stack_disables_exec_policy_rules() {
let temp_dir = tempdir().expect("create temp dir");
let policy_dir = temp_dir.path().join(RULES_DIR_NAME);
fs::create_dir_all(&policy_dir).expect("create policy dir");
fs::write(
policy_dir.join("allow.rules"),
r#"prefix_rule(pattern=["curl"], decision="allow")"#,
)
.expect("write policy file");
let config_stack = config_stack_for_dot_codex_folder(temp_dir.path())
.with_user_and_project_exec_policy_rules_ignored(
/*ignore_user_and_project_exec_policy_rules*/ true,
);
let policy = load_exec_policy(&config_stack)
.await
.expect("policy result");
assert_eq!(
policy
.check_multiple([vec!["curl".to_string()]].iter(), &|_| Decision::Forbidden)
.decision,
Decision::Forbidden,
);
}
#[tokio::test]
async fn ignore_user_project_rules_keeps_system_policy_files() {
let temp_dir = tempdir().expect("create temp dir");
let config_dir = temp_dir.path().join("system");
let policy_dir = config_dir.join(RULES_DIR_NAME);
fs::create_dir_all(&policy_dir).expect("create policy dir");
fs::write(
policy_dir.join("allow.rules"),
r#"prefix_rule(pattern=["curl"], decision="allow")"#,
)
.expect("write policy file");
let config_file =
AbsolutePathBuf::from_absolute_path(config_dir.join(codex_config::CONFIG_TOML_FILE))
.expect("absolute config file");
let layer = ConfigLayerEntry::new(
ConfigLayerSource::System { file: config_file },
TomlValue::Table(Default::default()),
);
let config_stack = ConfigLayerStack::new(
vec![layer],
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("ConfigLayerStack")
.with_user_and_project_exec_policy_rules_ignored(
/*ignore_user_and_project_exec_policy_rules*/ true,
);
let policy = load_exec_policy(&config_stack)
.await
.expect("policy result");
assert_eq!(
policy
.check_multiple([vec!["curl".to_string()]].iter(), &|_| Decision::Forbidden)
.decision,
Decision::Allow,
);
}
#[tokio::test]
async fn ignores_rules_from_untrusted_project_layers() -> anyhow::Result<()> {
let project_dir = tempdir()?;
@@ -575,6 +660,45 @@ fn commands_for_exec_policy_falls_back_for_whitespace_shell_script() {
assert_eq!(commands_for_exec_policy(&command), (vec![command], false));
}
#[tokio::test]
async fn ignore_user_config_keeps_user_policy_files() -> std::io::Result<()> {
let temp = tempdir()?;
let codex_home = temp.path().join("home_ignore_user_config");
let rules_dir = codex_home.join(RULES_DIR_NAME);
fs::create_dir_all(&rules_dir)?;
fs::write(
codex_home.join(CONFIG_TOML_FILE),
"model = \"from-user-config\"\ninvalid = [",
)?;
fs::write(
rules_dir.join("deny-curl.rules"),
r#"prefix_rule(pattern=["curl"], decision="forbidden")"#,
)?;
let config = ConfigBuilder::default()
.codex_home(codex_home)
.fallback_cwd(Some(temp.path().to_path_buf()))
.loader_overrides(LoaderOverrides {
ignore_user_config: true,
..Default::default()
})
.build()
.await?;
let policy = load_exec_policy(&config.config_layer_stack)
.await
.map_err(std::io::Error::other)?;
assert_eq!(
policy
.check_multiple([vec!["curl".to_string()]].iter(), &|_| Decision::Allow)
.decision,
Decision::Forbidden,
);
Ok(())
}
#[tokio::test]
async fn evaluates_heredoc_script_against_prefix_rules() {
let command = vec![
+61 -36
View File
@@ -25,6 +25,8 @@ const EXTERNAL_AGENT_CONFIG_DETECT_METRIC: &str = "codex.external_agent_config.d
const EXTERNAL_AGENT_CONFIG_IMPORT_METRIC: &str = "codex.external_agent_config.import";
const EXTERNAL_AGENT_DIR: &str = ".claude";
const EXTERNAL_AGENT_CONFIG_MD: &str = "CLAUDE.md";
const EXTERNAL_OFFICIAL_MARKETPLACE_NAME: &str = "claude-plugins-official";
const EXTERNAL_OFFICIAL_MARKETPLACE_SOURCE: &str = "anthropics/claude-plugins-official";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalAgentConfigDetectOptions {
@@ -706,6 +708,16 @@ fn collect_enabled_plugins(settings: &JsonValue) -> Vec<String> {
.collect()
}
fn has_enabled_plugin_for_marketplace(settings: &JsonValue, marketplace_name: &str) -> bool {
collect_enabled_plugins(settings)
.into_iter()
.any(|plugin_id| {
PluginId::parse(&plugin_id)
.map(|plugin_id| plugin_id.marketplace_name == marketplace_name)
.unwrap_or(false)
})
}
fn configured_marketplace_plugins(
config: &Config,
plugins_manager: &PluginsManager,
@@ -741,48 +753,61 @@ fn collect_marketplace_import_sources(
settings: &JsonValue,
source_root: &Path,
) -> BTreeMap<String, MarketplaceImportSource> {
let Some(extra_known_marketplaces) = settings
let mut import_sources: BTreeMap<String, MarketplaceImportSource> = settings
.as_object()
.and_then(|settings| settings.get("extraKnownMarketplaces"))
.and_then(JsonValue::as_object)
else {
return BTreeMap::new();
};
.map(|extra_known_marketplaces| {
extra_known_marketplaces
.iter()
.filter_map(|(name, value)| {
let source_fields = if let Some(source) = value.get("source")
&& source.is_object()
{
source.as_object()?
} else {
value.as_object()?
};
let source = source_fields
.get("repo")
.or_else(|| source_fields.get("url"))
.or_else(|| source_fields.get("path"))
.or_else(|| value.get("source"))?
.as_str()?
.trim()
.to_string();
if source.is_empty() {
return None;
}
let source = resolve_external_marketplace_source(&source, source_root);
extra_known_marketplaces
.iter()
.filter_map(|(name, value)| {
let source_fields = if let Some(source) = value.get("source")
&& source.is_object()
{
source.as_object()?
} else {
value.as_object()?
};
let source = source_fields
.get("repo")
.or_else(|| source_fields.get("url"))
.or_else(|| source_fields.get("path"))
.or_else(|| value.get("source"))?
.as_str()?
.trim()
.to_string();
if source.is_empty() {
return None;
}
let source = resolve_external_marketplace_source(&source, source_root);
let ref_name = source_fields
.get("ref")
.or_else(|| value.get("ref"))
.and_then(JsonValue::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned);
let ref_name = source_fields
.get("ref")
.or_else(|| value.get("ref"))
.and_then(JsonValue::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned);
Some((name.clone(), MarketplaceImportSource { source, ref_name }))
Some((name.clone(), MarketplaceImportSource { source, ref_name }))
})
.collect()
})
.collect()
.unwrap_or_default();
if has_enabled_plugin_for_marketplace(settings, EXTERNAL_OFFICIAL_MARKETPLACE_NAME)
&& !import_sources.contains_key(EXTERNAL_OFFICIAL_MARKETPLACE_NAME)
{
import_sources.insert(
EXTERNAL_OFFICIAL_MARKETPLACE_NAME.to_string(),
MarketplaceImportSource {
source: EXTERNAL_OFFICIAL_MARKETPLACE_SOURCE.to_string(),
ref_name: None,
},
);
}
import_sources
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -1289,6 +1289,49 @@ async fn detect_home_supports_relative_external_agent_plugin_marketplace_path()
);
}
#[tokio::test]
async fn detect_home_infers_claude_official_marketplace_when_missing_from_settings() {
let (_root, external_agent_home, codex_home) = fixture_paths();
fs::create_dir_all(&external_agent_home).expect("create external agent home");
fs::create_dir_all(&codex_home).expect("create codex home");
fs::write(
external_agent_home.join("settings.json"),
r#"{
"enabledPlugins": {
"sample@claude-plugins-official": true
}
}"#,
)
.expect("write settings");
let items = service_for_paths(external_agent_home.clone(), codex_home)
.detect(ExternalAgentConfigDetectOptions {
include_home: true,
cwds: None,
})
.await
.expect("detect");
assert_eq!(
items,
vec![ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Plugins,
description: format!(
"Migrate enabled plugins from {}",
external_agent_home.join("settings.json").display()
),
cwd: None,
details: Some(MigrationDetails {
plugins: vec![PluginsMigration {
marketplace_name: "claude-plugins-official".to_string(),
plugin_names: vec!["sample".to_string()],
}],
}),
}]
);
}
#[tokio::test]
async fn import_plugins_supports_relative_external_agent_plugin_marketplace_path() {
let (_root, external_agent_home, codex_home) = fixture_paths();
@@ -1362,6 +1405,46 @@ async fn import_plugins_supports_relative_external_agent_plugin_marketplace_path
assert!(config.contains("enabled = true"));
}
#[tokio::test]
async fn import_plugins_infers_claude_official_marketplace_when_missing_from_settings() {
let (_root, external_agent_home, codex_home) = fixture_paths();
fs::create_dir_all(&external_agent_home).expect("create external agent home");
fs::create_dir_all(&codex_home).expect("create codex home");
fs::write(
external_agent_home.join("settings.json"),
r#"{
"enabledPlugins": {
"sample@claude-plugins-official": true
}
}"#,
)
.expect("write settings");
let outcome = service_for_paths(external_agent_home, codex_home)
.import_plugins(
/*cwd*/ None,
Some(MigrationDetails {
plugins: vec![PluginsMigration {
marketplace_name: "claude-plugins-official".to_string(),
plugin_names: vec!["sample".to_string()],
}],
}),
)
.await
.expect("import plugins");
assert_eq!(
outcome,
PluginImportOutcome {
succeeded_marketplaces: vec!["claude-plugins-official".to_string()],
succeeded_plugin_ids: Vec::new(),
failed_marketplaces: Vec::new(),
failed_plugin_ids: vec!["sample@claude-plugins-official".to_string()],
}
);
}
#[tokio::test]
async fn detect_repo_supports_project_relative_external_agent_plugin_marketplace_path() {
let root = TempDir::new().expect("create tempdir");

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