From 42156ba007278d9068f1518ac1f627b56c136ef6 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Tue, 7 Jul 2026 09:28:52 -0700 Subject: [PATCH 01/95] test(skills): cover plugin namespace loading (#31369) ## Why Before changing plugin namespace loading performance, lock down the existing behavior so the same cases can be validated before and after the optimization. ## What - cover mixed plain and nested plugin skills under one scan root - cover inherited, nested, and invalid-manifest namespace precedence - cover symlinked plugin skill directories, symlinked plain directories, and scan-root ancestor symlinks ## Validation - just test -p codex-core-skills namespace on unmodified main: 12 passed --- codex-rs/core-skills/src/loader_tests.rs | 275 +++++++++++++++++++++++ 1 file changed, 275 insertions(+) diff --git a/codex-rs/core-skills/src/loader_tests.rs b/codex-rs/core-skills/src/loader_tests.rs index 8cd371c9a7..1bdfe39520 100644 --- a/codex-rs/core-skills/src/loader_tests.rs +++ b/codex-rs/core-skills/src/loader_tests.rs @@ -388,6 +388,41 @@ fn write_skill_interface_at(skill_dir: &Path, contents: &str) -> PathBuf { write_skill_metadata_at(skill_dir, contents) } +fn write_plugin_manifest(plugin_root: &Path, contents: &str) { + let manifest_path = plugin_root.join(".codex-plugin/plugin.json"); + fs::create_dir_all(manifest_path.parent().expect("manifest parent")).unwrap(); + fs::write(manifest_path, contents).unwrap(); +} + +async fn load_user_skills_root(root: &Path) -> SkillLoadOutcome { + load_skills_from_roots( + [SkillRoot { + path: root.abs(), + scope: SkillScope::User, + file_system: Arc::clone(&LOCAL_FS), + plugin_id: None, + plugin_namespace: None, + plugin_root: None, + }], + /*plugin_skill_snapshots*/ None, + ) + .await +} + +fn expected_user_skill(path: &Path, name: &str, description: &str) -> SkillMetadata { + SkillMetadata { + name: name.to_string(), + description: description.to_string(), + short_description: None, + interface: None, + dependencies: None, + policy: None, + path_to_skills_md: normalized(path), + scope: SkillScope::User, + plugin_id: None, + } +} + #[tokio::test] async fn loads_skill_dependencies_metadata_from_yaml() { let codex_home = tempfile::tempdir().expect("tempdir"); @@ -1326,6 +1361,246 @@ async fn namespaces_plugin_skills_using_provided_namespace() { ); } +#[tokio::test] +async fn namespaces_nested_plugin_skills_without_namespacing_plain_siblings() { + let root = tempfile::tempdir().expect("tempdir"); + let skills_root = root.path().join("skills"); + let plain_skill_path = + write_skill_at(&skills_root, "plain", "plain-skill", "plain description"); + let plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"nested"}"#); + let plugin_skill_path = write_skill_at( + &plugin_root.join("skills"), + "search", + "plugin-skill", + "plugin description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![ + expected_user_skill( + &plugin_skill_path, + "nested:plugin-skill", + "plugin description" + ), + expected_user_skill(&plain_skill_path, "plain-skill", "plain description"), + ] + ); +} + +#[tokio::test] +async fn inherits_plugin_namespace_from_above_scanned_skills_root() { + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let skill_path = write_skill_at(&skills_root, "search", "search-skill", "search description"); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:search-skill", + "search description", + )] + ); +} + +#[tokio::test] +async fn nearest_valid_nested_plugin_namespace_overrides_outer_namespace() { + let root = tempfile::tempdir().expect("tempdir"); + let outer_plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&outer_plugin_root, r#"{"name":"outer"}"#); + let skills_root = outer_plugin_root.join("skills"); + let nested_plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&nested_plugin_root, r#"{"name":"nested"}"#); + let skill_path = write_skill_at( + &nested_plugin_root.join("skills"), + "search", + "search-skill", + "search description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "nested:search-skill", + "search description", + )] + ); +} + +#[tokio::test] +async fn invalid_nested_plugin_manifest_falls_back_to_outer_namespace() { + let root = tempfile::tempdir().expect("tempdir"); + let outer_plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&outer_plugin_root, r#"{"name":"outer"}"#); + let skills_root = outer_plugin_root.join("skills"); + let nested_plugin_root = skills_root.join("nested-plugin"); + write_plugin_manifest(&nested_plugin_root, "not json"); + let skill_path = write_skill_at( + &nested_plugin_root.join("skills"), + "search", + "search-skill", + "search description", + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:search-skill", + "search description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn namespaces_skills_in_symlinked_plugin_skills_dir() { + // skills/ + // └── linked-plugin -> shared-plugin/skills/ + // shared-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/search/SKILL.md + let root = tempfile::tempdir().expect("tempdir"); + let shared_plugin_root = tempfile::tempdir().expect("tempdir"); + write_plugin_manifest(shared_plugin_root.path(), r#"{"name":"linked"}"#); + let skill_path = write_skill_at( + &shared_plugin_root.path().join("skills"), + "search", + "search-skill", + "search description", + ); + let skills_root = root.path().join("skills"); + fs::create_dir_all(&skills_root).unwrap(); + symlink_dir( + &shared_plugin_root.path().join("skills"), + &skills_root.join("linked-plugin"), + ); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "linked:search-skill", + "search description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn does_not_inherit_namespace_for_skills_in_symlinked_plain_dir() { + // outer-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/linked-plain -> plain-root/ + // plain-root/ + // └── search/SKILL.md + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("outer-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let plain_root = tempfile::tempdir().expect("tempdir"); + let skill_path = write_skill_at( + plain_root.path(), + "search", + "plain-skill", + "plain description", + ); + fs::create_dir_all(&skills_root).unwrap(); + symlink_dir(plain_root.path(), &skills_root.join("linked-plain")); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "plain-skill", + "plain description", + )] + ); +} + +// Directory symlinks on Windows can require Developer Mode or administrator privileges. +#[cfg(unix)] +#[tokio::test] +async fn keeps_inherited_namespace_when_symlink_target_is_scan_root_ancestor() { + // temp-root/ + // └── a/b/c/d/e/f/outer-plugin/ + // ├── .codex-plugin/plugin.json + // └── skills/ + // ├── root/SKILL.md + // └── link -> temp-root/ + let root = tempfile::tempdir().expect("tempdir"); + let plugin_root = root.path().join("a/b/c/d/e/f/outer-plugin"); + write_plugin_manifest(&plugin_root, r#"{"name":"outer"}"#); + let skills_root = plugin_root.join("skills"); + let skill_path = write_skill_at(&skills_root, "root", "root-skill", "root description"); + symlink_dir(root.path(), &skills_root.join("link")); + + let outcome = load_user_skills_root(&skills_root).await; + + assert!( + outcome.errors.is_empty(), + "unexpected errors: {:?}", + outcome.errors + ); + assert_eq!( + outcome.skills, + vec![expected_user_skill( + &skill_path, + "outer:root-skill", + "root description", + )] + ); +} + #[tokio::test] async fn plugin_skill_name_length_limit_allows_max_qualified_name() { let root = tempfile::tempdir().expect("tempdir"); From f363ed70cc1c6e2cae15fc1b8711f7e0d7b96cf1 Mon Sep 17 00:00:00 2001 From: malsamiri-oai Date: Tue, 7 Jul 2026 09:47:21 -0700 Subject: [PATCH 02/95] fix(release): add missing Intel V8 signing entitlement (#30953) ## Why Intel macOS release binaries crash on the first Code Mode tool call while V8 creates its code range. The x86_64 V8 allocator later makes a non-`MAP_JIT` reservation executable, which Hardened Runtime rejects when the signature contains only `com.apple.security.cs.allow-jit`. Tracks [SE-8006](https://linear.app/openai/issue/SE-8006/intel-macos-codex-cli-crashes-in-v8-startup-on-gpt-56-sol-tool-calls). Fixes #28390. ## What - add an expanded entitlement profile only for x86_64 `codex` and `codex-app-server`, the release binaries that link V8 - keep arm64 and `codex-responses-api-proxy` on the existing narrower profile - share one fail-closed target/binary selector between signing and final verification - verify the expected Mach-O architecture and exact entitlement dictionary for the signed binary, tar.gz, zstd, package, and DMG copies ## Verification - `just test-github-scripts` (34 tests) - `UV_CACHE_DIR=/private/tmp/codex-uv-cache just fmt-check` - `bash -n .github/scripts/macos-signing/select_codex_entitlements.sh` - `plutil -lint` on both entitlement profiles - parsed `rust-release.yml` as YAML - `git diff --check` - ad-hoc Hardened Runtime signing smoke on an x86_64 Mach-O slice: strict `codesign` verification passed; the Codex profile contained exactly both keys and the proxy profile retained exactly `allow-jit` ## Release validation Run a native Intel smoke of the final Developer ID-signed x86_64 Codex binary through V8 isolate creation before shipping. PR #30849 is diagnostic scaffolding, but its non-sandbox release job currently fails in the harness before V8 starts, so it is not counted as coverage here. --- .../codex-app-server.entitlements.plist | 10 +++++ .../codex-code-mode-host.entitlements.plist | 10 +++++ ...dex-responses-api-proxy.entitlements.plist | 8 ++++ .../macos-signing/codex.entitlements.plist | 2 + .../test_macos_signing_entitlements.py | 37 ++++++++++++++++++ .github/workflows/rust-release.yml | 38 ++++++++++++++----- 6 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 .github/scripts/macos-signing/codex-app-server.entitlements.plist create mode 100644 .github/scripts/macos-signing/codex-code-mode-host.entitlements.plist create mode 100644 .github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist create mode 100644 .github/scripts/test_macos_signing_entitlements.py diff --git a/.github/scripts/macos-signing/codex-app-server.entitlements.plist b/.github/scripts/macos-signing/codex-app-server.entitlements.plist new file mode 100644 index 0000000000..26b12f2886 --- /dev/null +++ b/.github/scripts/macos-signing/codex-app-server.entitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist b/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist new file mode 100644 index 0000000000..26b12f2886 --- /dev/null +++ b/.github/scripts/macos-signing/codex-code-mode-host.entitlements.plist @@ -0,0 +1,10 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + + diff --git a/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist b/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist new file mode 100644 index 0000000000..d35e43ae58 --- /dev/null +++ b/.github/scripts/macos-signing/codex-responses-api-proxy.entitlements.plist @@ -0,0 +1,8 @@ + + + + + com.apple.security.cs.allow-jit + + + diff --git a/.github/scripts/macos-signing/codex.entitlements.plist b/.github/scripts/macos-signing/codex.entitlements.plist index d35e43ae58..26b12f2886 100644 --- a/.github/scripts/macos-signing/codex.entitlements.plist +++ b/.github/scripts/macos-signing/codex.entitlements.plist @@ -4,5 +4,7 @@ com.apple.security.cs.allow-jit + com.apple.security.cs.allow-unsigned-executable-memory + diff --git a/.github/scripts/test_macos_signing_entitlements.py b/.github/scripts/test_macos_signing_entitlements.py new file mode 100644 index 0000000000..e56d5f3a1b --- /dev/null +++ b/.github/scripts/test_macos_signing_entitlements.py @@ -0,0 +1,37 @@ +import plistlib +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +SIGNING_DIR = ROOT / ".github" / "scripts" / "macos-signing" +ALLOW_JIT = "com.apple.security.cs.allow-jit" +ALLOW_UNSIGNED_EXECUTABLE_MEMORY = ( + "com.apple.security.cs.allow-unsigned-executable-memory" +) + + +class MacosSigningEntitlementsTest(unittest.TestCase): + def load(self, binary: str) -> dict[str, bool]: + path = SIGNING_DIR / f"{binary}.entitlements.plist" + with path.open("rb") as file: + return plistlib.load(file) + + def test_v8_binaries_allow_unsigned_executable_memory(self) -> None: + expected = { + ALLOW_JIT: True, + ALLOW_UNSIGNED_EXECUTABLE_MEMORY: True, + } + for binary in ["codex", "codex-app-server", "codex-code-mode-host"]: + with self.subTest(binary=binary): + self.assertEqual(self.load(binary), expected) + + def test_responses_proxy_keeps_existing_entitlements(self) -> None: + self.assertEqual( + self.load("codex-responses-api-proxy"), + {ALLOW_JIT: True}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index 93f03e63d1..9fdd66637b 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -573,6 +573,12 @@ jobs: zstd -d --stdout "$unsigned_path" >"$signed_path" chmod 0755 "$signed_path" + entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/${binary}.entitlements.plist" + if [[ ! -f "$entitlements" ]]; then + echo "Entitlements file $entitlements not found" + exit 1 + fi + .github/scripts/macos-signing/sign_macos_code.sh \ --target "$signed_path" \ --identity unused \ @@ -580,7 +586,7 @@ jobs: --identifier "$binary" \ --options runtime \ --timestamp true \ - --entitlements .github/scripts/macos-signing/codex.entitlements.plist + --entitlements "$entitlements" mkdir -p "${report_dir}/${binary}" rcodesign print-signature-info "$signed_path" \ @@ -974,15 +980,29 @@ jobs: target="${{ matrix.target }}" packaged_dir="dist/${target}" - expected_entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/codex.entitlements.plist" + case "$target" in + aarch64-apple-darwin) expected_arch="arm64" ;; + x86_64-apple-darwin) expected_arch="x86_64" ;; + *) + echo "Unexpected macOS target: $target" + exit 1 + ;; + esac verify_signed_binary() { local path="$1" - local actual_entitlements normalized_actual normalized_expected + local binary="$2" + local actual_entitlements expected_entitlements normalized_actual normalized_expected chmod 0755 "$path" + lipo "$path" -verify_arch "$expected_arch" codesign --verify --strict --verbose=2 "$path" + expected_entitlements="${GITHUB_WORKSPACE}/.github/scripts/macos-signing/${binary}.entitlements.plist" + if [[ ! -f "$expected_entitlements" ]]; then + echo "Expected entitlements file $expected_entitlements not found" + exit 1 + fi actual_entitlements="$(mktemp)" normalized_actual="$(mktemp)" normalized_expected="$(mktemp)" @@ -995,7 +1015,7 @@ jobs: for binary in ${{ matrix.binaries }}; do binary_path="${RUNNER_TEMP}/signed-binaries/${binary}" - verify_signed_binary "$binary_path" + verify_signed_binary "$binary_path" "$binary" # The app-server package contains the host, but its standalone archives # are omitted above to avoid duplicate release asset names. @@ -1007,11 +1027,11 @@ jobs: rm -rf "$direct_archive_dir" mkdir -p "$direct_archive_dir" tar -xzf "${packaged_dir}/${binary}-${target}.tar.gz" -C "$direct_archive_dir" - verify_signed_binary "${direct_archive_dir}/${binary}-${target}" + verify_signed_binary "${direct_archive_dir}/${binary}-${target}" "$binary" direct_zstd_path="${RUNNER_TEMP}/${binary}-${target}-from-zstd" zstd -d --stdout "${packaged_dir}/${binary}-${target}.zst" >"$direct_zstd_path" - verify_signed_binary "$direct_zstd_path" + verify_signed_binary "$direct_zstd_path" "$binary" done case "${{ matrix.bundle }}" in @@ -1033,8 +1053,8 @@ jobs: rm -rf "$package_dir" mkdir -p "$package_dir" tar -xzf "${packaged_dir}/${package_stem}-${target}.tar.gz" -C "$package_dir" - verify_signed_binary "${package_dir}/bin/${package_entrypoint}" - verify_signed_binary "${package_dir}/bin/codex-code-mode-host" + verify_signed_binary "${package_dir}/bin/${package_entrypoint}" "$package_entrypoint" + verify_signed_binary "${package_dir}/bin/codex-code-mode-host" "codex-code-mode-host" if [[ "${{ matrix.verify_dmg }}" != "true" ]]; then exit 0 @@ -1060,7 +1080,7 @@ jobs: trap cleanup_mount EXIT for binary in ${{ matrix.binaries }}; do - verify_signed_binary "${mount_dir}/${binary}" + verify_signed_binary "${mount_dir}/${binary}" "$binary" done cleanup_mount From a3f8b0b33284054133474e7b1cc5fa7600221d97 Mon Sep 17 00:00:00 2001 From: lt-oai Date: Tue, 7 Jul 2026 09:47:41 -0700 Subject: [PATCH 03/95] refactor: make ExternalAuth return CodexAuth (#31355) ## Summary - refactor `ExternalAuth` to return `CodexAuth` directly - remove the parallel `ExternalAuthTokens` wrapper - preserve existing external bearer and app-server refresh behavior This is a mechanical precursor refactor; it does not add auth capabilities or change recovery behavior. ## Testing - `cargo fmt --all` - `cargo test -q -p codex-login --lib` - `cargo test -q -p codex-app-server --test all external_auth_refreshes_on_unauthorized` --- codex-rs/app-server/src/message_processor.rs | 19 ++- codex-rs/login/src/auth/auth_tests.rs | 13 -- codex-rs/login/src/auth/external_bearer.rs | 24 ++-- codex-rs/login/src/auth/manager.rs | 134 ++++++++----------- codex-rs/login/src/lib.rs | 2 - codex-rs/models-manager/src/manager_tests.rs | 19 +-- 6 files changed, 76 insertions(+), 135 deletions(-) diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 6ae73784ff..29ace7d99f 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -74,10 +74,10 @@ use codex_feedback::CodexFeedback; use codex_goal_extension::GoalService; use codex_home::CodexHomeUserInstructionsProvider; use codex_login::AuthManager; +use codex_login::CodexAuth; use codex_login::auth::ExternalAuth; use codex_login::auth::ExternalAuthRefreshContext; use codex_login::auth::ExternalAuthRefreshReason; -use codex_login::auth::ExternalAuthTokens; use codex_protocol::ThreadId; use codex_protocol::auth::AuthMode as LoginAuthMode; use codex_protocol::protocol::SessionSource; @@ -121,10 +121,7 @@ impl ExternalAuthRefreshBridge { } } - async fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> std::io::Result { + async fn refresh(&self, context: ExternalAuthRefreshContext) -> std::io::Result { let params = ChatgptAuthTokensRefreshParams { reason: Self::map_reason(context.reason), previous_account_id: context.previous_account_id, @@ -162,11 +159,11 @@ impl ExternalAuthRefreshBridge { let response: ChatgptAuthTokensRefreshResponse = serde_json::from_value(result).map_err(std::io::Error::other)?; - Ok(ExternalAuthTokens::chatgpt( - response.access_token, - response.chatgpt_account_id, - response.chatgpt_plan_type, - )) + CodexAuth::from_external_chatgpt_tokens( + response.access_token.as_str(), + response.chatgpt_account_id.as_str(), + response.chatgpt_plan_type.as_deref(), + ) } } @@ -178,7 +175,7 @@ impl ExternalAuth for ExternalAuthRefreshBridge { fn refresh( &self, context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { Box::pin(ExternalAuthRefreshBridge::refresh(self, context)) } } diff --git a/codex-rs/login/src/auth/auth_tests.rs b/codex-rs/login/src/auth/auth_tests.rs index 9509cab456..77d8c4fdfb 100644 --- a/codex-rs/login/src/auth/auth_tests.rs +++ b/codex-rs/login/src/auth/auth_tests.rs @@ -1015,19 +1015,6 @@ async fn refresh_failure_is_scoped_to_the_matching_auth_snapshot() { assert_eq!(manager.refresh_failure_for_auth(&updated_auth), None); } -#[test] -fn external_auth_tokens_without_chatgpt_metadata_cannot_seed_chatgpt_auth() { - let err = AuthDotJson::from_external_tokens(&ExternalAuthTokens::access_token_only( - "test-access-token", - )) - .expect_err("bearer-only external auth should not seed ChatGPT auth"); - - assert_eq!( - err.to_string(), - "external auth tokens are missing ChatGPT metadata" - ); -} - #[tokio::test] async fn external_bearer_only_auth_manager_uses_cached_provider_token() { let script = ProviderAuthScript::new(&["provider-token", "next-token"]).unwrap(); diff --git a/codex-rs/login/src/auth/external_bearer.rs b/codex-rs/login/src/auth/external_bearer.rs index f30d52f434..1dbd2c3eee 100644 --- a/codex-rs/login/src/auth/external_bearer.rs +++ b/codex-rs/login/src/auth/external_bearer.rs @@ -1,7 +1,7 @@ +use super::manager::CodexAuth; use super::manager::ExternalAuth; use super::manager::ExternalAuthFuture; use super::manager::ExternalAuthRefreshContext; -use super::manager::ExternalAuthTokens; use codex_protocol::auth::AuthMode; use codex_protocol::config_types::ModelProviderAuthInfo; use std::fmt; @@ -30,7 +30,7 @@ impl BearerTokenRefresher { clippy::await_holding_invalid_type, reason = "external bearer cache misses intentionally hold cached_token across the provider command to avoid duplicate refreshes" )] - async fn resolve(&self) -> io::Result> { + async fn resolve(&self) -> io::Result> { let access_token = { let mut cached = self.state.cached_token.lock().await; if let Some(cached_token) = cached.as_ref() { @@ -39,8 +39,8 @@ impl BearerTokenRefresher { None => true, }; if should_use_cached_token { - return Ok(Some(ExternalAuthTokens::access_token_only( - cached_token.access_token.clone(), + return Ok(Some(CodexAuth::from_api_key( + cached_token.access_token.as_str(), ))); } } @@ -52,20 +52,17 @@ impl BearerTokenRefresher { }); access_token }; - Ok(Some(ExternalAuthTokens::access_token_only(access_token))) + Ok(Some(CodexAuth::from_api_key(access_token.as_str()))) } - async fn refresh( - &self, - _context: ExternalAuthRefreshContext, - ) -> io::Result { + async fn refresh(&self, _context: ExternalAuthRefreshContext) -> io::Result { let access_token = run_provider_auth_command(&self.state.config).await?; let mut cached = self.state.cached_token.lock().await; *cached = Some(CachedExternalBearerToken { access_token: access_token.clone(), fetched_at: Instant::now(), }); - Ok(ExternalAuthTokens::access_token_only(access_token)) + Ok(CodexAuth::from_api_key(access_token.as_str())) } } @@ -74,14 +71,11 @@ impl ExternalAuth for BearerTokenRefresher { AuthMode::ApiKey } - fn resolve(&self) -> ExternalAuthFuture<'_, Option> { + fn resolve(&self) -> ExternalAuthFuture<'_, Option> { Box::pin(BearerTokenRefresher::resolve(self)) } - fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> ExternalAuthFuture<'_, ExternalAuthTokens> { + fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> { Box::pin(BearerTokenRefresher::refresh(self, context)) } } diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index a2d005dfa6..06d125422c 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -198,45 +198,6 @@ pub enum RefreshTokenError { Transient(#[from] std::io::Error), } -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ExternalAuthTokens { - pub access_token: String, - pub chatgpt_metadata: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ExternalAuthChatgptMetadata { - pub account_id: String, - pub plan_type: Option, -} - -impl ExternalAuthTokens { - pub fn access_token_only(access_token: impl Into) -> Self { - Self { - access_token: access_token.into(), - chatgpt_metadata: None, - } - } - - pub fn chatgpt( - access_token: impl Into, - chatgpt_account_id: impl Into, - chatgpt_plan_type: Option, - ) -> Self { - Self { - access_token: access_token.into(), - chatgpt_metadata: Some(ExternalAuthChatgptMetadata { - account_id: chatgpt_account_id.into(), - plan_type: chatgpt_plan_type, - }), - } - } - - pub fn chatgpt_metadata(&self) -> Option<&ExternalAuthChatgptMetadata> { - self.chatgpt_metadata.as_ref() - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExternalAuthRefreshReason { Unauthorized, @@ -251,22 +212,19 @@ pub struct ExternalAuthRefreshContext { /// Pluggable auth provider used by `AuthManager` for externally managed auth flows. /// /// Implementations may either resolve auth eagerly via `resolve()` or provide refreshed -/// credentials on demand via `refresh()`. +/// auth on demand via `refresh()`. pub trait ExternalAuth: Send + Sync { /// Indicates which top-level auth mode this external provider supplies. fn auth_mode(&self) -> AuthMode; /// Returns cached or immediately available auth, if this provider can resolve it synchronously /// from the caller's perspective. - fn resolve(&self) -> ExternalAuthFuture<'_, Option> { + fn resolve(&self) -> ExternalAuthFuture<'_, Option> { Box::pin(async { Ok(None) }) } /// Refreshes auth in response to a manager-driven refresh attempt. - fn refresh( - &self, - context: ExternalAuthRefreshContext, - ) -> ExternalAuthFuture<'_, ExternalAuthTokens>; + fn refresh(&self, context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth>; } pub type ExternalAuthFuture<'a, T> = Pin> + Send + 'a>>; @@ -747,6 +705,24 @@ impl CodexAuth { Self::Chatgpt(ChatgptAuth { state, storage }) } + /// Constructs in-memory ChatGPT auth from externally managed tokens. + pub fn from_external_chatgpt_tokens( + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, + ) -> std::io::Result { + let auth_dot_json = AuthDotJson::from_external_access_token( + access_token, + chatgpt_account_id, + chatgpt_plan_type, + )?; + let state = ChatgptAuthState { + auth_dot_json: Arc::new(Mutex::new(Some(auth_dot_json))), + client: create_client(), + }; + Ok(Self::ChatgptAuthTokens(ChatgptAuthTokens { state })) + } + pub fn from_api_key(api_key: &str) -> Self { Self::ApiKey(ApiKeyAuth { api_key: api_key.to_owned(), @@ -1456,26 +1432,23 @@ fn refresh_token_endpoint() -> String { } impl AuthDotJson { - fn from_external_tokens(external: &ExternalAuthTokens) -> std::io::Result { - let Some(chatgpt_metadata) = external.chatgpt_metadata() else { - return Err(std::io::Error::other( - "external auth tokens are missing ChatGPT metadata", - )); - }; + fn from_external_access_token( + access_token: &str, + chatgpt_account_id: &str, + chatgpt_plan_type: Option<&str>, + ) -> std::io::Result { let mut token_info = - parse_chatgpt_jwt_claims(&external.access_token).map_err(std::io::Error::other)?; - token_info.chatgpt_account_id = Some(chatgpt_metadata.account_id.clone()); - token_info.chatgpt_plan_type = chatgpt_metadata - .plan_type - .as_deref() + parse_chatgpt_jwt_claims(access_token).map_err(std::io::Error::other)?; + token_info.chatgpt_account_id = Some(chatgpt_account_id.to_string()); + token_info.chatgpt_plan_type = chatgpt_plan_type .map(InternalPlanType::from_raw_value) .or(token_info.chatgpt_plan_type) .or(Some(InternalPlanType::Unknown("unknown".to_string()))); let tokens = TokenData { id_token: token_info, - access_token: external.access_token.clone(), + access_token: access_token.to_string(), refresh_token: String::new(), - account_id: Some(chatgpt_metadata.account_id.clone()), + account_id: Some(chatgpt_account_id.to_string()), }; Ok(Self { @@ -1489,19 +1462,6 @@ impl AuthDotJson { }) } - fn from_external_access_token( - access_token: &str, - chatgpt_account_id: &str, - chatgpt_plan_type: Option<&str>, - ) -> std::io::Result { - let external = ExternalAuthTokens::chatgpt( - access_token, - chatgpt_account_id, - chatgpt_plan_type.map(str::to_string), - ); - Self::from_external_tokens(&external) - } - pub(super) fn resolved_mode(&self) -> AuthMode { if let Some(mode) = self.auth_mode { return mode; @@ -2361,7 +2321,14 @@ impl AuthManager { let external_auth = self.external_auth()?; match external_auth.resolve().await { - Ok(Some(tokens)) => Some(CodexAuth::from_api_key(&tokens.access_token)), + Ok(Some(auth)) if auth.api_auth_mode() == AuthMode::ApiKey => Some(auth), + Ok(Some(auth)) => { + tracing::error!( + resolved_mode = ?auth.api_auth_mode(), + "ignoring non-API-key auth from external API key provider" + ); + None + } Ok(None) => None, Err(err) => { tracing::error!("Failed to resolve external API key auth: {err}"); @@ -2567,23 +2534,30 @@ impl AuthManager { if external_auth.auth_mode() == AuthMode::ApiKey { return Ok(()); } - let Some(chatgpt_metadata) = refreshed.chatgpt_metadata() else { + if refreshed.api_auth_mode() != AuthMode::ChatgptAuthTokens { return Err(RefreshTokenError::Transient(std::io::Error::other( - "external auth refresh did not return ChatGPT metadata", + "external auth refresh did not return ChatGPT auth tokens", ))); - }; + } + let account_id = refreshed.get_account_id().ok_or_else(|| { + RefreshTokenError::Transient(std::io::Error::other( + "external ChatGPT auth tokens are missing an account id", + )) + })?; if let Some(expected_workspace_ids) = forced_chatgpt_workspace_id.as_deref() - && !expected_workspace_ids.contains(&chatgpt_metadata.account_id) + && !expected_workspace_ids.contains(&account_id) { return Err(RefreshTokenError::Transient(std::io::Error::other( format!( - "external auth refresh returned workspace {:?}, expected one of {:?}", - chatgpt_metadata.account_id, expected_workspace_ids, + "external auth refresh returned workspace {account_id:?}, expected one of {expected_workspace_ids:?}" ), ))); } - let auth_dot_json = - AuthDotJson::from_external_tokens(&refreshed).map_err(RefreshTokenError::Transient)?; + let auth_dot_json = refreshed.get_current_auth_json().ok_or_else(|| { + RefreshTokenError::Transient(std::io::Error::other( + "external ChatGPT auth tokens are missing auth state", + )) + })?; save_auth( &self.codex_home, &auth_dot_json, diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index 7ea415fcc5..8a08ddeadb 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -30,11 +30,9 @@ pub use auth::CODEX_ACCESS_TOKEN_ENV_VAR; pub use auth::CODEX_API_KEY_ENV_VAR; pub use auth::CodexAuth; pub use auth::ExternalAuth; -pub use auth::ExternalAuthChatgptMetadata; pub use auth::ExternalAuthFuture; pub use auth::ExternalAuthRefreshContext; pub use auth::ExternalAuthRefreshReason; -pub use auth::ExternalAuthTokens; pub use auth::OPENAI_API_KEY_ENV_VAR; pub use auth::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; pub use auth::REVOKE_TOKEN_URL_OVERRIDE_ENV_VAR; diff --git a/codex-rs/models-manager/src/manager_tests.rs b/codex-rs/models-manager/src/manager_tests.rs index e7d1691a3a..2e97dfac43 100644 --- a/codex-rs/models-manager/src/manager_tests.rs +++ b/codex-rs/models-manager/src/manager_tests.rs @@ -7,7 +7,6 @@ use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::ExternalAuth; use codex_login::ExternalAuthRefreshContext; -use codex_login::ExternalAuthTokens; use codex_login::TokenData; use codex_protocol::auth::AuthMode; use codex_protocol::openai_models::ModelsResponse; @@ -122,23 +121,15 @@ impl ExternalAuth for TestExternalApiKeyAuth { AuthMode::ApiKey } - fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, Option> { - Box::pin(async { - Ok(Some(ExternalAuthTokens::access_token_only( - "test-external-api-key", - ))) - }) + fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, Option> { + Box::pin(async { Ok(Some(CodexAuth::from_api_key("test-external-api-key"))) }) } fn refresh( &self, _context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { - Box::pin(async { - Ok(ExternalAuthTokens::access_token_only( - "test-external-api-key", - )) - }) + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { + Box::pin(async { Ok(CodexAuth::from_api_key("test-external-api-key")) }) } } @@ -153,7 +144,7 @@ impl ExternalAuth for TestUnresolvedExternalApiKeyAuth { fn refresh( &self, _context: ExternalAuthRefreshContext, - ) -> codex_login::ExternalAuthFuture<'_, ExternalAuthTokens> { + ) -> codex_login::ExternalAuthFuture<'_, CodexAuth> { Box::pin(async { Err(std::io::Error::other("unresolved test auth")) }) } } From 8841f506c07ccdb773ca012f2271b852c43fbf52 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Tue, 7 Jul 2026 09:55:27 -0700 Subject: [PATCH 04/95] ci: increase Windows Bazel local test jobs (#31352) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why Windows Bazel test shards currently cap local test actions at 4. Controlled forced-test-execution measurements in #31339 found that 8 local jobs reduced Bazel elapsed time on every shard by 19–29%, including the slow shard from 835.5s to 609.3s, while 12 jobs regressed. ## What Set `common:ci-windows-cross --local_test_jobs=8` in `.bazelrc`. ## Manual validation - `git diff --check` - `just fmt` - [8-job CI experiment](https://github.com/openai/codex/actions/runs/28838387129) --- .bazelrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.bazelrc b/.bazelrc index de01a87443..93fcb0c164 100644 --- a/.bazelrc +++ b/.bazelrc @@ -190,7 +190,7 @@ common:ci-windows-cross --strategy=TestRunner=local # V8 embeds IsolateData offsets in snapshot builtins; Windows snapshots must be # generated by a Windows mksnapshot binary rather than the Linux RBE host tool. common:ci-windows-cross --strategy=V8Mksnapshot=local -common:ci-windows-cross --local_test_jobs=4 +common:ci-windows-cross --local_test_jobs=8 common:ci-windows-cross --test_env=RUST_TEST_THREADS=1 # Native Windows CI still covers the PowerShell parser-process tests. The # cross-built gnullvm binaries currently hang in those tests when run on the From f6e251c3ac6573a4d6eccddea6ad12587868485f Mon Sep 17 00:00:00 2001 From: Alex Zamoshchin Date: Tue, 7 Jul 2026 13:13:59 -0400 Subject: [PATCH 05/95] [codex-rs] Add writes app approval mode (#30482) ## Summary - Adds `writes` to `AppToolApproval` and exposes it through config and app-server schemas, including `[apps._default].default_tools_approval_mode`. - In `writes`, tools with `readOnlyHint = true` skip approval; all other tools prompt, including non-destructive writes and tools without annotations. - Prevents session or persistent approval choices in this mode so later writes still prompt. ## Why `auto` only prompts for risk-hinted actions, while `prompt` also interrupts reads. Apps need a middle mode that gates writes without prompting for declared read-only actions. ## Validation - `just write-config-schema` - `just write-app-server-schema` - `just fmt` - `just test -p codex-core mcp_turn_metadata` (4 passed) - `just test -p codex-core writes_mode` (2 passed) - `just test -p codex-app-server config_read_includes_apps` (1 passed) - `just test -p codex-app-server-protocol` (251 passed) - `just test -p codex-config` (200 passed) - `just test -p codex-cli` (300 passed) - `just fix -p codex-core -p codex-config -p codex-app-server-protocol -p codex-app-server -p codex-cli` --- .../codex_app_server_protocol.schemas.json | 1 + .../codex_app_server_protocol.v2.schemas.json | 1 + .../schema/json/v2/ConfigReadResponse.json | 1 + .../schema/typescript/v2/AppToolApproval.ts | 2 +- .../src/protocol/v2/config.rs | 1 + codex-rs/app-server/README.md | 4 +- .../app-server/tests/suite/v2/config_rpc.rs | 4 +- codex-rs/cli/src/mcp_cmd.rs | 1 + codex-rs/config/src/mcp_edit.rs | 2 + codex-rs/config/src/mcp_types.rs | 1 + codex-rs/core/config.schema.json | 1 + .../core/src/config/edit/document_helpers.rs | 2 + codex-rs/core/src/mcp_tool_call.rs | 30 +++-- codex-rs/core/src/mcp_tool_call_tests.rs | 46 +++++-- .../core/tests/suite/mcp_turn_metadata.rs | 124 ++++++++++++++++++ 15 files changed, 198 insertions(+), 23 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 2ffff2f96f..53bd7cef4e 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -6728,6 +6728,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index dc6e2c9693..11540d40c7 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -854,6 +854,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json index 16f8363416..19863dd1f3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigReadResponse.json @@ -78,6 +78,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts index e92cd8e28b..6704ef0fde 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppToolApproval.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type AppToolApproval = "auto" | "prompt" | "approve"; +export type AppToolApproval = "auto" | "prompt" | "writes" | "approve"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index f615b25d44..24d574a935 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -163,6 +163,7 @@ pub struct AnalyticsConfig { pub enum AppToolApproval { Auto, Prompt, + Writes, Approve, } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 8300c70d94..d52f1bd168 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1879,7 +1879,9 @@ review when allowed by configuration requirements. Use `apps._default.default_tools_approval_mode` to set the approval mode for tools without a per-app or per-tool override. Supported values are `"auto"`, -`"prompt"`, and `"approve"`. Tool-level `approval_mode` takes precedence over +`"prompt"`, `"writes"`, and `"approve"`. The `"writes"` mode prompts for tools +that do not advertise `readOnlyHint = true` and skips declared read-only tools. +Tool-level `approval_mode` takes precedence over the per-app `default_tools_approval_mode`, which takes precedence over the `apps._default` value. Managed tool requirements take precedence over all of these settings. When none are configured, the mode defaults to `"auto"`. diff --git a/codex-rs/app-server/tests/suite/v2/config_rpc.rs b/codex-rs/app-server/tests/suite/v2/config_rpc.rs index 07b8ccc2e8..945ab16d7e 100644 --- a/codex-rs/app-server/tests/suite/v2/config_rpc.rs +++ b/codex-rs/app-server/tests/suite/v2/config_rpc.rs @@ -400,7 +400,7 @@ async fn config_read_includes_apps() -> Result<()> { r#" [apps._default] approvals_reviewer = "auto_review" -default_tools_approval_mode = "approve" +default_tools_approval_mode = "writes" [apps.app1] enabled = false @@ -440,7 +440,7 @@ default_tools_approval_mode = "prompt" approvals_reviewer: Some(ApprovalsReviewer::AutoReview), destructive_enabled: true, open_world_enabled: true, - default_tools_approval_mode: Some(AppToolApproval::Approve), + default_tools_approval_mode: Some(AppToolApproval::Writes), }), apps: std::collections::HashMap::from([( "app1".to_string(), diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index fd0b1a0e4f..848180a517 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -963,6 +963,7 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; println!(" default_tools_approval_mode: {approval_mode}"); diff --git a/codex-rs/config/src/mcp_edit.rs b/codex-rs/config/src/mcp_edit.rs index 16b3904917..ef0d8eae48 100644 --- a/codex-rs/config/src/mcp_edit.rs +++ b/codex-rs/config/src/mcp_edit.rs @@ -198,6 +198,7 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { entry["default_tools_approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } @@ -242,6 +243,7 @@ fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { tool_entry["approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } diff --git a/codex-rs/config/src/mcp_types.rs b/codex-rs/config/src/mcp_types.rs index 550de84a0c..7043e0cb69 100644 --- a/codex-rs/config/src/mcp_types.rs +++ b/codex-rs/config/src/mcp_types.rs @@ -22,6 +22,7 @@ pub enum AppToolApproval { #[default] Auto, Prompt, + Writes, Approve, } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 0a48882b09..fb4d8740ba 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -150,6 +150,7 @@ "enum": [ "auto", "prompt", + "writes", "approve" ], "type": "string" diff --git a/codex-rs/core/src/config/edit/document_helpers.rs b/codex-rs/core/src/config/edit/document_helpers.rs index 308eb9922f..871ca0e41e 100644 --- a/codex-rs/core/src/config/edit/document_helpers.rs +++ b/codex-rs/core/src/config/edit/document_helpers.rs @@ -121,6 +121,7 @@ fn serialize_mcp_server_table(config: &McpServerConfig) -> TomlTable { entry["default_tools_approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } @@ -173,6 +174,7 @@ fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> TomlItem { entry["approval_mode"] = value(match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }); } diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index d03f232d12..63d21504b9 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1223,8 +1223,7 @@ async fn maybe_request_mcp_tool_approval( } let annotations = metadata.and_then(|metadata| metadata.annotations.as_ref()); - let approval_required = requires_mcp_tool_approval(annotations); - if !approval_required && approval_mode != AppToolApproval::Prompt { + if !requires_mcp_tool_approval_for_mode(annotations, approval_mode) { return None; } @@ -1927,12 +1926,13 @@ fn normalize_approval_decision_for_mode( decision: McpToolApprovalDecision, approval_mode: AppToolApproval, ) -> McpToolApprovalDecision { - if approval_mode == AppToolApproval::Prompt - && matches!( - decision, - McpToolApprovalDecision::AcceptForSession | McpToolApprovalDecision::AcceptAndRemember - ) - { + if matches!( + approval_mode, + AppToolApproval::Prompt | AppToolApproval::Writes + ) && matches!( + decision, + McpToolApprovalDecision::AcceptForSession | McpToolApprovalDecision::AcceptAndRemember + ) { McpToolApprovalDecision::Accept } else { decision @@ -2179,6 +2179,20 @@ fn requires_mcp_tool_approval(annotations: Option<&ToolAnnotations>) -> bool { .unwrap_or(true) } +fn requires_mcp_tool_approval_for_mode( + annotations: Option<&ToolAnnotations>, + approval_mode: AppToolApproval, +) -> bool { + match approval_mode { + AppToolApproval::Auto => requires_mcp_tool_approval(annotations), + AppToolApproval::Prompt => true, + AppToolApproval::Writes => !annotations + .and_then(|annotations| annotations.read_only_hint) + .unwrap_or(false), + AppToolApproval::Approve => false, + } +} + async fn notify_mcp_tool_call_skip( sess: &Session, turn_context: &TurnContext, diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index f68d32ff4e..336eecbfdf 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -398,23 +398,47 @@ fn approval_not_required_when_read_only_and_other_hints_are_absent() { } #[test] -fn prompt_mode_does_not_allow_persistent_remember() { +fn writes_mode_requires_approval_for_non_read_only_tools() { + let annotations = annotations(Some(false), Some(false), Some(false)); assert_eq!( - normalize_approval_decision_for_mode( - McpToolApprovalDecision::AcceptForSession, - AppToolApproval::Prompt, - ), - McpToolApprovalDecision::Accept + requires_mcp_tool_approval_for_mode(Some(&annotations), AppToolApproval::Writes), + true ); assert_eq!( - normalize_approval_decision_for_mode( - McpToolApprovalDecision::AcceptAndRemember, - AppToolApproval::Prompt, - ), - McpToolApprovalDecision::Accept + requires_mcp_tool_approval_for_mode(/*annotations*/ None, AppToolApproval::Writes), + true ); } +#[test] +fn writes_mode_does_not_require_approval_for_read_only_tools() { + let annotations = annotations(Some(true), Some(true), Some(true)); + assert_eq!( + requires_mcp_tool_approval_for_mode(Some(&annotations), AppToolApproval::Writes), + false + ); +} + +#[test] +fn prompting_modes_do_not_allow_persistent_remember() { + for approval_mode in [AppToolApproval::Prompt, AppToolApproval::Writes] { + assert_eq!( + normalize_approval_decision_for_mode( + McpToolApprovalDecision::AcceptForSession, + approval_mode, + ), + McpToolApprovalDecision::Accept + ); + assert_eq!( + normalize_approval_decision_for_mode( + McpToolApprovalDecision::AcceptAndRemember, + approval_mode, + ), + McpToolApprovalDecision::Accept + ); + } +} + #[tokio::test] async fn mcp_tool_call_span_records_expected_fields() { let buffer: &'static std::sync::Mutex> = diff --git a/codex-rs/core/tests/suite/mcp_turn_metadata.rs b/codex-rs/core/tests/suite/mcp_turn_metadata.rs index 0d403180d7..0ecaa80274 100644 --- a/codex-rs/core/tests/suite/mcp_turn_metadata.rs +++ b/codex-rs/core/tests/suite/mcp_turn_metadata.rs @@ -20,6 +20,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::PathExt; use core_test_support::apps_test_server::AppsTestServer; use core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL; +use core_test_support::apps_test_server::SEARCH_CALENDAR_LIST_TOOL; use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE; use core_test_support::apps_test_server::recorded_apps_tool_call_by_call_id; use core_test_support::apps_test_server::search_capable_apps_builder; @@ -45,6 +46,7 @@ fn set_calendar_approval_mode(config: &mut Config, approval_mode: AppToolApprova let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; let user_config_path = config.codex_home.join("config.toml").abs(); @@ -68,6 +70,7 @@ fn set_default_app_approval_mode_and_reviewer( let approval_mode = match approval_mode { AppToolApproval::Auto => "auto", AppToolApproval::Prompt => "prompt", + AppToolApproval::Writes => "writes", AppToolApproval::Approve => "approve", }; let user_config_path = config.codex_home.join("config.toml").abs(); @@ -333,6 +336,127 @@ async fn apps_default_prompt_with_auto_review_routes_actual_mcp_approval_to_guar Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn apps_default_writes_prompts_for_writes_but_not_reads() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let apps_server = AppsTestServer::mount(&server).await?; + let read_call_id = "calendar-read"; + let write_call_id = "calendar-write"; + let list_args = serde_json::to_string(&json!({}))?; + let create_args = serde_json::to_string(&json!({ + "title": "Lunch", + "starts_at": "2026-03-10T12:00:00Z" + }))?; + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-read"), + ev_function_call_with_namespace( + read_call_id, + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_LIST_TOOL, + &list_args, + ), + ev_completed("resp-read"), + ]), + sse(vec![ + ev_response_created("resp-write"), + ev_function_call_with_namespace( + write_call_id, + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_CREATE_TOOL, + &create_args, + ), + ev_completed("resp-write"), + ]), + sse(vec![ + ev_response_created("resp-done"), + ev_assistant_message("msg-done", "done"), + ev_completed("resp-done"), + ]), + ], + ) + .await; + + let mut builder = search_capable_apps_builder(apps_server.chatgpt_base_url.clone()) + .with_config(|config| { + config + .features + .enable(Feature::ToolCallMcpElicitation) + .expect("test config should allow feature update"); + set_default_app_approval_mode_and_reviewer( + config, + AppToolApproval::Writes, + ApprovalsReviewer::User, + ); + }); + let test = builder.build(&server).await?; + + submit_user_turn( + &test, + "Use [$calendar](app://calendar) to list events, then create one.", + AskForApproval::OnRequest, + /*collaboration_mode*/ None, + ) + .await?; + + let EventMsg::McpToolCallBegin(read_begin) = wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::McpToolCallBegin(_)) + }) + .await + else { + unreachable!("event guard guarantees McpToolCallBegin"); + }; + assert_eq!(read_begin.call_id, read_call_id); + + let next_route = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::McpToolCallBegin(_) | EventMsg::ElicitationRequest(_) + ) + }) + .await; + let EventMsg::McpToolCallBegin(write_begin) = next_route else { + panic!("read-only app action should not prompt in writes mode"); + }; + assert_eq!(write_begin.call_id, write_call_id); + + let EventMsg::ElicitationRequest(request) = wait_for_event(&test.codex, |event| { + matches!( + event, + EventMsg::ElicitationRequest(_) | EventMsg::TurnComplete(_) + ) + }) + .await + else { + panic!("write app action should prompt in writes mode"); + }; + + test.codex + .submit(Op::ResolveElicitation { + server_name: request.server_name, + request_id: request.id, + decision: ElicitationAction::Accept, + content: None, + meta: None, + }) + .await?; + + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + assert_eq!(responses.requests().len(), 3); + recorded_apps_tool_call_by_call_id(&server, read_call_id).await; + recorded_apps_tool_call_by_call_id(&server, write_call_id).await; + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn mcp_tool_call_metadata_records_prior_request_user_input_tool() -> Result<()> { skip_if_no_network!(Ok(())); From 78df1237d1a7a3b5d9d383acffbf7d3664b5acc7 Mon Sep 17 00:00:00 2001 From: Francis Chalissery Date: Tue, 7 Jul 2026 10:33:42 -0700 Subject: [PATCH 06/95] Handle bio policy errors in Codex (#31439) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - Treat streamed Responses `bio_policy` failures as terminal invalid requests instead of retryable stream errors. - Recognize the new biology policy code and message in the TUI while preserving the legacy `invalid_prompt` contract. - Keep the existing dedicated biology safety notice and add regression/snapshot coverage for all supported error shapes. ## Why [openai/openai#1068559](https://github.com/openai/openai/pull/1068559) gates a Responses API contract change from `invalid_prompt` and the legacy message to `bio_policy` and new biology copy. Without this compatibility change, streamed blocks are retried as transient failures and the OSS TUI falls back to a generic/raw error instead of the dedicated safety notice. ## Validation - `just test -p codex-api` — 137 passed - `just test -p codex-tui app_server_safety_access_errors_render_dedicated_notice` — passed - `just fix -p codex-api` - `just fix -p codex-tui` - `just fmt` - `just test -p codex-tui` — 2,957 passed; two reproducible failures remain in untouched Guardian feature-flag persistence tests: - `update_feature_flags_disabling_guardian_clears_review_policy_and_restores_default` - `update_feature_flags_disabling_guardian_clears_manual_review_policy_without_history` --- codex-rs/codex-api/src/sse/responses.rs | 54 ++++++++++++------- .../tui/src/chatwidget/tests/app_server.rs | 36 ++++++++++--- ...policy_error_renders_dedicated_notice.snap | 11 ++++ codex-rs/tui/src/chatwidget/turn_runtime.rs | 18 +++++-- 4 files changed, 89 insertions(+), 30 deletions(-) create mode 100644 codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 265d3ced5c..70f96cb855 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -398,7 +398,8 @@ pub fn process_responses_event( } else if is_cyber_policy_error(&error) { let message = cyber_policy_message(error.message); response_error = ApiError::CyberPolicy { message }; - } else if is_invalid_prompt_error(&error) { + } else if matches!(error.code.as_deref(), Some("invalid_prompt" | "bio_policy")) + { let message = error .message .unwrap_or_else(|| "Invalid request.".to_string()); @@ -632,10 +633,6 @@ fn is_usage_not_included(error: &Error) -> bool { error.code.as_deref() == Some("usage_not_included") } -fn is_invalid_prompt_error(error: &Error) -> bool { - error.code.as_deref() == Some("invalid_prompt") -} - fn is_cyber_policy_error(error: &Error) -> bool { error.code.as_deref() == Some("cyber_policy") } @@ -1076,23 +1073,42 @@ mod tests { } #[tokio::test] - async fn invalid_prompt_without_type_is_invalid_request() { - let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_invalid_prompt_no_type","object":"response","created_at":1759771628,"status":"failed","background":false,"error":{"code":"invalid_prompt","message":"Invalid prompt: we've limited access to this content for safety reasons."},"incomplete_details":null}}"#; + async fn content_policy_errors_without_type_are_invalid_requests() { + for (code, expected_message) in [ + ( + "invalid_prompt", + "Invalid prompt: we've limited access to this content for safety reasons.", + ), + ( + "bio_policy", + "This content was flagged for possible biological risk.", + ), + ] { + let raw_error = json!({ + "type": "response.failed", + "sequence_number": 3, + "response": { + "id": "resp_content_policy_no_type", + "object": "response", + "created_at": 1759771628, + "status": "failed", + "background": false, + "error": { "code": code, "message": expected_message }, + "incomplete_details": null, + }, + }) + .to_string(); + let sse1 = format!("event: response.failed\ndata: {raw_error}\n\n"); - let sse1 = format!("event: response.failed\ndata: {raw_error}\n\n"); + let events = collect_events(&[sse1.as_bytes()]).await; - let events = collect_events(&[sse1.as_bytes()]).await; - - assert_eq!(events.len(), 1); - - match &events[0] { - Err(ApiError::InvalidRequest { message }) => { - assert_eq!( - message, - "Invalid prompt: we've limited access to this content for safety reasons." - ); + assert_eq!(events.len(), 1); + match &events[0] { + Err(ApiError::InvalidRequest { message }) => { + assert_eq!(message, expected_message); + } + other => panic!("unexpected event for {code}: {other:?}"), } - other => panic!("unexpected event: {other:?}"), } } diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index 952aff9f95..28e3cbae3e 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -1182,11 +1182,26 @@ async fn live_app_server_cyber_policy_error_renders_dedicated_notice() { #[tokio::test] async fn app_server_safety_access_errors_render_dedicated_notice() { - let message = "Invalid prompt: we've limited access to this content for safety reasons."; - for message in [ - message.to_string(), - json!({ "error": { "message": message } }).to_string(), - ] { + let legacy_message = "Invalid prompt: we've limited access to this content for safety reasons."; + let bio_policy_message = "This content was flagged for possible biological risk."; + let cases = [ + ("legacy plain message", legacy_message.to_string()), + ( + "legacy JSON message", + json!({ "error": { "message": legacy_message } }).to_string(), + ), + ("bio policy plain message", bio_policy_message.to_string()), + ( + "bio policy JSON message", + json!({ "error": { "message": bio_policy_message } }).to_string(), + ), + ( + "bio policy code", + json!({ "error": { "code": "bio_policy", "message": "copy may change" } }).to_string(), + ), + ]; + let mut rendered_cases = Vec::new(); + for (case, message) in cases { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; chat.handle_non_retry_error(message, /*codex_error_info*/ None); @@ -1195,8 +1210,17 @@ async fn app_server_safety_access_errors_render_dedicated_notice() { let rendered = lines_to_single_string(&cells[0]); assert!(rendered.contains("This content can't be shown")); assert!(rendered.contains("biological research")); - assert!(!rendered.contains("Invalid prompt:")); + rendered_cases.push((case, rendered)); } + + let canonical = &rendered_cases[0].1; + for (case, rendered) in &rendered_cases[1..] { + assert_eq!(rendered, canonical, "unexpected rendering for {case}"); + } + insta::assert_snapshot!( + "app_server_bio_policy_error_renders_dedicated_notice", + rendered_cases.last().unwrap().1.as_str() + ); } #[tokio::test] diff --git a/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap new file mode 100644 index 0000000000..3149943b64 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/tests/snapshots/codex_tui__chatwidget__tests__app_server__app_server_bio_policy_error_renders_dedicated_notice.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests/app_server.rs +expression: rendered_cases.last().unwrap().1.as_str() +--- +ⓘ This content can't be shown + We take extra caution with requests involving biological research and + applications that could pose safety risks. Eligible researchers can apply + for Trusted Access. + Trusted Access: https://www.openai.com/form/trusted-access-for-biology- + research/ + Learn more: https://help.openai.com/en/articles/20001326 diff --git a/codex-rs/tui/src/chatwidget/turn_runtime.rs b/codex-rs/tui/src/chatwidget/turn_runtime.rs index fdfad7f6d8..d71a60820e 100644 --- a/codex-rs/tui/src/chatwidget/turn_runtime.rs +++ b/codex-rs/tui/src/chatwidget/turn_runtime.rs @@ -5,8 +5,15 @@ use super::*; -const SAFETY_ACCESS_BLOCK_PREFIX: &str = +const LEGACY_SAFETY_ACCESS_BLOCK_PREFIX: &str = "Invalid prompt: we've limited access to this content for safety reasons."; +const BIO_POLICY_SAFETY_ACCESS_BLOCK_PREFIX: &str = + "This content was flagged for possible biological risk."; + +fn is_safety_access_block_message(message: &str) -> bool { + message.starts_with(LEGACY_SAFETY_ACCESS_BLOCK_PREFIX) + || message.starts_with(BIO_POLICY_SAFETY_ACCESS_BLOCK_PREFIX) +} impl ChatWidget { /// Synchronize the bottom-pane "task running" indicator with the current lifecycles. @@ -430,11 +437,12 @@ impl ChatWidget { .is_some_and(is_app_server_cyber_policy_error) { self.on_cyber_policy_error(); - } else if message.starts_with(SAFETY_ACCESS_BLOCK_PREFIX) + } else if is_safety_access_block_message(&message) || serde_json::from_str::(&message).is_ok_and(|response| { - response["error"]["message"] - .as_str() - .is_some_and(|message| message.starts_with(SAFETY_ACCESS_BLOCK_PREFIX)) + response["error"]["code"].as_str() == Some("bio_policy") + || response["error"]["message"] + .as_str() + .is_some_and(is_safety_access_block_message) }) { self.input_queue.submit_pending_steers_after_interrupt = false; From 1345c16dd79849eafc5b4a826fa7e534df424810 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Tue, 7 Jul 2026 10:49:06 -0700 Subject: [PATCH 07/95] [codex] add connector runtime latency metrics (#31319) ## Summary - measure successful legacy `app/list` latency with `codex.apps.installed.duration_ms`, segmented by `path=legacy` and `reload` - measure successful host-owned `codex_apps` startup and explicit refresh latency with `codex.apps.refresh.duration_ms` - add the refresh trigger to successful `codex.mcp.tools.fetch_uncached.duration_ms` samples for `codex_apps` without changing other MCP-server samples ## Why This establishes a small latency baseline for the current connector path before `ConnectorRuntimeManager`, `app/installed`, and `app/read` land. Error-rate and broader runtime-state instrumentation are intentionally deferred. This is telemetry-only and does not change connector behavior. ## Validation - `just test -p codex-mcp` (94 passed) - `just test -p codex-app-server list_apps` (13 passed) - `just fix -p codex-mcp` - `just fix -p codex-app-server` - `just fmt` - `git diff --check` --- .../src/request_processors/apps_processor.rs | 35 ++++++++++++++++--- codex-rs/codex-mcp/src/connection_manager.rs | 21 ++++++----- codex-rs/codex-mcp/src/rmcp_client.rs | 33 +++++++++++++---- 3 files changed, 68 insertions(+), 21 deletions(-) diff --git a/codex-rs/app-server/src/request_processors/apps_processor.rs b/codex-rs/app-server/src/request_processors/apps_processor.rs index 67d768fa57..5ff7ec40db 100644 --- a/codex-rs/app-server/src/request_processors/apps_processor.rs +++ b/codex-rs/app-server/src/request_processors/apps_processor.rs @@ -47,6 +47,8 @@ impl AppsRequestProcessor { request_id: &ConnectionRequestId, params: AppsListParams, ) -> Result, JSONRPCErrorError> { + let installed_start = Instant::now(); + let reload = params.force_refetch; let thread = if let Some(thread_id) = params.thread_id.as_deref() { let (_, loaded_thread) = self.load_thread(thread_id).await?; Some(loaded_thread) @@ -70,20 +72,24 @@ impl AppsRequestProcessor { .features .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)) { - return Ok(Some(AppsListResponse { + let response = AppsListResponse { data: Vec::new(), next_cursor: None, - })); + }; + record_legacy_apps_installed_duration(installed_start, reload); + return Ok(Some(response)); } if !self .workspace_codex_plugins_enabled(&config, auth.as_ref()) .await { - return Ok(Some(AppsListResponse { + let response = AppsListResponse { data: Vec::new(), next_cursor: None, - })); + }; + record_legacy_apps_installed_duration(installed_start, reload); + return Ok(Some(response)); } let request = request_id.clone(); @@ -103,6 +109,7 @@ impl AppsRequestProcessor { environment_manager, mcp_manager, plugins_manager, + installed_start, ) => {} } }); @@ -113,6 +120,7 @@ impl AppsRequestProcessor { self.shutdown_token.cancel(); } + #[allow(clippy::too_many_arguments)] async fn apps_list_task( outgoing: Arc, request_id: ConnectionRequestId, @@ -121,7 +129,9 @@ impl AppsRequestProcessor { environment_manager: Arc, mcp_manager: Arc, plugins_manager: Arc, + installed_start: Instant, ) { + let reload = params.force_refetch; let retry_params = params.clone(); let retry_config = config.clone(); let retry_environment_manager = Arc::clone(&environment_manager); @@ -136,6 +146,9 @@ impl AppsRequestProcessor { plugins_manager, ) .await; + if result.is_ok() { + record_legacy_apps_installed_duration(installed_start, reload); + } let should_retry = result .as_ref() .is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready); @@ -363,6 +376,20 @@ impl AppsRequestProcessor { } const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90); +// `app/list` is the legacy request-path baseline for the future `app/installed` endpoint; +// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards. +const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms"; + +fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) { + let reload = if reload { "true" } else { "false" }; + if let Some(metrics) = codex_otel::global() { + let _ = metrics.record_duration( + APPS_INSTALLED_DURATION_METRIC, + started_at.elapsed(), + &[("path", "legacy"), ("reload", reload)], + ); + } +} enum AppListLoadResult { Accessible(Result), diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index 2143e3b577..223d4296d5 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -23,8 +23,8 @@ use crate::elicitation::ElicitationReviewerHandle; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::ToolPluginProvenance; use crate::rmcp_client::AsyncManagedClient; +use crate::rmcp_client::CODEX_APPS_REFRESH_DURATION_METRIC; use crate::rmcp_client::DEFAULT_STARTUP_TIMEOUT; -use crate::rmcp_client::MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC; use crate::rmcp_client::MCP_TOOLS_LIST_DURATION_METRIC; use crate::rmcp_client::ManagedClient; use crate::rmcp_client::StartupOutcomeError; @@ -530,6 +530,7 @@ impl McpConnectionManager { /// cache is enabled and the latest filtered tools are returned directly to /// the caller. On failure, existing shared cache contents remain unchanged. pub async fn hard_refresh_codex_apps_tools_cache(&self) -> Result> { + let refresh_start = Instant::now(); let managed_client = self .clients .get(CODEX_APPS_MCP_SERVER_NAME) @@ -539,7 +540,6 @@ impl McpConnectionManager { .context("failed to get client")?; let list_start = Instant::now(); - let fetch_start = Instant::now(); let fetch_ticket = managed_client .codex_apps_tools_cache_context .as_ref() @@ -547,6 +547,7 @@ impl McpConnectionManager { let tools = list_tools_for_client_uncached( CODEX_APPS_MCP_SERVER_NAME, /*is_codex_apps_mcp_server*/ true, + /*codex_apps_refresh_trigger*/ "explicit", &managed_client.client, managed_client.tool_timeout, managed_client.server_instructions.as_deref(), @@ -555,11 +556,6 @@ impl McpConnectionManager { .with_context(|| { format!("failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'") })?; - emit_duration( - MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, - fetch_start.elapsed(), - &[], - ); let tools = match ( @@ -582,10 +578,13 @@ impl McpConnectionManager { tool.tool = tool_with_model_visible_input_schema(&tool.tool); self.with_server_metadata(tool) }); - Ok(normalize_tools_for_model_with_prefix( - tools, - self.prefix_mcp_tool_names, - )) + let tools = normalize_tools_for_model_with_prefix(tools, self.prefix_mcp_tool_names); + emit_duration( + CODEX_APPS_REFRESH_DURATION_METRIC, + refresh_start.elapsed(), + &[("path", "legacy"), ("trigger", "explicit")], + ); + Ok(tools) } /// Returns resources from servers selected by `include_server`. Each key diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index 37819203f6..6fe820b4fe 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -82,6 +82,7 @@ pub const OPENAI_FORM_CAPABILITY: &str = "openai/form"; pub(crate) const MCP_TOOLS_LIST_DURATION_METRIC: &str = "codex.mcp.tools.list.duration_ms"; pub(crate) const MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC: &str = "codex.mcp.tools.fetch_uncached.duration_ms"; +pub(crate) const CODEX_APPS_REFRESH_DURATION_METRIC: &str = "codex.apps.refresh.duration_ms"; pub(crate) const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(30); pub(crate) const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(300); @@ -304,6 +305,7 @@ impl ManagedClientStartup { .unwrap_or_default(); let cancel_token_for_fut = cancel_token; async move { + let refresh_start = is_codex_apps_mcp_server.then(Instant::now); let outcome = match async { if let Err(error) = validate_mcp_server_name(&server_name) { return Err(error.into()); @@ -349,6 +351,15 @@ impl ManagedClientStartup { Ok(result) => result, Err(CancelErr::Cancelled) => Err(StartupOutcomeError::Cancelled), }; + if outcome.is_ok() + && let Some(refresh_start) = refresh_start + { + emit_duration( + CODEX_APPS_REFRESH_DURATION_METRIC, + refresh_start.elapsed(), + &[("path", "legacy"), ("trigger", "initial")], + ); + } startup_complete.store(true, Ordering::Release); outcome @@ -564,10 +575,12 @@ impl From for StartupOutcomeError { pub(crate) async fn list_tools_for_client_uncached( server_name: &str, is_codex_apps_mcp_server: bool, + codex_apps_refresh_trigger: &'static str, client: &Arc, timeout: Option, server_instructions: Option<&str>, ) -> Result> { + let fetch_start = Instant::now(); let resp = client .list_tools_with_connector_ids(/*params*/ None, timeout) .await?; @@ -583,6 +596,19 @@ pub(crate) async fn list_tools_for_client_uncached( ) }) .collect(); + if is_codex_apps_mcp_server { + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[("trigger", codex_apps_refresh_trigger)], + ); + } else { + emit_duration( + MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, + fetch_start.elapsed(), + &[], + ); + } Ok(tools) } @@ -820,24 +846,19 @@ async fn start_server_task( .and_then(|exp| exp.get(MCP_SANDBOX_STATE_META_CAPABILITY)) .is_some(); let list_start = Instant::now(); - let fetch_start = Instant::now(); let fetch_ticket = codex_apps_tools_cache_context .as_ref() .map(|cache_context| cache_context.begin_fetch(CodexAppsToolsFetchSource::Startup)); let tools = list_tools_for_client_uncached( &server_name, is_codex_apps_mcp_server, + /*codex_apps_refresh_trigger*/ "initial", &client, startup_timeout, initialize_result.instructions.as_deref(), ) .await .map_err(StartupOutcomeError::from)?; - emit_duration( - MCP_TOOLS_FETCH_UNCACHED_DURATION_METRIC, - fetch_start.elapsed(), - &[], - ); let server_info = mcp_server_info_from_implementation(initialize_result.server_info); let tools = match (codex_apps_tools_cache_context.as_ref(), fetch_ticket) { (Some(cache_context), Some(fetch_ticket)) => { From 358575465c65182cf77e6a1e6da395eb00ba51cf Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Tue, 7 Jul 2026 10:52:38 -0700 Subject: [PATCH 08/95] Use model catalog approval messages (#31312) ## Why Approval guidance is currently assembled entirely by the client. Model Messages V2 needs model catalogs to provide model-specific `on_request` guidance for both user-reviewed and auto-reviewed approval flows while retaining the existing generated prompt as a compatibility fallback. ## What changed - add nullable `on_request` and `on_request_auto_review` catalog messages - select the message matching the active approvals reviewer for `on_request` policies - replace the complete legacy approval section when the selected catalog value exists, including support for an empty string that suppresses the section - retain legacy rendering when the object or selected key is absent, and for non-`on_request` policies - preserve approval messages when base-instruction or personality overrides clear instruction templates - refresh permissions instructions when the active model changes - pass catalog messages through initial and incremental permissions construction ## Relationship to reviewer persistence PR #31309 independently persists the approvals reviewer in turn context and refreshes permissions when that reviewer changes. This PR is based directly on `main` and does not duplicate that rollout migration; once both land, reviewer switches will also select and append the new catalog variant. ## Testing - `just test -p codex-protocol` - `just test -p codex-prompts` - `just test -p codex-models-manager` - `just test -p codex-core permissions_messages` --- codex-rs/core/src/context/mod.rs | 1 + .../src/context/permissions_instructions.rs | 1 + codex-rs/core/src/context_manager/updates.rs | 10 +- codex-rs/core/src/session/mod.rs | 10 +- codex-rs/core/src/session/tests.rs | 17 +-- .../core/tests/suite/permissions_messages.rs | 130 +++++++++++++++++- codex-rs/core/tests/suite/personality.rs | 2 + codex-rs/models-manager/src/model_info.rs | 15 +- .../models-manager/src/model_info_tests.rs | 63 +++++++++ codex-rs/prompts/src/lib.rs | 1 + .../prompts/src/permissions_instructions.rs | 33 ++++- .../src/permissions_instructions_tests.rs | 114 ++++++++++++++- codex-rs/protocol/src/openai_models.rs | 42 ++++++ 13 files changed, 419 insertions(+), 20 deletions(-) diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index da7db0b373..20b35e7af3 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -62,6 +62,7 @@ pub(crate) use legacy_unified_exec_process_limit_warning::LegacyUnifiedExecProce pub(crate) use model_switch_instructions::ModelSwitchInstructions; pub(crate) use multi_agent_mode_instructions::MultiAgentModeInstructions; pub(crate) use network_rule_saved::NetworkRuleSaved; +pub use permissions_instructions::ApprovalPromptContext; pub use permissions_instructions::PermissionsInstructions; pub(crate) use personality_spec_instructions::PersonalitySpecInstructions; pub(crate) use plugin_instructions::PluginInstructions; diff --git a/codex-rs/core/src/context/permissions_instructions.rs b/codex-rs/core/src/context/permissions_instructions.rs index 73629a3d53..3dd1bbac92 100644 --- a/codex-rs/core/src/context/permissions_instructions.rs +++ b/codex-rs/core/src/context/permissions_instructions.rs @@ -1 +1,2 @@ +pub use codex_prompts::ApprovalPromptContext; pub use codex_prompts::PermissionsInstructions; diff --git a/codex-rs/core/src/context_manager/updates.rs b/codex-rs/core/src/context_manager/updates.rs index a520e6f595..d4cf65e86d 100644 --- a/codex-rs/core/src/context_manager/updates.rs +++ b/codex-rs/core/src/context_manager/updates.rs @@ -1,3 +1,4 @@ +use crate::context::ApprovalPromptContext; use crate::context::CollaborationModeInstructions; use crate::context::ContextualUserFragment; use crate::context::ModelSwitchInstructions; @@ -30,6 +31,7 @@ fn build_permissions_update_item( let prev = previous?; if prev.permission_profile() == next.permission_profile() && prev.approval_policy == next.approval_policy.value() + && prev.model == next.model_info.slug { return None; } @@ -38,7 +40,13 @@ fn build_permissions_update_item( PermissionsInstructions::from_permission_profile( &next.permission_profile, next.approval_policy.value(), - next.config.approvals_reviewer, + ApprovalPromptContext::new( + next.config.approvals_reviewer, + next.model_info + .model_messages + .as_ref() + .and_then(|messages| messages.approvals.as_ref()), + ), exec_policy, #[allow(deprecated)] &next.cwd, diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index fa240b890b..af2412e5c4 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -21,6 +21,7 @@ use crate::build_available_skills; use crate::compact; use crate::config::ManagedFeatures; use crate::config::resolve_tool_suggest_config_from_layer_stack; +use crate::context::ApprovalPromptContext; use crate::context::ApprovedCommandPrefixSaved; use crate::context::AvailableSkillsInstructions; use crate::context::CollaborationModeInstructions; @@ -3206,7 +3207,14 @@ impl Session { PermissionsInstructions::from_permission_profile( &turn_context.permission_profile, turn_context.approval_policy.value(), - turn_context.config.approvals_reviewer, + ApprovalPromptContext::new( + turn_context.config.approvals_reviewer, + turn_context + .model_info + .model_messages + .as_ref() + .and_then(|messages| messages.approvals.as_ref()), + ), self.services.exec_policy.current().as_ref(), #[allow(deprecated)] &turn_context.cwd, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5ebce9aa42..ac8f9d049e 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -9041,18 +9041,13 @@ async fn record_context_updates_and_set_reference_context_item_reinjects_full_co #[tokio::test] async fn record_context_updates_and_set_reference_context_item_persists_baseline_without_emitting_diffs() { - let (mut session, previous_context) = make_session_and_context().await; - let next_model = if previous_context.model_info.slug == "gpt-5.4" { - "gpt-5.2" - } else { - "gpt-5.4" - }; - let turn_context = previous_context - .with_model(next_model.to_string(), &session.services.models_manager) - .await; - let previous_context_item = previous_context.to_turn_context_item(); - let previous_context = Arc::new(previous_context); + let (mut session, turn_context) = make_session_and_context().await; + let previous_context_item = turn_context.to_turn_context_item(); + let previous_context = Arc::new(turn_context); let world_state = build_world_state_from_turn_context(&session, &previous_context).await; + let mut turn_context = Arc::try_unwrap(previous_context) + .unwrap_or_else(|_| panic!("previous turn context should have no remaining references")); + turn_context.sub_id = format!("{}-next", turn_context.sub_id); { let mut state = session.state.lock().await; state.set_reference_context_item(Some(previous_context_item.clone())); diff --git a/codex-rs/core/tests/suite/permissions_messages.rs b/codex-rs/core/tests/suite/permissions_messages.rs index e5a69962bc..7f42ba893c 100644 --- a/codex-rs/core/tests/suite/permissions_messages.rs +++ b/codex-rs/core/tests/suite/permissions_messages.rs @@ -2,10 +2,15 @@ use anyhow::Result; use codex_config::ConfigLayerStack; use codex_core::ForkSnapshot; use codex_core::config::Constrained; +use codex_core::context::ApprovalPromptContext; use codex_core::context::ContextualUserFragment; use codex_core::context::PermissionsInstructions; use codex_core::load_exec_policy; +use codex_models_manager::model_info::model_info_from_slug; use codex_protocol::models::PermissionProfile; +use codex_protocol::openai_models::ApprovalMessages; +use codex_protocol::openai_models::ModelMessages; +use codex_protocol::openai_models::ModelsResponse; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -33,6 +38,129 @@ fn permissions_texts(request: &ResponsesRequest) -> Vec { .collect() } +fn model_with_approval_messages( + slug: &str, + on_request: &str, + on_request_auto_review: &str, +) -> codex_protocol::openai_models::ModelInfo { + let mut model = model_info_from_slug(slug); + model.model_messages = Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(ApprovalMessages { + on_request: Some(on_request.to_string()), + on_request_auto_review: Some(on_request_auto_review.to_string()), + }), + }); + model +} + +async fn submit_text_turn( + test: &core_test_support::test_codex::TestCodex, + text: &str, +) -> Result<()> { + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn catalog_approval_message_is_sent_in_initial_permissions() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let req = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + ) + .await; + let model_slug = "catalog-approvals-model"; + let model = model_with_approval_messages( + model_slug, + "catalog user approval instructions", + "catalog auto-review approval instructions", + ); + let mut builder = test_codex() + .with_model(model_slug) + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + }); + let test = builder.build(&server).await?; + + submit_text_turn(&test, "hello").await?; + + let permissions = permissions_texts(&req.single_request()); + assert_eq!(permissions.len(), 1); + assert!(permissions[0].contains("catalog user approval instructions")); + assert!(permissions[0].contains("Filesystem sandboxing defines")); + assert!(!permissions[0].contains("How to request escalation")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn model_change_appends_new_catalog_approval_message() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let _req1 = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + ) + .await; + let req2 = mount_sse_once( + &server, + sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]), + ) + .await; + let first_slug = "catalog-approvals-model-a"; + let second_slug = "catalog-approvals-model-b"; + let first = model_with_approval_messages(first_slug, "model A approvals", "model A auto"); + let second = model_with_approval_messages(second_slug, "model B approvals", "model B auto"); + let mut builder = test_codex() + .with_model(first_slug) + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); + config.model_catalog = Some(ModelsResponse { + models: vec![first, second], + }); + }); + let test = builder.build(&server).await?; + submit_text_turn(&test, "first").await?; + + core_test_support::submit_thread_settings( + &test.codex, + codex_protocol::protocol::ThreadSettingsOverrides { + model: Some(second_slug.to_string()), + ..Default::default() + }, + ) + .await?; + submit_text_turn(&test, "second").await?; + + let permissions = permissions_texts(&req2.single_request()); + assert_eq!(permissions.len(), 2); + assert!( + permissions + .last() + .is_some_and(|text| text.contains("model B approvals")) + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn permissions_message_sent_once_on_start() -> Result<()> { skip_if_no_network!(Ok(())); @@ -563,7 +691,7 @@ async fn permissions_message_includes_writable_roots() -> Result<()> { let expected = PermissionsInstructions::from_permission_profile( &permission_profile, AskForApproval::OnRequest, - test.config.approvals_reviewer, + ApprovalPromptContext::new(test.config.approvals_reviewer, /*messages*/ None), &exec_policy, test.config.cwd.as_path(), /*exec_permission_approvals_enabled*/ false, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index e74695b59d..88733b4666 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -573,6 +573,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow personality_friendly: Some(friendly_personality_message.to_string()), personality_pragmatic: Some("Pragmatic variant".to_string()), }), + approvals: None, }), include_skills_usage_instructions: false, supports_reasoning_summaries: false, @@ -689,6 +690,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - personality_friendly: Some(remote_friendly_message.to_string()), personality_pragmatic: Some(remote_pragmatic_message.to_string()), }), + approvals: None, }), include_skills_usage_instructions: false, supports_reasoning_summaries: false, diff --git a/codex-rs/models-manager/src/model_info.rs b/codex-rs/models-manager/src/model_info.rs index 573403b728..75d333efe3 100644 --- a/codex-rs/models-manager/src/model_info.rs +++ b/codex-rs/models-manager/src/model_info.rs @@ -54,14 +54,24 @@ pub fn with_config_overrides(mut model: ModelInfo, config: &ModelsManagerConfig) if let Some(base_instructions) = &config.base_instructions { model.base_instructions = base_instructions.clone(); - model.model_messages = None; + clear_instruction_messages(&mut model); } else if !config.personality_enabled { - model.model_messages = None; + clear_instruction_messages(&mut model); } model } +fn clear_instruction_messages(model: &mut ModelInfo) { + if let Some(model_messages) = &mut model.model_messages { + model_messages.instructions_template = None; + model_messages.instructions_variables = None; + if model_messages.approvals.is_none() { + model.model_messages = None; + } + } +} + /// Build a minimal fallback model descriptor for missing/unknown slugs. pub fn model_info_from_slug(slug: &str) -> ModelInfo { warn!("Unknown model {slug} is used. This will use fallback model metadata."); @@ -119,6 +129,7 @@ fn local_personality_messages_for_slug(slug: &str) -> Option { personality_friendly: Some(LOCAL_FRIENDLY_TEMPLATE.to_string()), personality_pragmatic: Some(LOCAL_PRAGMATIC_TEMPLATE.to_string()), }), + approvals: None, }), _ => None, } diff --git a/codex-rs/models-manager/src/model_info_tests.rs b/codex-rs/models-manager/src/model_info_tests.rs index 70ad3da8df..2240f0a391 100644 --- a/codex-rs/models-manager/src/model_info_tests.rs +++ b/codex-rs/models-manager/src/model_info_tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::ModelsManagerConfig; +use codex_protocol::openai_models::ApprovalMessages; use pretty_assertions::assert_eq; #[test] @@ -44,6 +45,68 @@ fn reasoning_summaries_override_false_is_noop_when_model_is_false() { assert_eq!(updated, model); } +#[test] +fn base_instruction_override_preserves_catalog_approval_messages() { + let mut model = model_info_from_slug("unknown-model"); + let approvals = ApprovalMessages { + on_request: Some("user approvals".to_string()), + on_request_auto_review: Some("auto approvals".to_string()), + }; + model.model_messages = Some(ModelMessages { + instructions_template: Some("template".to_string()), + instructions_variables: Some(ModelInstructionsVariables { + personality_default: Some("default".to_string()), + personality_friendly: Some("friendly".to_string()), + personality_pragmatic: Some("pragmatic".to_string()), + }), + approvals: Some(approvals.clone()), + }); + let config = ModelsManagerConfig { + base_instructions: Some("override".to_string()), + ..Default::default() + }; + + let updated = with_config_overrides(model, &config); + + assert_eq!( + updated.model_messages, + Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(approvals), + }) + ); +} + +#[test] +fn disabled_personality_preserves_catalog_approval_messages() { + let mut model = model_info_from_slug("unknown-model"); + let approvals = ApprovalMessages { + on_request: Some("user approvals".to_string()), + on_request_auto_review: None, + }; + model.model_messages = Some(ModelMessages { + instructions_template: Some("template".to_string()), + instructions_variables: None, + approvals: Some(approvals.clone()), + }); + let config = ModelsManagerConfig { + personality_enabled: false, + ..Default::default() + }; + + let updated = with_config_overrides(model, &config); + + assert_eq!( + updated.model_messages, + Some(ModelMessages { + instructions_template: None, + instructions_variables: None, + approvals: Some(approvals), + }) + ); +} + #[test] fn model_context_window_override_clamps_to_max_context_window() { let mut model = model_info_from_slug("unknown-model"); diff --git a/codex-rs/prompts/src/lib.rs b/codex-rs/prompts/src/lib.rs index 5a30358393..c598b2d765 100644 --- a/codex-rs/prompts/src/lib.rs +++ b/codex-rs/prompts/src/lib.rs @@ -12,6 +12,7 @@ pub use compact::SUMMARY_PREFIX; pub use goals::budget_limit_prompt; pub use goals::continuation_prompt; pub use goals::objective_updated_prompt; +pub use permissions_instructions::ApprovalPromptContext; pub use permissions_instructions::PermissionsInstructions; pub use realtime::BACKEND_PROMPT; pub use realtime::END_INSTRUCTIONS; diff --git a/codex-rs/prompts/src/permissions_instructions.rs b/codex-rs/prompts/src/permissions_instructions.rs index c382b804a0..1c19d008cf 100644 --- a/codex-rs/prompts/src/permissions_instructions.rs +++ b/codex-rs/prompts/src/permissions_instructions.rs @@ -4,6 +4,7 @@ use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::SandboxMode; use codex_protocol::models::PermissionProfile; use codex_protocol::models::format_allow_prefixes; +use codex_protocol::openai_models::ApprovalMessages; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; @@ -47,6 +48,7 @@ static SANDBOX_MODE_READ_ONLY_TEMPLATE: LazyLock