From 1f17e7512f0e47625f2cad416f14870688a99814 Mon Sep 17 00:00:00 2001 From: Brent Traut Date: Fri, 3 Jul 2026 13:06:07 -0700 Subject: [PATCH 01/17] Fix MIME types for path-backed feedback attachments (#30796) ## Why Path-backed feedback attachments were always labeled `text/plain`, even when the attached file was a gzip archive. Sentry consumers could therefore UTF-8-decode a valid Codex Desktop log bundle and corrupt the transferred bytes before anyone inspected it. Desktop already creates a valid archive and sends its path through `feedback/upload`; the bad metadata was assigned later by app-server's feedback upload path. Slack investigation: https://openai.slack.com/archives/C09NZ54M4KY/p1782867266569699 ## What changed Path-backed feedback attachments now derive their MIME type from the final uploaded filename. Gzip files use `application/gzip`, known text formats remain text, and unrecognized files use the safe `application/octet-stream` fallback. Attachment filenames and bytes are unchanged. ## How it works - **Classify at the upload boundary:** The feedback crate selects MIME metadata after resolving the final filename, including filename overrides. - **Preserve text rollouts:** Codex `.jsonl` rollouts remain `text/plain`, while other known formats use the repository's existing `mime_guess` mapping. - **Protect unknown binaries:** Unrecognized extensions fall back to `application/octet-stream` instead of being treated as UTF-8 text. - **Keep the wire stable:** `feedback/upload` still accepts the same path list, so Desktop, generated protocol surfaces, and remote-host minimums do not change. ## Verification Added focused coverage for gzip MIME, unknown binary fallback, `.jsonl` text handling, and exact filename/byte preservation. Ran the complete `codex-feedback` test suite (9 tests), crate-scoped Clippy, Rust formatting, Bazel lock refresh, and diff checks successfully. --- codex-rs/Cargo.lock | 1 + codex-rs/feedback/Cargo.toml | 1 + codex-rs/feedback/src/lib.rs | 75 +++++++++++++++++++++++++++++++++++- 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 3561550db5..6ac51d403f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3077,6 +3077,7 @@ dependencies = [ "anyhow", "codex-login", "codex-protocol", + "mime_guess", "pretty_assertions", "sentry", "tracing", diff --git a/codex-rs/feedback/Cargo.toml b/codex-rs/feedback/Cargo.toml index 032f0398be..dd89ddb76b 100644 --- a/codex-rs/feedback/Cargo.toml +++ b/codex-rs/feedback/Cargo.toml @@ -11,6 +11,7 @@ workspace = true anyhow = { workspace = true } codex-login = { workspace = true } codex-protocol = { workspace = true } +mime_guess = { workspace = true } sentry = { version = "0.46" } tracing = { workspace = true } tracing-subscriber = { workspace = true } diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 7c27d2b3b0..cd97349c48 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -4,6 +4,7 @@ use std::collections::btree_map::Entry; use std::fs; use std::io::Write; use std::io::{self}; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; @@ -593,10 +594,22 @@ impl FeedbackSnapshot { .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "extra-log.log".to_string()) }); + let content_type = match Path::new(&filename) + .extension() + .and_then(|extension| extension.to_str()) + { + Some(extension) if extension.eq_ignore_ascii_case("jsonl") => { + "text/plain".to_string() + } + _ => mime_guess::from_path(&filename) + .first_or_octet_stream() + .essence_str() + .to_string(), + }; attachments.push(Attachment { buffer: data, filename, - content_type: Some("text/plain".to_string()), + content_type: Some(content_type), ty: None, }); } @@ -774,6 +787,10 @@ mod tests { b"Connectivity diagnostics\n\n- Proxy environment variables are set and may affect connectivity.\n - HTTPS_PROXY = https://example.com:443".to_vec() ); assert_eq!(attachments_with_diagnostics[3].buffer, b"rollout".to_vec()); + assert_eq!( + attachments_with_diagnostics[3].content_type.as_deref(), + Some("text/plain") + ); assert_eq!( OsStr::new(attachments_with_diagnostics[3].filename.as_str()), OsStr::new(extra_filename.as_str()) @@ -794,6 +811,62 @@ mod tests { fs::remove_file(extra_path).expect("extra attachment should be removed"); } + #[test] + fn path_backed_attachments_use_binary_content_types() { + let suffix = ThreadId::new(); + let gzip_filename = format!("codex-desktop-app-logs-{suffix}.tar.gz"); + let unknown_filename = format!("codex-feedback-extra-{suffix}.binunknown"); + let gzip_path = std::env::temp_dir().join(&gzip_filename); + let unknown_path = std::env::temp_dir().join(&unknown_filename); + let gzip_bytes = b"\x1f\x8b\x08\x00\xff"; + let unknown_bytes = b"\x00\x9f\x92\x96"; + fs::write(&gzip_path, gzip_bytes).expect("gzip attachment should be written"); + fs::write(&unknown_path, unknown_bytes).expect("unknown attachment should be written"); + + let attachments = CodexFeedback::new() + .snapshot(/*session_id*/ None) + .feedback_attachments( + /*include_logs*/ false, + &[], + &[ + FeedbackAttachmentPath { + path: gzip_path.clone(), + attachment_filename_override: None, + }, + FeedbackAttachmentPath { + path: unknown_path.clone(), + attachment_filename_override: None, + }, + ], + /*logs_override*/ None, + ); + + fs::remove_file(gzip_path).expect("gzip attachment should be removed"); + fs::remove_file(unknown_path).expect("unknown attachment should be removed"); + assert_eq!( + attachments + .iter() + .map(|attachment| ( + attachment.filename.as_str(), + attachment.content_type.as_deref(), + attachment.buffer.as_slice(), + )) + .collect::>(), + vec![ + ( + gzip_filename.as_str(), + Some("application/gzip"), + gzip_bytes.as_slice(), + ), + ( + unknown_filename.as_str(), + Some("application/octet-stream"), + unknown_bytes.as_slice(), + ), + ] + ); + } + #[test] fn upload_tags_include_client_tags_and_preserve_reserved_fields() { let mut tags = BTreeMap::new(); From 319d03056e9b345fe9d129873c3a808c5df783df Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 3 Jul 2026 15:11:19 -0700 Subject: [PATCH 02/17] fix(install): reuse GitHub release metadata (#31056) ## Why The standalone installers currently perform separate unauthenticated GitHub REST API lookups while resolving the latest version, locating the platform package, locating its checksum manifest, and retrieving asset digests. A single install can therefore make up to four release-metadata requests. When GitHub's shared unauthenticated rate limit is exhausted, valid releases fail to install. The shell installer also suppresses the metadata request failure while probing assets, so a `403` is misreported as though the release assets do not exist. This makes the failure both more likely and harder to diagnose. Fixes #28538. ## What changed - Resolve the selected version and fetch its release metadata together. - Reuse that one metadata response for package, checksum, and legacy-package selection in both `install.sh` and `install.ps1`. - Report metadata fetch failures as possible GitHub availability or rate-limit failures instead of missing assets. - Add a mocked-`curl` regression suite covering exact releases, `latest`, and a simulated metadata `403`, and run it in `repo-checks`. For `latest`, the metadata returned by `/releases/latest` now supplies both the resolved version and the asset list. For an explicitly selected version, the installer makes one request to that release's tag endpoint. ## Verification - `python3 -m unittest discover -s scripts/install -p 'test_*.py' -v` - `sh -n scripts/install/install.sh` - Parsed `scripts/install/install.ps1` with the PowerShell language parser. ## Scope This change reduces GitHub API usage and preserves the underlying error, but it does not move release artifacts away from GitHub's CDN. --- .github/workflows/repo-checks.yml | 3 + scripts/install/install.ps1 | 65 ++++++------ scripts/install/install.sh | 69 +++++++------ scripts/install/test_install_sh.py | 159 +++++++++++++++++++++++++++++ 4 files changed, 232 insertions(+), 64 deletions(-) create mode 100644 scripts/install/test_install_sh.py diff --git a/.github/workflows/repo-checks.yml b/.github/workflows/repo-checks.yml index 3a76a202ea..3d0504172d 100644 --- a/.github/workflows/repo-checks.yml +++ b/.github/workflows/repo-checks.yml @@ -28,6 +28,9 @@ jobs: - name: Test Codex package builder run: python3 -m unittest discover -s scripts/codex_package -p 'test_*.py' + - name: Test standalone installer + run: python3 -m unittest discover -s scripts/install -p 'test_*.py' + - name: Setup pnpm uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5 with: diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1 index 6973d482e2..986f6c6566 100644 --- a/scripts/install/install.ps1 +++ b/scripts/install/install.ps1 @@ -79,11 +79,10 @@ function Assert-ValidReleaseVersion { function Find-ReleaseAssetMetadata { param( [string]$AssetName, - [string]$ResolvedVersion + [object]$ReleaseMetadata ) - $release = Invoke-RestMethod -Uri "https://api.github.com/repos/openai/codex/releases/tags/rust-v$ResolvedVersion" - $asset = $release.assets | Where-Object { $_.name -eq $AssetName } | Select-Object -First 1 + $asset = $ReleaseMetadata.assets | Where-Object { $_.name -eq $AssetName } | Select-Object -First 1 if ($null -eq $asset) { return $null } @@ -99,20 +98,6 @@ function Find-ReleaseAssetMetadata { } } -function Get-ReleaseAssetMetadata { - param( - [string]$AssetName, - [string]$ResolvedVersion - ) - - $metadata = Find-ReleaseAssetMetadata -AssetName $AssetName -ResolvedVersion $ResolvedVersion - if ($null -eq $metadata) { - throw "Could not find release asset $AssetName for Codex $ResolvedVersion." - } - - return $metadata -} - function Test-ArchiveDigest { param( [string]$ArchivePath, @@ -216,22 +201,38 @@ function Remove-StaleInstallArtifacts { } } -function Resolve-Version { +function Resolve-Release { $normalizedVersion = Normalize-Version -RawVersion $Release Assert-ValidReleaseVersion -Version $normalizedVersion - if ($normalizedVersion -ne "latest") { - return $normalizedVersion + + if ($normalizedVersion -eq "latest") { + $requestedRelease = "latest" + $metadataUri = "https://api.github.com/repos/openai/codex/releases/latest" + } else { + $resolvedVersion = $normalizedVersion + $requestedRelease = $resolvedVersion + $metadataUri = "https://api.github.com/repos/openai/codex/releases/tags/rust-v$resolvedVersion" } - $release = Invoke-RestMethod -Uri "https://api.github.com/repos/openai/codex/releases/latest" - if (-not $release.tag_name) { - Write-Error "Failed to resolve the latest Codex release version." - exit 1 + try { + $releaseMetadata = Invoke-RestMethod -Uri $metadataUri + } catch { + throw "Could not fetch GitHub release metadata for Codex $requestedRelease. GitHub API may be unavailable or rate limited. $($_.Exception.Message)" } - $resolvedVersion = Normalize-Version -RawVersion $release.tag_name - Assert-ValidReleaseVersion -Version $resolvedVersion - return $resolvedVersion + if ($normalizedVersion -eq "latest") { + if (-not $releaseMetadata.tag_name) { + throw "Failed to resolve the latest Codex release version." + } + + $resolvedVersion = Normalize-Version -RawVersion $releaseMetadata.tag_name + Assert-ValidReleaseVersion -Version $resolvedVersion + } + + return [PSCustomObject]@{ + Version = $resolvedVersion + Metadata = $releaseMetadata + } } function Get-VersionFromBinary { @@ -746,7 +747,9 @@ if ([string]::IsNullOrWhiteSpace($env:CODEX_INSTALL_DIR)) { } $currentVersion = Get-CurrentInstalledVersion -StandaloneCurrentDir $currentDir -$resolvedVersion = Resolve-Version +$resolvedRelease = Resolve-Release +$resolvedVersion = $resolvedRelease.Version +$releaseMetadata = $resolvedRelease.Metadata $releaseName = "$resolvedVersion-$target" $releaseDir = Join-Path $releasesDir $releaseName @@ -765,12 +768,12 @@ $oldStandaloneBackup = $null $packageAsset = "codex-package-$target.tar.gz" $checksumAsset = "codex-package_SHA256SUMS" -$packageMetadata = Find-ReleaseAssetMetadata -AssetName $packageAsset -ResolvedVersion $resolvedVersion -$checksumMetadata = Find-ReleaseAssetMetadata -AssetName $checksumAsset -ResolvedVersion $resolvedVersion +$packageMetadata = Find-ReleaseAssetMetadata -AssetName $packageAsset -ReleaseMetadata $releaseMetadata +$checksumMetadata = Find-ReleaseAssetMetadata -AssetName $checksumAsset -ReleaseMetadata $releaseMetadata $installLayout = "Package" if ($null -eq $packageMetadata -or $null -eq $checksumMetadata) { $packageAsset = "codex-npm-$npmTag-$resolvedVersion.tgz" - $packageMetadata = Find-ReleaseAssetMetadata -AssetName $packageAsset -ResolvedVersion $resolvedVersion + $packageMetadata = Find-ReleaseAssetMetadata -AssetName $packageAsset -ReleaseMetadata $releaseMetadata if ($null -ne $packageMetadata) { $installLayout = "LegacyPlatformNpm" } else { diff --git a/scripts/install/install.sh b/scripts/install/install.sh index 7513efc429..d44b353860 100755 --- a/scripts/install/install.sh +++ b/scripts/install/install.sh @@ -138,10 +138,36 @@ release_metadata_url() { printf 'https://api.github.com/repos/openai/codex/releases/tags/rust-v%s\n' "$resolved_version" } +resolve_release() { + normalized_version="$(normalize_version "$RELEASE")" + validate_version "$normalized_version" + + if [ "$normalized_version" = "latest" ]; then + requested_release="latest" + metadata_url="https://api.github.com/repos/openai/codex/releases/latest" + else + resolved_version="$normalized_version" + requested_release="$resolved_version" + metadata_url="$(release_metadata_url "$resolved_version")" + fi + + if ! release_json="$(download_text "$metadata_url")"; then + echo "Could not fetch GitHub release metadata for Codex $requested_release. GitHub API may be unavailable or rate limited." >&2 + exit 1 + fi + + if [ "$normalized_version" = "latest" ]; then + resolved_version="$(printf '%s\n' "$release_json" | sed -n 's/.*"tag_name":[[:space:]]*"rust-v\([^"]*\)".*/\1/p' | head -n 1)" + if [ -z "$resolved_version" ]; then + echo "Failed to resolve the latest Codex release version." >&2 + exit 1 + fi + validate_version "$resolved_version" + fi +} + release_asset_digest_or_empty() { asset="$1" - resolved_version="$2" - release_json="$(download_text "$(release_metadata_url "$resolved_version")")" digest="$(printf '%s\n' "$release_json" | awk -v asset="$asset" ' /"name":[[:space:]]*"[^"]+"/ { @@ -190,16 +216,14 @@ release_asset_digest_or_empty() { release_asset_exists() { asset="$1" - resolved_version="$2" - release_asset_digest_or_empty "$asset" "$resolved_version" >/dev/null 2>&1 + release_asset_digest_or_empty "$asset" >/dev/null 2>&1 } release_asset_digest() { asset="$1" - resolved_version="$2" - digest="$(release_asset_digest_or_empty "$asset" "$resolved_version" || true)" + digest="$(release_asset_digest_or_empty "$asset" || true)" if [ -z "$digest" ]; then echo "Could not find SHA-256 digest for release asset $asset." >&2 exit 1 @@ -275,27 +299,6 @@ require_command() { fi } -resolve_version() { - normalized_version="$(normalize_version "$RELEASE")" - validate_version "$normalized_version" - - if [ "$normalized_version" != "latest" ]; then - printf '%s\n' "$normalized_version" - return - fi - - release_json="$(download_text "https://api.github.com/repos/openai/codex/releases/latest")" - resolved="$(printf '%s\n' "$release_json" | sed -n 's/.*"tag_name":[[:space:]]*"rust-v\([^"]*\)".*/\1/p' | head -n 1)" - - if [ -z "$resolved" ]; then - echo "Failed to resolve the latest Codex release version." >&2 - exit 1 - fi - - validate_version "$resolved" - printf '%s\n' "$resolved" -} - pick_profile() { # Use the same shell-specific split Homebrew documents because there is no # universal startup file across macOS/Linux login and interactive shells. @@ -839,14 +842,14 @@ else fi fi -resolved_version="$(resolve_version)" +resolve_release package_asset="codex-package-$vendor_target.tar.gz" checksum_asset="codex-package_SHA256SUMS" -if release_asset_exists "$package_asset" "$resolved_version" && - release_asset_exists "$checksum_asset" "$resolved_version"; then +if release_asset_exists "$package_asset" && + release_asset_exists "$checksum_asset"; then install_layout="package" asset="$package_asset" -elif release_asset_exists "codex-npm-$npm_tag-$resolved_version.tgz" "$resolved_version"; then +elif release_asset_exists "codex-npm-$npm_tag-$resolved_version.tgz"; then install_layout="legacy-platform-npm" asset="codex-npm-$npm_tag-$resolved_version.tgz" else @@ -893,12 +896,12 @@ if ! release_dir_is_complete "$release_dir" "$resolved_version" "$vendor_target" step "Downloading Codex CLI" if [ "$install_layout" = "package" ]; then - checksum_digest="$(release_asset_digest "$checksum_asset" "$resolved_version")" + checksum_digest="$(release_asset_digest "$checksum_asset")" download_file "$checksum_url" "$checksum_path" verify_archive_digest "$checksum_path" "$checksum_digest" expected_digest="$(package_archive_digest "$asset" "$checksum_path")" else - expected_digest="$(release_asset_digest "$asset" "$resolved_version")" + expected_digest="$(release_asset_digest "$asset")" fi download_file "$download_url" "$archive_path" verify_archive_digest "$archive_path" "$expected_digest" diff --git a/scripts/install/test_install_sh.py b/scripts/install/test_install_sh.py new file mode 100644 index 0000000000..556c6213bb --- /dev/null +++ b/scripts/install/test_install_sh.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 + +import json +import os +from pathlib import Path +import subprocess +import tempfile +import textwrap +import unittest + + +INSTALL_SCRIPT = Path(__file__).with_name("install.sh") +VERSION = "0.142.5" + + +class InstallShTest(unittest.TestCase): + def test_metadata_fetch_failure_is_not_reported_as_missing_assets(self) -> None: + result, requests = run_installer(VERSION, metadata_failure=True) + + self.assertNotEqual(result.returncode, 0) + self.assertEqual( + requests, + [ + "https://api.github.com/repos/openai/codex/releases/tags/" + f"rust-v{VERSION}" + ], + ) + self.assertIn( + f"Could not fetch GitHub release metadata for Codex {VERSION}", + result.stderr, + ) + self.assertNotIn("Could not find Codex package", result.stderr) + + def test_exact_release_fetches_metadata_once(self) -> None: + result, requests = run_installer(VERSION) + + self.assertNotEqual(result.returncode, 0) + self.assertEqual( + requests, + [ + "https://api.github.com/repos/openai/codex/releases/tags/" + f"rust-v{VERSION}", + "https://github.com/openai/codex/releases/download/" + f"rust-v{VERSION}/codex-package_SHA256SUMS", + ], + ) + self.assertIn(f"Resolved version: {VERSION}", result.stdout) + + def test_latest_release_reuses_version_metadata(self) -> None: + result, requests = run_installer("latest") + + self.assertNotEqual(result.returncode, 0) + self.assertEqual( + requests, + [ + "https://api.github.com/repos/openai/codex/releases/latest", + "https://github.com/openai/codex/releases/download/" + f"rust-v{VERSION}/codex-package_SHA256SUMS", + ], + ) + self.assertIn(f"Resolved version: {VERSION}", result.stdout) + + +def run_installer( + release: str, *, metadata_failure: bool = False +) -> tuple[subprocess.CompletedProcess[str], list[str]]: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + bin_dir = root / "bin" + bin_dir.mkdir() + request_log = root / "requests.log" + fake_curl = bin_dir / "curl" + fake_curl.write_text( + textwrap.dedent( + """\ + #!/bin/sh + url="" + for arg in "$@"; do + case "$arg" in + https://*) url="$arg" ;; + esac + done + printf '%s\n' "$url" >>"$CODEX_TEST_REQUEST_LOG" + + case "$url" in + https://api.github.com/*) + if [ "$CODEX_TEST_METADATA_FAILURE" = "1" ]; then + echo "curl: (22) The requested URL returned error: 403" >&2 + exit 22 + fi + printf '%s\n' "$CODEX_TEST_METADATA_JSON" + ;; + *) + exit 22 + ;; + esac + """ + ), + encoding="utf-8", + ) + fake_curl.chmod(0o755) + + env = os.environ.copy() + env.update( + { + "CODEX_HOME": str(root / "codex-home"), + "CODEX_INSTALL_DIR": str(root / "install-bin"), + "CODEX_NON_INTERACTIVE": "1", + "CODEX_RELEASE": release, + "CODEX_TEST_METADATA_FAILURE": "1" if metadata_failure else "0", + "CODEX_TEST_METADATA_JSON": release_metadata(), + "CODEX_TEST_REQUEST_LOG": str(request_log), + "HOME": str(root / "home"), + "PATH": f"{bin_dir}:/usr/bin:/bin", + "SHELL": "/bin/sh", + } + ) + result = subprocess.run( + ["/bin/sh", str(INSTALL_SCRIPT)], + capture_output=True, + check=False, + env=env, + text=True, + ) + requests = ( + request_log.read_text(encoding="utf-8").splitlines() + if request_log.exists() + else [] + ) + return result, requests + + +def release_metadata() -> str: + assets = [ + { + "name": f"codex-package-{target}.tar.gz", + "digest": f"sha256:{'a' * 64}", + } + for target in ( + "aarch64-apple-darwin", + "x86_64-apple-darwin", + "aarch64-unknown-linux-musl", + "x86_64-unknown-linux-musl", + ) + ] + assets.append( + { + "name": "codex-package_SHA256SUMS", + "digest": f"sha256:{'b' * 64}", + } + ) + return json.dumps( + {"tag_name": f"rust-v{VERSION}", "assets": assets}, + indent=2, + ) + + +if __name__ == "__main__": + unittest.main() From d206a5d68f1240b51f13a8364c20a4de307737d0 Mon Sep 17 00:00:00 2001 From: Eric Ning Date: Fri, 3 Jul 2026 17:14:49 -0600 Subject: [PATCH 03/17] [codex] expose remote plugin versions (#30981) --- .../codex_app_server_protocol.schemas.json | 8 +++++++ .../codex_app_server_protocol.v2.schemas.json | 8 +++++++ .../json/v2/PluginInstalledResponse.json | 8 +++++++ .../schema/json/v2/PluginListResponse.json | 8 +++++++ .../schema/json/v2/PluginReadResponse.json | 8 +++++++ .../json/v2/PluginShareListResponse.json | 8 +++++++ .../schema/typescript/v2/PluginSummary.ts | 4 ++++ .../src/protocol/v2/plugin.rs | 3 +++ .../src/protocol/v2/tests.rs | 2 ++ codex-rs/app-server/README.md | 2 +- .../src/request_processors/plugins.rs | 3 +++ .../app-server/tests/suite/v2/plugin_list.rs | 21 ++++++++++++++++++- .../app-server/tests/suite/v2/plugin_share.rs | 3 +++ codex-rs/core-plugins/src/manager_tests.rs | 1 + codex-rs/core-plugins/src/remote.rs | 5 +++++ .../core-plugins/src/remote/share/tests.rs | 2 ++ codex-rs/tui/src/app/plugin_mentions.rs | 1 + codex-rs/tui/src/chatwidget/tests/helpers.rs | 2 ++ 18 files changed, 95 insertions(+), 2 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 a717ec3428..53139c82d8 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 @@ -14350,6 +14350,14 @@ }, "source": { "$ref": "#/definitions/v2/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ 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 6155844a8b..961dd14f3e 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 @@ -10754,6 +10754,14 @@ }, "source": { "$ref": "#/definitions/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json index 4c5b205538..55ad95be2e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginInstalledResponse.json @@ -540,6 +540,14 @@ }, "source": { "$ref": "#/definitions/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json index 62b9ac19ea..25d12e50dd 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginListResponse.json @@ -540,6 +540,14 @@ }, "source": { "$ref": "#/definitions/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json index ad63129bf8..b4b917602a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json @@ -680,6 +680,14 @@ }, "source": { "$ref": "#/definitions/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json index 7c6f486240..751a6c5e7f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginShareListResponse.json @@ -496,6 +496,14 @@ }, "source": { "$ref": "#/definitions/PluginSource" + }, + "version": { + "default": null, + "description": "Version advertised by the remote marketplace backend when available.", + "type": [ + "string", + "null" + ] } }, "required": [ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts b/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts index 268349cb9b..d12f55b3a3 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/PluginSummary.ts @@ -13,6 +13,10 @@ export type PluginSummary = { id: string, * Backend remote plugin identifier when available. */ remotePluginId: string | null, +/** + * Version advertised by the remote marketplace backend when available. + */ +version: string | null, /** * Version of the locally materialized plugin package when available. */ diff --git a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs index 148fe2f2a4..19a4ccd889 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs @@ -600,6 +600,9 @@ pub struct PluginSummary { pub id: String, /// Backend remote plugin identifier when available. pub remote_plugin_id: Option, + /// Version advertised by the remote marketplace backend when available. + #[serde(default)] + pub version: Option, /// Version of the locally materialized plugin package when available. #[serde(default)] pub local_version: Option, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index 48f92bf785..77d8a1439b 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -3642,6 +3642,7 @@ fn plugin_share_list_response_serializes_share_items() { remote_plugin_id: Some( "plugins~Plugin_00000000000000000000000000000000".to_string(), ), + version: None, local_version: None, name: "gmail".to_string(), share_context: None, @@ -3663,6 +3664,7 @@ fn plugin_share_list_response_serializes_share_items() { "plugin": { "id": "gmail@openai-curated-remote", "remotePluginId": "plugins~Plugin_00000000000000000000000000000000", + "version": null, "localVersion": null, "name": "gmail", "shareContext": null, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index c9ac2f5fb2..43e7dbd3eb 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -213,7 +213,7 @@ Example with notification opt-out: - `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. - `marketplace/upgrade` — upgrade all configured Git plugin marketplaces, or one named marketplace when `marketplaceName` is provided. Returns selected marketplace names, upgraded roots, and per-marketplace errors. -- `plugin/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, plugin `availability` (`AVAILABLE` by default or `DISABLED_BY_ADMIN` for remote plugins blocked upstream), fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. Clients can explicitly request the remote `workspace-directory`, `shared-with-me`, or `created-by-me-remote` marketplace kinds. `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/list` — list discovered plugin marketplaces and plugin state, including effective marketplace install/auth policy metadata, the remote marketplace `version` and locally materialized `localVersion` when available, plugin `availability` (`AVAILABLE` by default or `DISABLED_BY_ADMIN` for remote plugins blocked upstream), fail-open `marketplaceLoadErrors` entries for marketplace files that could not be parsed or loaded, and best-effort `featuredPluginIds` for the official curated marketplace. Clients can explicitly request the remote `workspace-directory`, `shared-with-me`, or `created-by-me-remote` marketplace kinds. `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/installed` — list installed plugin rows plus any explicitly requested local install-suggestion plugin names, without fetching the broader remote catalog. Mention surfaces can use this narrower view when they need plugin mention payloads rather than plugin-page discovery data (**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/hooks/apps/MCP server names. Remote plugin details expose the canonical `shareUrl` supplied by the remote catalog when available; it is `null` for local plugins or when the catalog omits it. This field is separate from `summary.shareContext`, which continues to describe user and workspace sharing state. Returned plugin skills include their current `enabled` state after local config filtering; bundled hooks are returned as lightweight declaration summaries keyed for correlation with `hooks/list`. Use `plugin/install`'s `appsNeedingAuth` to drive post-install authentication and `app/list`'s `isAccessible` to determine current connector accessibility (**under development; do not call from production clients yet**). - `plugin/skill/read` — read remote plugin skill markdown on demand by `remoteMarketplaceName`, `remotePluginId`, and `skillName`. This lets clients preview uninstalled remote plugin skills without downloading the plugin bundle. diff --git a/codex-rs/app-server/src/request_processors/plugins.rs b/codex-rs/app-server/src/request_processors/plugins.rs index 020fdc7cbd..35c12d49c1 100644 --- a/codex-rs/app-server/src/request_processors/plugins.rs +++ b/codex-rs/app-server/src/request_processors/plugins.rs @@ -155,6 +155,7 @@ fn convert_configured_marketplace_plugin_to_plugin_summary( PluginSummary { id: plugin.id, remote_plugin_id: None, + version: None, local_version: plugin.local_version, installed: plugin.installed, enabled: plugin.enabled, @@ -1095,6 +1096,7 @@ impl PluginRequestProcessor { summary: PluginSummary { id: outcome.plugin.id, remote_plugin_id: None, + version: None, local_version: outcome.plugin.local_version, name: outcome.plugin.name, share_context, @@ -2168,6 +2170,7 @@ fn remote_plugin_summary_to_info(summary: RemoteCatalogPluginSummary) -> PluginS PluginSummary { id: summary.id, remote_plugin_id: Some(summary.remote_plugin_id), + version: summary.version, local_version: summary.local_version, name: summary.name, share_context: summary diff --git a/codex-rs/app-server/tests/suite/v2/plugin_list.rs b/codex-rs/app-server/tests/suite/v2/plugin_list.rs index 974bb8a2c5..ae03b3a1a9 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_list.rs @@ -452,6 +452,7 @@ async fn plugin_list_keeps_valid_marketplaces_when_another_marketplace_fails_to_ plugins: vec![PluginSummary { id: "valid-plugin@valid-marketplace".to_string(), remote_plugin_id: None, + version: None, local_version: None, name: "valid-plugin".to_string(), share_context: None, @@ -743,6 +744,7 @@ async fn plugin_list_uses_alternate_discoverable_manifest_and_keeps_undiscoverab PluginSummary { id: "valid-plugin@alternate-marketplace".to_string(), remote_plugin_id: None, + version: None, local_version: None, name: "valid-plugin".to_string(), share_context: None, @@ -780,6 +782,7 @@ async fn plugin_list_uses_alternate_discoverable_manifest_and_keeps_undiscoverab PluginSummary { id: "missing-plugin@alternate-marketplace".to_string(), remote_plugin_id: None, + version: None, local_version: None, name: "missing-plugin".to_string(), share_context: None, @@ -1683,6 +1686,7 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - "authentication_policy": "ON_USE", "status": "ENABLED", "release": { + "version": "1.2.3", "display_name": "Linear", "description": "Track work in Linear", "app_ids": [], @@ -1831,6 +1835,10 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() - ); assert_eq!(remote_marketplace.plugins[0].name, "linear"); assert_eq!(remote_marketplace.plugins[0].source, PluginSource::Remote); + assert_eq!( + remote_marketplace.plugins[0].version.as_deref(), + Some("1.2.3") + ); assert_eq!( remote_marketplace.plugins[0].local_version.as_deref(), Some("1.2.3") @@ -2030,6 +2038,7 @@ async fn plugin_list_includes_openai_curated_remote_collection_when_remote_plugi "authentication_policy": "ON_USE", "status": "ENABLED", "release": { + "version": "1.2.3", "display_name": "Linear", "description": "Track work in Linear", "app_ids": [], @@ -2090,6 +2099,7 @@ async fn plugin_list_includes_openai_curated_remote_collection_when_remote_plugi ); assert_eq!(plugin.name, "linear"); assert_eq!(plugin.source, PluginSource::Remote); + assert_eq!(plugin.version.as_deref(), Some("1.2.3")); assert_eq!(plugin.installed, false); assert_eq!(plugin.enabled, false); @@ -2492,16 +2502,25 @@ plugin_sharing = true marketplace .plugins .iter() - .map(|plugin| (plugin.id.clone(), plugin.installed, plugin.enabled)) + .map(|plugin| { + ( + plugin.id.clone(), + plugin.version.clone(), + plugin.installed, + plugin.enabled, + ) + }) .collect::>(), vec![ ( "shared-linear@workspace-shared-with-me".to_string(), + Some("1.2.3".to_string()), true, true ), ( "unlisted-linear@workspace-shared-with-me".to_string(), + Some("1.2.3".to_string()), true, false ) diff --git a/codex-rs/app-server/tests/suite/v2/plugin_share.rs b/codex-rs/app-server/tests/suite/v2/plugin_share.rs index 80fd56515c..a82b363806 100644 --- a/codex-rs/app-server/tests/suite/v2/plugin_share.rs +++ b/codex-rs/app-server/tests/suite/v2/plugin_share.rs @@ -171,6 +171,7 @@ async fn plugin_share_save_uploads_local_plugin() -> Result<()> { plugin: PluginSummary { id: "demo-plugin@workspace-shared-with-me".to_string(), remote_plugin_id: Some("plugins_123".to_string()), + version: Some("0.1.0".to_string()), local_version: Some("0.1.0".to_string()), name: "demo-plugin".to_string(), share_context: Some(expected_share_context("plugins_123")), @@ -574,6 +575,7 @@ async fn plugin_share_list_returns_created_workspace_plugins() -> Result<()> { plugin: PluginSummary { id: "demo-plugin@workspace-shared-with-me".to_string(), remote_plugin_id: Some("plugins_123".to_string()), + version: Some("0.1.0".to_string()), local_version: Some("0.1.0".to_string()), name: "demo-plugin".to_string(), share_context: Some(expected_share_context("plugins_123")), @@ -1174,6 +1176,7 @@ async fn plugin_share_delete_removes_created_workspace_plugin() -> Result<()> { plugin: PluginSummary { id: "demo-plugin@workspace-shared-with-me".to_string(), remote_plugin_id: Some("plugins_123".to_string()), + version: Some("0.1.0".to_string()), local_version: Some("0.1.0".to_string()), name: "demo-plugin".to_string(), share_context: Some(expected_share_context("plugins_123")), diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index da7bc0b5a5..469a9a7fc5 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -777,6 +777,7 @@ fn remote_installed_plugin_in_marketplace( RemoteInstalledPlugin { marketplace_name: marketplace_name.to_string(), id: format!("plugins~Plugin_{name}"), + version: None, name: name.to_string(), enabled: true, install_policy: codex_app_server_protocol::PluginInstallPolicy::Available, diff --git a/codex-rs/core-plugins/src/remote.rs b/codex-rs/core-plugins/src/remote.rs index 515bbb71c0..4c9bd2e672 100644 --- a/codex-rs/core-plugins/src/remote.rs +++ b/codex-rs/core-plugins/src/remote.rs @@ -148,6 +148,7 @@ pub enum RemoteMarketplaceSource { pub struct RemoteInstalledPlugin { pub marketplace_name: String, pub id: String, + pub version: Option, pub name: String, pub enabled: bool, pub install_policy: PluginInstallPolicy, @@ -161,6 +162,7 @@ pub struct RemoteInstalledPlugin { pub struct RemotePluginSummary { pub id: String, pub remote_plugin_id: String, + pub version: Option, pub local_version: Option, pub name: String, pub share_context: Option, @@ -1041,6 +1043,7 @@ pub fn group_remote_installed_plugins_by_marketplaces( let plugin_summary = RemotePluginSummary { id: plugin_id.as_key(), remote_plugin_id: plugin.id.clone(), + version: plugin.version.clone(), local_version: None, name: plugin.name.clone(), share_context: None, @@ -1472,6 +1475,7 @@ fn build_remote_plugin_summary( Ok(RemotePluginSummary { id: plugin_id.as_key(), remote_plugin_id: plugin.id.clone(), + version: plugin.release.version.clone(), local_version: installed_plugin .and_then(|installed| installed.plugin.release.version.clone()), name: plugin.name.clone(), @@ -1554,6 +1558,7 @@ fn remote_installed_plugin_to_cache_entry( Ok(RemoteInstalledPlugin { marketplace_name: remote_plugin_canonical_marketplace_name(plugin)?.to_string(), id: plugin.id.clone(), + version: plugin.release.version.clone(), name: plugin.name.clone(), enabled: installed_plugin.enabled, install_policy: plugin.installation_policy, diff --git a/codex-rs/core-plugins/src/remote/share/tests.rs b/codex-rs/core-plugins/src/remote/share/tests.rs index c8d06b234d..d7744681b9 100644 --- a/codex-rs/core-plugins/src/remote/share/tests.rs +++ b/codex-rs/core-plugins/src/remote/share/tests.rs @@ -618,6 +618,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() { summary: RemotePluginSummary { id: "demo-plugin@workspace-shared-with-me".to_string(), remote_plugin_id: "plugins_123".to_string(), + version: Some("0.1.0".to_string()), local_version: None, name: "demo-plugin".to_string(), share_context: Some(RemotePluginShareContext { @@ -658,6 +659,7 @@ async fn list_remote_plugin_shares_fetches_created_workspace_plugins() { summary: RemotePluginSummary { id: "demo-plugin@workspace-shared-with-me".to_string(), remote_plugin_id: "plugins_456".to_string(), + version: Some("0.1.0".to_string()), local_version: Some("0.1.0".to_string()), name: "demo-plugin".to_string(), share_context: Some(RemotePluginShareContext { diff --git a/codex-rs/tui/src/app/plugin_mentions.rs b/codex-rs/tui/src/app/plugin_mentions.rs index f12dee72cc..ae2d25a4dc 100644 --- a/codex-rs/tui/src/app/plugin_mentions.rs +++ b/codex-rs/tui/src/app/plugin_mentions.rs @@ -165,6 +165,7 @@ mod tests { PluginSummary { id: format!("{name}@server-marketplace"), remote_plugin_id: Some(format!("plugins~{name}")), + version: None, local_version: None, name: name.to_string(), share_context: None, diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 5e23e9f96a..1f9374bbc3 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -1331,6 +1331,7 @@ pub(super) fn plugins_test_summary( PluginSummary { id: id.to_string(), remote_plugin_id: None, + version: None, local_version: None, name: name.to_string(), share_context: None, @@ -1361,6 +1362,7 @@ pub(super) fn plugins_test_remote_summary( PluginSummary { id: remote_plugin_id.to_string(), remote_plugin_id: Some(remote_plugin_id.to_string()), + version: None, local_version: None, name: name.to_string(), share_context: None, From 98d28aab54ed86714901b6619400598598876dd0 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 3 Jul 2026 17:18:26 -0700 Subject: [PATCH 04/17] chore: remove unused git-cliff configuration (#31066) ## Why `cliff.toml` was originally used by the TypeScript CLI release tooling to generate the changelog. #2048 removed that tooling, including the `git-cliff` dependency and changelog package script, but left the configuration behind. #2780 subsequently replaced the generated `CHANGELOG.md` contents with a link to GitHub Releases, and the current Rust release workflow builds release notes from the tagged commit message. Nothing in the repository references `cliff.toml` or `git-cliff` anymore, so retaining the file misleadingly suggests that it is part of the supported release process. ## What changed - Delete the unused root-level `cliff.toml` configuration. ## Testing Not run (non-executable configuration cleanup only). --- cliff.toml | 46 ---------------------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 cliff.toml diff --git a/cliff.toml b/cliff.toml deleted file mode 100644 index f31e1bd89c..0000000000 --- a/cliff.toml +++ /dev/null @@ -1,46 +0,0 @@ -# https://git-cliff.org/docs/configuration - -[changelog] -header = """ -# Changelog - -You can install any of these versions: `npm install -g @openai/codex@` -""" - -body = """ -{% if version -%} -## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} -{%- else %} -## [unreleased] -{% endif %} - -{%- for group, commits in commits | group_by(attribute="group") %} -### {{ group | striptags | trim }} - -{% for commit in commits %}- {% if commit.scope %}*({{ commit.scope }})* {% endif %}{% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }} -{% endfor %} - -{%- endfor -%} -""" - -footer = """ - -""" - -trim = true -postprocessors = [] - -[git] -conventional_commits = true - -commit_parsers = [ - { message = "^feat", group = "🚀 Features" }, - { message = "^fix", group = "🪲 Bug Fixes" }, - { message = "^bump", group = "🛳️ Release" }, - # Fallback – skip anything that didn't match the above rules. - { message = ".*", group = "💼 Other" }, -] - -filter_unconventional = false -sort_commits = "oldest" -topo_order = false \ No newline at end of file From be33f80bc65159c094ecd06bf155afa3061ce23d Mon Sep 17 00:00:00 2001 From: Francis Chalissery Date: Sat, 4 Jul 2026 17:07:53 -0700 Subject: [PATCH 05/17] [codex] Read buffering metadata from response events (#31064) ## Summary - read optional faster-model metadata from streamed buffering payloads - use the buffering payload itself to determine whether buffering UI should be shown - retain the existing header value as a compatibility fallback when the payload omits the field ## Behavior An object-valued buffering signal now enables the buffering UI. The response event's faster-model field takes precedence when present, while omitted fields fall back to existing response metadata. An explicit null leaves the retry target unset. ## Validation - `just test -p codex-api` - `just fix -p codex-api` - `cargo fmt --all -- --check` - `git diff --check` --- codex-rs/codex-api/src/common.rs | 10 -- .../src/endpoint/responses_websocket.rs | 95 +++++++++++++++++-- codex-rs/codex-api/src/safety_buffering.rs | 47 +++++---- codex-rs/codex-api/src/sse/responses.rs | 66 +++++++++++-- codex-rs/core/tests/suite/safety_buffering.rs | 57 ++++++++++- 5 files changed, 231 insertions(+), 44 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index bd037deb58..f00cd742e6 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -121,21 +121,11 @@ pub struct SafetyBuffering { pub reasons: Vec, #[serde(skip)] pub show_buffering_ui: bool, - #[serde(skip)] pub faster_model: Option, } -impl SafetyBuffering { - pub(crate) fn with_treatment(mut self, treatment: &SafetyBufferingTreatment) -> Self { - self.show_buffering_ui = treatment.show_buffering_ui; - self.faster_model.clone_from(&treatment.faster_model); - self - } -} - #[derive(Debug, Clone, Default, PartialEq, Eq)] pub(crate) struct SafetyBufferingTreatment { - pub show_buffering_ui: bool, pub faster_model: Option, } diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index df41608184..c4c617ac99 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -689,17 +689,10 @@ async fn run_websocket_response_stream( { let _ = turn_state.set(response_turn_state); } - if let Some(headers) = event.headers.as_ref().and_then(Value::as_object) - && let Some(treatment) = - treatment_from_headers(&json_headers_to_http_headers(headers)) - { - safety_buffering_treatment = treatment; - } let model_verifications = event.model_verifications(); let turn_moderation_metadata = event.turn_moderation_metadata(); - let safety_buffering = event - .safety_buffering() - .map(|buffering| buffering.with_treatment(&safety_buffering_treatment)); + let safety_buffering = + safety_buffering_for_event(&event, &mut safety_buffering_treatment); if event.kind() == "codex.rate_limits" { if let Some(snapshot) = parse_rate_limit_event(&text) { let _ = tx_event.send(Ok(ResponseEvent::RateLimits(snapshot))).await; @@ -774,6 +767,19 @@ async fn run_websocket_response_stream( Ok(()) } +fn safety_buffering_for_event( + event: &ResponsesStreamEvent, + treatment: &mut SafetyBufferingTreatment, +) -> Option { + if let Some(headers) = event.headers.as_ref().and_then(Value::as_object) + && let Some(updated_treatment) = + treatment_from_headers(&json_headers_to_http_headers(headers)) + { + *treatment = updated_treatment; + } + event.safety_buffering(treatment) +} + async fn send_websocket_request( ws_stream: &WsStream, request_text: String, @@ -1039,4 +1045,75 @@ mod tests { Some(&HeaderValue::from_static("default-only")) ); } + + #[test] + fn websocket_safety_buffering_uses_event_before_header_fallback() { + let metadata: ResponsesStreamEvent = serde_json::from_value(json!({ + "type": "codex.response.metadata", + "headers": { + "x-codex-safety-buffering-enabled": "true", + "x-codex-safety-buffering-faster-model": "gpt-fast-header" + } + })) + .expect("deserialize treatment metadata"); + let event: ResponsesStreamEvent = serde_json::from_value(json!({ + "type": "response.output_text.delta", + "safety_buffering": { + "use_cases": ["cyber"], + "reasons": ["user_risk"], + "faster_model": "gpt-fast-wire" + } + })) + .expect("deserialize safety buffering event"); + let mut treatment = SafetyBufferingTreatment::default(); + + assert!(safety_buffering_for_event(&metadata, &mut treatment).is_none()); + let buffering = safety_buffering_for_event(&event, &mut treatment) + .expect("expected safety buffering payload"); + + assert_eq!( + buffering, + crate::common::SafetyBuffering { + use_cases: vec!["cyber".to_string()], + reasons: vec!["user_risk".to_string()], + show_buffering_ui: true, + faster_model: Some("gpt-fast-wire".to_string()), + } + ); + } + + #[test] + fn websocket_safety_buffering_event_controls_visibility_when_header_disables_it() { + let metadata: ResponsesStreamEvent = serde_json::from_value(json!({ + "type": "codex.response.metadata", + "headers": { + "x-codex-safety-buffering-enabled": "false", + "x-codex-safety-buffering-faster-model": "gpt-fast-header" + } + })) + .expect("deserialize treatment metadata"); + let event: ResponsesStreamEvent = serde_json::from_value(json!({ + "type": "response.output_text.delta", + "safety_buffering": { + "use_cases": ["cyber"], + "reasons": ["user_risk"] + } + })) + .expect("deserialize safety buffering event"); + let mut treatment = SafetyBufferingTreatment::default(); + + assert!(safety_buffering_for_event(&metadata, &mut treatment).is_none()); + let buffering = safety_buffering_for_event(&event, &mut treatment) + .expect("expected safety buffering payload"); + + assert_eq!( + buffering, + crate::common::SafetyBuffering { + use_cases: vec!["cyber".to_string()], + reasons: vec!["user_risk".to_string()], + show_buffering_ui: true, + faster_model: Some("gpt-fast-header".to_string()), + } + ); + } } diff --git a/codex-rs/codex-api/src/safety_buffering.rs b/codex-rs/codex-api/src/safety_buffering.rs index e5f3dcd79e..aaf09c8eb4 100644 --- a/codex-rs/codex-api/src/safety_buffering.rs +++ b/codex-rs/codex-api/src/safety_buffering.rs @@ -6,23 +6,17 @@ pub(crate) const X_CODEX_SAFETY_BUFFERING_FASTER_MODEL_HEADER: &str = "x-codex-safety-buffering-faster-model"; pub(crate) fn treatment_from_headers(headers: &HeaderMap) -> Option { - let show_buffering_ui = headers - .get(X_CODEX_SAFETY_BUFFERING_ENABLED_HEADER) - .and_then(|value| value.to_str().ok())? - .eq_ignore_ascii_case("true"); - let faster_model = if show_buffering_ui { - headers - .get(X_CODEX_SAFETY_BUFFERING_FASTER_MODEL_HEADER) - .and_then(|value| value.to_str().ok()) - .map(str::to_string) - } else { - None - }; + if !headers.contains_key(X_CODEX_SAFETY_BUFFERING_ENABLED_HEADER) + && !headers.contains_key(X_CODEX_SAFETY_BUFFERING_FASTER_MODEL_HEADER) + { + return None; + } + let faster_model = headers + .get(X_CODEX_SAFETY_BUFFERING_FASTER_MODEL_HEADER) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); - Some(SafetyBufferingTreatment { - show_buffering_ui, - faster_model, - }) + Some(SafetyBufferingTreatment { faster_model }) } #[cfg(test)] @@ -46,7 +40,26 @@ mod tests { assert_eq!( treatment_from_headers(&headers), Some(SafetyBufferingTreatment { - show_buffering_ui: true, + faster_model: Some("faster-model".to_string()), + }) + ); + } + + #[test] + fn buffering_enabled_header_does_not_gate_the_faster_model_fallback() { + let mut headers = HeaderMap::new(); + headers.insert( + X_CODEX_SAFETY_BUFFERING_ENABLED_HEADER, + HeaderValue::from_static("false"), + ); + headers.insert( + X_CODEX_SAFETY_BUFFERING_FASTER_MODEL_HEADER, + HeaderValue::from_static("faster-model"), + ); + + assert_eq!( + treatment_from_headers(&headers), + Some(SafetyBufferingTreatment { faster_model: Some("faster-model".to_string()), }) ); diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 71f73c0232..bd742dfa14 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -231,8 +231,18 @@ impl ResponsesStreamEvent { .map(|metadata| TurnModerationMetadataEvent { metadata }) } - pub(crate) fn safety_buffering(&self) -> Option { - serde_json::from_value(self.safety_buffering.as_ref()?.clone()).ok() + pub(crate) fn safety_buffering( + &self, + treatment: &SafetyBufferingTreatment, + ) -> Option { + let value = self.safety_buffering.as_ref()?; + let faster_model_present = value.as_object()?.contains_key("faster_model"); + let mut buffering: SafetyBuffering = serde_json::from_value(value.clone()).ok()?; + buffering.show_buffering_ui = true; + if !faster_model_present { + buffering.faster_model.clone_from(&treatment.faster_model); + } + Some(buffering) } } @@ -515,9 +525,7 @@ async fn process_sse_with_treatment( }; let model_verifications = event.model_verifications(); let turn_moderation_metadata = event.turn_moderation_metadata(); - let safety_buffering = event - .safety_buffering() - .map(|buffering| buffering.with_treatment(&safety_buffering_treatment)); + let safety_buffering = event.safety_buffering(&safety_buffering_treatment); if let Some(model) = event.response_model() && last_server_model.as_deref() != Some(model.as_str()) @@ -1354,7 +1362,8 @@ mod tests { "delta": "hello", "safety_buffering": { "use_cases": ["cyber"], - "reasons": ["user_risk"] + "reasons": ["user_risk"], + "faster_model": "gpt-fast-wire" } }), json!({ @@ -1381,7 +1390,10 @@ mod tests { assert_matches!( &events[1], ResponseEvent::SafetyBuffering(buffering) - if buffering.use_cases == ["cyber"] && buffering.reasons == ["user_risk"] + if buffering.use_cases == ["cyber"] + && buffering.reasons == ["user_risk"] + && buffering.show_buffering_ui + && buffering.faster_model.as_deref() == Some("gpt-fast-wire") ); assert_matches!(&events[2], ResponseEvent::OutputTextDelta(delta) if delta == "hello"); assert_matches!( @@ -1398,6 +1410,46 @@ mod tests { assert_matches!(&events[6], ResponseEvent::Completed { response_id, .. } if response_id == "resp-1"); } + #[test] + fn safety_buffering_prefers_wire_faster_model_and_only_falls_back_when_omitted() { + let treatment = SafetyBufferingTreatment { + faster_model: Some("gpt-fast-header".to_string()), + }; + + for (faster_model, expected_faster_model) in [ + (None, Some("gpt-fast-header")), + (Some(Value::Null), None), + (Some(json!("gpt-fast-wire")), Some("gpt-fast-wire")), + ] { + let mut event = json!({ + "type": "response.output_text.delta", + "safety_buffering": { + "use_cases": ["cyber"], + "reasons": ["user_risk"] + } + }); + if let Some(faster_model) = faster_model { + event["safety_buffering"]["faster_model"] = faster_model; + } + let event: ResponsesStreamEvent = + serde_json::from_value(event).expect("deserialize safety buffering event"); + + let buffering = event + .safety_buffering(&treatment) + .expect("expected safety buffering payload"); + + assert_eq!( + buffering, + SafetyBuffering { + use_cases: vec!["cyber".to_string()], + reasons: vec!["user_risk".to_string()], + show_buffering_ui: true, + faster_model: expected_faster_model.map(str::to_string), + } + ); + } + } + #[test] fn responses_stream_event_response_model_reads_top_level_headers() { let ev: ResponsesStreamEvent = serde_json::from_value(json!({ diff --git a/codex-rs/core/tests/suite/safety_buffering.rs b/codex-rs/core/tests/suite/safety_buffering.rs index 6e41b23766..5a8393f864 100644 --- a/codex-rs/core/tests/suite/safety_buffering.rs +++ b/codex-rs/core/tests/suite/safety_buffering.rs @@ -19,7 +19,7 @@ use serde_json::json; const FASTER_MODEL: &str = "faster-model"; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn emits_safety_buffering_with_the_requested_model() -> anyhow::Result<()> { +async fn emits_safety_buffering_with_the_header_fallback_model() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; @@ -72,3 +72,58 @@ async fn emits_safety_buffering_with_the_requested_model() -> anyhow::Result<()> Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn emits_safety_buffering_with_the_responses_api_model_without_header_gating() +-> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let mut created = ev_response_created("resp-1"); + created["safety_buffering"] = json!({ + "use_cases": ["cyber"], + "reasons": ["policy-check"], + "faster_model": FASTER_MODEL, + }); + mount_response_once( + &server, + sse_response(sse(vec![created, ev_completed("resp-1")])), + ) + .await; + + let test = test_codex().build(&server).await?; + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "Check this request".into(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + + let event = wait_for_event_match(&test.codex, |event| match event { + EventMsg::SafetyBuffering(event) => Some(event.clone()), + _ => None, + }) + .await; + assert_eq!( + event, + SafetyBufferingEvent { + model: test.session_configured.model.clone(), + use_cases: vec!["cyber".to_string()], + reasons: vec!["policy-check".to_string()], + show_buffering_ui: true, + faster_model: Some(FASTER_MODEL.to_string()), + } + ); + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + Ok(()) +} From 9c5be7e1d500faeca63b467a73bccf83d420e495 Mon Sep 17 00:00:00 2001 From: sayan-oai Date: Mon, 6 Jul 2026 07:05:40 -0700 Subject: [PATCH 06/17] Make plugin guidance react to environment readiness (#30223) ## Why Generic plugin guidance is currently emitted only with initial context from host plugin state. An executor-selected plugin can become available later in the same turn, making its skills and tools usable without ever telling the model how plugin capabilities should be used. ## What - project every ready selected plugin package, including skill-only plugins - carry plugin availability with the exact MCP runtime projection while preserving MCP manager reuse when servers and connectors are unchanged - move generic plugin guidance from the static initial-context path into persisted World State - recognize legacy and retained plugin fragments so resume and compaction do not duplicate guidance ## Testing - `just test -p codex-mcp-extension` - `just test -p codex-core plugins_instructions` - `just test -p codex-core plugin_availability_change_reuses_the_mcp_manager` - `just test -p codex-app-server --test all selected_capabilit` --- .../suite/v2/selected_capability_stack.rs | 17 +++ codex-rs/core/src/config/mod.rs | 9 ++ .../context/available_plugins_instructions.rs | 17 +-- codex-rs/core/src/context/world_state/mod.rs | 18 ++- .../world_state/plugins_instructions.rs | 55 +++++++++ .../world_state/plugins_instructions_tests.rs | 72 ++++++++++++ .../core/src/context_manager/history_tests.rs | 4 + codex-rs/core/src/event_mapping.rs | 2 + codex-rs/core/src/mcp.rs | 50 +++++--- codex-rs/core/src/plugins/render.rs | 2 +- codex-rs/core/src/session/mcp.rs | 26 +++-- codex-rs/core/src/session/mcp_runtime.rs | 10 +- codex-rs/core/src/session/mod.rs | 6 - codex-rs/core/src/session/session.rs | 19 +-- codex-rs/core/src/session/tests.rs | 85 ++++++++++++++ codex-rs/core/src/session/world_state.rs | 4 + codex-rs/core/src/state/service.rs | 12 +- codex-rs/core/src/thread_manager_tests.rs | 4 +- .../ext/extension-api/src/contributors/mcp.rs | 4 +- codex-rs/ext/mcp/src/executor_plugin.rs | 13 +-- codex-rs/ext/mcp/tests/executor_plugin_mcp.rs | 108 ++++++++++++++---- 21 files changed, 443 insertions(+), 94 deletions(-) create mode 100644 codex-rs/core/src/context/world_state/plugins_instructions.rs create mode 100644 codex-rs/core/src/context/world_state/plugins_instructions_tests.rs diff --git a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs index 6a70116aef..22153f1af7 100644 --- a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs +++ b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs @@ -28,6 +28,7 @@ use codex_exec_server::LOCAL_ENVIRONMENT_ID; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; +use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use core_test_support::process::wait_for_pid_file; @@ -235,7 +236,9 @@ async fn selected_capability_stack_tracks_environment_availability_and_resume() for request in &requests[1..4] { assert_selected_skill_is_injected(request, /*expected_count*/ 1); assert_selected_plugin_tools(request); + assert_plugin_guidance_count(request, /*expected_count*/ 1); } + assert_plugin_guidance_count(&requests[4], /*expected_count*/ 1); assert_selected_skill_is_injected(&requests[5], /*expected_count*/ 2); assert_selected_plugin_tools(&requests[5]); let output = requests[2].function_call_output(MCP_CALL_ID); @@ -398,7 +401,9 @@ async fn selected_capabilities_become_available_between_samples_in_one_turn() -> assert_eq!(3, requests.len()); assert_selected_skill_catalog_available(&requests[1]); assert_selected_plugin_tools(&requests[1]); + assert_plugin_guidance_count(&requests[1], /*expected_count*/ 1); assert_selected_plugin_tools(&requests[2]); + assert_plugin_guidance_count(&requests[2], /*expected_count*/ 1); let output = requests[2].function_call_output(MCP_CALL_ID); let output = output["output"] .as_str() @@ -537,6 +542,7 @@ fn assert_selected_capabilities_absent(request: &ResponsesRequest) { .all(|text| !text.contains(SKILL_DESCRIPTION)) ); assert_selected_plugin_tools_absent(request); + assert_plugin_guidance_count(request, /*expected_count*/ 0); } fn assert_selected_plugin_tools_absent(request: &ResponsesRequest) { @@ -555,6 +561,17 @@ fn assert_selected_plugin_tools_absent(request: &ResponsesRequest) { ); } +fn assert_plugin_guidance_count(request: &ResponsesRequest, expected_count: usize) { + assert_eq!( + expected_count, + request + .message_input_texts("developer") + .into_iter() + .filter(|text| text.starts_with(PLUGINS_INSTRUCTIONS_OPEN_TAG)) + .count() + ); +} + fn assert_selected_skill_is_injected(request: &ResponsesRequest, expected_count: usize) { assert_selected_skill_catalog_available(request); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index e29cb3875c..54fbb97f69 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -52,6 +52,7 @@ use codex_config::types::TuiNotificationSettings; use codex_config::types::TuiPetAnchor; use codex_config::types::UriBasedFileOpener; use codex_config::types::WindowsSandboxModeToml; +use codex_core_plugins::PluginLoadOutcome; use codex_core_plugins::PluginsConfigInput; use codex_exec_server::ExecutorFileSystem; use codex_exec_server::LOCAL_FS; @@ -1528,6 +1529,14 @@ impl Config { ) -> McpConfig { let plugins_input = self.plugins_config_input(); let loaded_plugins = plugins_manager.plugins_for_config(&plugins_input).await; + self.to_mcp_config_with_loaded_plugins(&loaded_plugins, additional_plugin_registrations) + } + + pub(crate) fn to_mcp_config_with_loaded_plugins( + &self, + loaded_plugins: &PluginLoadOutcome, + additional_plugin_registrations: impl IntoIterator, + ) -> McpConfig { let mut catalog = ResolvedMcpCatalog::builder(); for (plugin_order, plugin) in loaded_plugins .plugins() diff --git a/codex-rs/core/src/context/available_plugins_instructions.rs b/codex-rs/core/src/context/available_plugins_instructions.rs index 683d939aa0..a31d61d7fd 100644 --- a/codex-rs/core/src/context/available_plugins_instructions.rs +++ b/codex-rs/core/src/context/available_plugins_instructions.rs @@ -1,25 +1,10 @@ -use codex_plugin::PluginCapabilitySummary; use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_CLOSE_TAG; use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; use super::ContextualUserFragment; #[derive(Debug, Clone, PartialEq)] -pub(crate) struct AvailablePluginsInstructions { - plugins: Vec, -} - -impl AvailablePluginsInstructions { - pub(crate) fn from_plugins(plugins: &[PluginCapabilitySummary]) -> Option { - if plugins.is_empty() { - return None; - } - - Some(Self { - plugins: plugins.to_vec(), - }) - } -} +pub(crate) struct AvailablePluginsInstructions; impl ContextualUserFragment for AvailablePluginsInstructions { fn role(&self) -> &'static str { diff --git a/codex-rs/core/src/context/world_state/mod.rs b/codex-rs/core/src/context/world_state/mod.rs index ea82ddd11f..5dc22030ba 100644 --- a/codex-rs/core/src/context/world_state/mod.rs +++ b/codex-rs/core/src/context/world_state/mod.rs @@ -1,5 +1,6 @@ mod agents_md; mod environment; +mod plugins_instructions; use crate::context::ContextualUserFragment; use codex_extension_api::PreviousWorldStateSection; @@ -17,6 +18,7 @@ use std::fmt; pub(crate) use agents_md::AgentsMdState; pub(crate) use environment::EnvironmentsState; +pub(crate) use plugins_instructions::PluginsInstructionsState; trait ErasedWorldStateSection: Send + Sync { fn snapshot(&self) -> Option; @@ -62,11 +64,11 @@ impl ErasedWorldStateSection for S { } fn has_retained_fragment_matcher(&self) -> bool { - false + S::has_retained_fragment_matcher() } - fn matches_retained_fragment(&self, _role: &str, _text: &str) -> bool { - false + fn matches_retained_fragment(&self, role: &str, text: &str) -> bool { + S::matches_retained_fragment(role, text) } fn render_diff( @@ -183,6 +185,16 @@ pub(crate) trait WorldStateSection: Send + Sync + 'static { false } + /// Whether retained history must still contain this section's rendered fragment. + fn has_retained_fragment_matcher() -> bool { + false + } + + /// Recognizes this section's rendered fragment in retained model history. + fn matches_retained_fragment(_role: &str, _text: &str) -> bool { + false + } + fn render_diff( &self, previous: PreviousSectionState<'_, Self::Snapshot>, diff --git a/codex-rs/core/src/context/world_state/plugins_instructions.rs b/codex-rs/core/src/context/world_state/plugins_instructions.rs new file mode 100644 index 0000000000..303307317d --- /dev/null +++ b/codex-rs/core/src/context/world_state/plugins_instructions.rs @@ -0,0 +1,55 @@ +use super::PreviousSectionState; +use super::WorldStateSection; +use crate::context::AvailablePluginsInstructions; +use crate::context::ContextualUserFragment; + +/// Whether generic plugin usage guidance should be visible to the model. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct PluginsInstructionsState { + available: bool, +} + +impl PluginsInstructionsState { + pub(crate) fn new(available: bool) -> Self { + Self { available } + } +} + +impl WorldStateSection for PluginsInstructionsState { + const ID: &'static str = "plugins_instructions"; + type Snapshot = bool; + + fn snapshot(&self) -> Self::Snapshot { + self.available + } + + fn matches_legacy_fragment(role: &str, text: &str) -> bool { + role == "developer" && AvailablePluginsInstructions::matches_text(text) + } + + fn has_retained_fragment_matcher() -> bool { + true + } + + fn matches_retained_fragment(role: &str, text: &str) -> bool { + Self::matches_legacy_fragment(role, text) + } + + fn render_diff( + &self, + previous: PreviousSectionState<'_, Self::Snapshot>, + ) -> Option> { + if !self.available + || matches!(previous, PreviousSectionState::Known(previous) if *previous) + || matches!(previous, PreviousSectionState::Unknown) + { + return None; + } + + Some(Box::new(AvailablePluginsInstructions)) + } +} + +#[cfg(test)] +#[path = "plugins_instructions_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/context/world_state/plugins_instructions_tests.rs b/codex-rs/core/src/context/world_state/plugins_instructions_tests.rs new file mode 100644 index 0000000000..a688ff93ca --- /dev/null +++ b/codex-rs/core/src/context/world_state/plugins_instructions_tests.rs @@ -0,0 +1,72 @@ +use super::*; +use crate::context::ContextualUserFragment; +use codex_protocol::models::ResponseItem; +use pretty_assertions::assert_eq; + +fn render( + state: PluginsInstructionsState, + previous: PreviousSectionState<'_, bool>, +) -> Vec { + state + .render_diff(previous) + .into_iter() + .map(|fragment| fragment.render()) + .collect() +} + +#[test] +fn renders_only_when_plugins_become_available() { + let unavailable = PluginsInstructionsState::new(/*available*/ false); + let available = PluginsInstructionsState::new(/*available*/ true); + let false_snapshot = false; + let true_snapshot = true; + + assert_eq!( + render(unavailable, PreviousSectionState::Absent), + Vec::::new() + ); + assert_eq!(render(available, PreviousSectionState::Absent).len(), 1); + assert_eq!( + render(available, PreviousSectionState::Known(&false_snapshot)).len(), + 1 + ); + assert_eq!( + render(available, PreviousSectionState::Known(&true_snapshot)), + Vec::::new() + ); + assert_eq!( + render(unavailable, PreviousSectionState::Known(&true_snapshot)), + Vec::::new() + ); +} + +#[test] +fn legacy_guidance_is_not_injected_again() { + let mut world_state = super::super::WorldState::default(); + world_state.add_section(PluginsInstructionsState::new(/*available*/ true)); + let legacy: ResponseItem = ContextualUserFragment::into(AvailablePluginsInstructions); + + assert!( + world_state + .render_history_diff(/*previous*/ None, &[legacy]) + .is_empty() + ); +} + +#[test] +fn persisted_guidance_is_restored_only_when_missing_from_history() { + let mut world_state = super::super::WorldState::default(); + world_state.add_section(PluginsInstructionsState::new(/*available*/ true)); + let snapshot = world_state.snapshot(); + let retained: ResponseItem = ContextualUserFragment::into(AvailablePluginsInstructions); + + assert_eq!( + world_state.render_history_diff(Some(&snapshot), &[]).len(), + 1 + ); + assert!( + world_state + .render_history_diff(Some(&snapshot), &[retained]) + .is_empty() + ); +} diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index cbe0209e21..df5abd4708 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -22,6 +22,7 @@ use codex_protocol::openai_models::InputModality; use codex_protocol::openai_models::default_input_modalities; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::InterAgentCommunication; +use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::TurnContextItem; use codex_utils_absolute_path::AbsolutePathBuf; @@ -1021,6 +1022,9 @@ fn drop_last_n_user_turns_trims_context_updates_above_rolled_back_turn() { user_input_text_msg("turn 1 user"), assistant_msg("turn 1 assistant"), developer_msg("Generated images are saved to /tmp as /tmp/image-1.png by default."), + developer_msg(&format!( + "{PLUGINS_INSTRUCTIONS_OPEN_TAG}\nROLLED_BACK_PLUGIN_INSTRUCTIONS" + )), developer_msg("ROLLED_BACK_DEV_INSTRUCTIONS"), developer_msg("ROLLED_BACK_MULTI_AGENT_MODE"), user_input_text_msg( diff --git a/codex-rs/core/src/event_mapping.rs b/codex-rs/core/src/event_mapping.rs index 392203c079..5e24b78d05 100644 --- a/codex-rs/core/src/event_mapping.rs +++ b/codex-rs/core/src/event_mapping.rs @@ -18,6 +18,7 @@ use codex_protocol::protocol::COLLABORATION_MODE_OPEN_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_GUIDANCE_OPEN_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_OPEN_TAG; use codex_protocol::protocol::MULTI_AGENT_MODE_OPEN_TAG; +use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG; use codex_protocol::protocol::REALTIME_CONVERSATION_OPEN_TAG; use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG; use codex_protocol::user_input::UserInput; @@ -33,6 +34,7 @@ const CONTEXTUAL_DEVELOPER_PREFIXES: &[&str] = &[ "", COLLABORATION_MODE_OPEN_TAG, MULTI_AGENT_MODE_OPEN_TAG, + PLUGINS_INSTRUCTIONS_OPEN_TAG, REALTIME_CONVERSATION_OPEN_TAG, SKILLS_INSTRUCTIONS_OPEN_TAG, "", diff --git a/codex-rs/core/src/mcp.rs b/codex-rs/core/src/mcp.rs index 45ca0d563d..835c47ff51 100644 --- a/codex-rs/core/src/mcp.rs +++ b/codex-rs/core/src/mcp.rs @@ -25,6 +25,12 @@ use codex_plugin::AppConnectorId; const LEGACY_CODEX_APPS_REGISTRATION_ID: &str = "legacy_codex_apps"; +/// MCP configuration and capability availability derived from the same inputs. +pub(crate) struct McpRuntimeProjection { + pub(crate) config: McpConfig, + pub(crate) plugins_available: bool, +} + enum OrderedMcpOverlay { Set { contributor_id: &'static str, @@ -75,6 +81,7 @@ impl McpManager { pub async fn runtime_config(&self, config: &Config) -> McpConfig { self.runtime_config_with_context(McpServerContributionContext::global(config)) .await + .config } pub(crate) async fn runtime_config_for_step( @@ -83,7 +90,7 @@ impl McpManager { thread_init: &ExtensionDataInit, thread_store: &ExtensionData, available_environment_ids: &[String], - ) -> McpConfig { + ) -> McpRuntimeProjection { self.runtime_config_with_context(McpServerContributionContext::for_step( config, thread_init, @@ -96,8 +103,9 @@ impl McpManager { async fn runtime_config_with_context( &self, context: McpServerContributionContext<'_, Config>, - ) -> McpConfig { + ) -> McpRuntimeProjection { let config = context.config(); + let mut selected_plugin_available = false; let mut selected_plugin_connector_sources = Vec::new(); let mut selected_plugin_registrations = Vec::new(); let mut overlays = Vec::new(); @@ -129,17 +137,22 @@ impl McpManager { *config, ), ), - McpServerContribution::SelectedPluginConnectors { + McpServerContribution::SelectedPluginPackage { plugin_id, plugin_display_name, connector_ids, - } => selected_plugin_connector_sources.push( - PluginConnectorSource::from_connector_ids( - plugin_id, - plugin_display_name, - connector_ids.into_iter().map(AppConnectorId), - ), - ), + } => { + selected_plugin_available = true; + if !connector_ids.is_empty() { + selected_plugin_connector_sources.push( + PluginConnectorSource::from_connector_ids( + plugin_id, + plugin_display_name, + connector_ids.into_iter().map(AppConnectorId), + ), + ); + } + } McpServerContribution::Remove { name } => { overlays.push(OrderedMcpOverlay::Remove { contributor_id: contributor.id(), @@ -152,12 +165,14 @@ impl McpManager { } } - let mut mcp_config = config - .to_mcp_config_with_plugin_registrations( - self.plugins_manager.as_ref(), - selected_plugin_registrations, - ) + let loaded_plugins = self + .plugins_manager + .plugins_for_config(&config.plugins_config_input()) .await; + let plugins_available = + selected_plugin_available || !loaded_plugins.capability_summaries().is_empty(); + let mut mcp_config = config + .to_mcp_config_with_loaded_plugins(&loaded_plugins, selected_plugin_registrations); let mut catalog = mcp_config.mcp_server_catalog.to_builder(); if mcp_config.apps_enabled { catalog.register(McpServerRegistration::from_compatibility( @@ -211,7 +226,10 @@ impl McpManager { .merged_with(&ConnectorSnapshot::from_plugin_sources( selected_plugin_connector_sources, )); - mcp_config + McpRuntimeProjection { + config: mcp_config, + plugins_available, + } } /// Returns config- and plugin-backed servers without runtime contributions. diff --git a/codex-rs/core/src/plugins/render.rs b/codex-rs/core/src/plugins/render.rs index fc197dbbea..4e7575bd62 100644 --- a/codex-rs/core/src/plugins/render.rs +++ b/codex-rs/core/src/plugins/render.rs @@ -6,7 +6,7 @@ use crate::plugins::PluginCapabilitySummary; #[cfg(test)] pub(crate) fn render_plugins_section(plugins: &[PluginCapabilitySummary]) -> Option { - AvailablePluginsInstructions::from_plugins(plugins).map(|instructions| instructions.render()) + (!plugins.is_empty()).then(|| AvailablePluginsInstructions.render()) } pub(crate) fn render_explicit_plugin_instructions( diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index 25d95e30ea..4cfb0a36de 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -1,4 +1,5 @@ use super::*; +use crate::mcp::McpRuntimeProjection; use codex_exec_server::ResolvedSelectedCapabilityRoot; use codex_mcp::ElicitationReviewRequest; use codex_mcp::ElicitationReviewer; @@ -92,6 +93,7 @@ impl Session { &available_environment_ids, ) .await + .config } pub(crate) async fn runtime_mcp_servers( @@ -123,7 +125,7 @@ impl Session { if current.available_environment_ids() == available_environment_ids { return current; } - let mcp_config = self + let mcp_projection = self .services .mcp_manager .runtime_config_for_step( @@ -133,6 +135,7 @@ impl Session { &available_environment_ids, ) .await; + let mcp_config = &mcp_projection.config; let changed_environment_is_used_by_mcp = mcp_config .mcp_server_catalog .configured_servers() @@ -156,6 +159,7 @@ impl Session { // replacing the live manager and restarting its processes. let runtime = Arc::new(McpRuntimeSnapshot::new( Arc::new(current.config().clone()), + mcp_projection.plugins_available, current.manager_arc(), current.runtime_context().clone(), available_environment_ids, @@ -165,7 +169,7 @@ impl Session { } self.refresh_mcp_servers_inner( turn_context, - mcp_config, + mcp_projection, environments, &available_environment_ids, Some(self.mcp_elicitation_reviewer()), @@ -309,12 +313,16 @@ impl Session { async fn refresh_mcp_servers_inner( &self, turn_context: &TurnContext, - mcp_config: McpConfig, + mcp_projection: McpRuntimeProjection, environments: &TurnEnvironmentSnapshot, available_environment_ids: &[String], elicitation_reviewer: Option, ) -> Arc { let auth = self.services.auth_manager.auth().await; + let McpRuntimeProjection { + config: mcp_config, + plugins_available, + } = mcp_projection; let mcp_config = Arc::new(mcp_config); let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config); let mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref()); @@ -376,6 +384,7 @@ impl Session { .set_elicitations_auto_deny(current_runtime.manager().elicitations_auto_deny()); self.services.publish_mcp_runtime( mcp_config, + plugins_available, mcp_runtime_context, available_environment_ids.to_vec(), refreshed_manager, @@ -448,7 +457,7 @@ impl Session { .latest_mcp_runtime() .available_environment_ids() .to_vec(); - let mut mcp_config = self + let mut mcp_projection = self .services .mcp_manager .runtime_config_for_step( @@ -458,12 +467,13 @@ impl Session { &available_environment_ids, ) .await; - mcp_config.mcp_server_catalog = mcp_config + mcp_projection.config.mcp_server_catalog = mcp_projection + .config .mcp_server_catalog .with_materialized_servers(mcp_servers); self.refresh_mcp_servers_inner( turn_context, - mcp_config, + mcp_projection, &turn_context.environments, &available_environment_ids, elicitation_reviewer, @@ -515,7 +525,7 @@ impl Session { .latest_mcp_runtime() .available_environment_ids() .to_vec(); - let mcp_config = self + let mcp_projection = self .services .mcp_manager .runtime_config_for_step( @@ -527,7 +537,7 @@ impl Session { .await; self.refresh_mcp_servers_inner( turn_context, - mcp_config, + mcp_projection, &turn_context.environments, &available_environment_ids, elicitation_reviewer, diff --git a/codex-rs/core/src/session/mcp_runtime.rs b/codex-rs/core/src/session/mcp_runtime.rs index 34cf07cc35..5e7aeffcee 100644 --- a/codex-rs/core/src/session/mcp_runtime.rs +++ b/codex-rs/core/src/session/mcp_runtime.rs @@ -5,9 +5,10 @@ use codex_mcp::McpConfig; use codex_mcp::McpConnectionManager; use codex_mcp::McpRuntimeContext; -/// MCP config, exact environment bindings, and manager used by one model request. +/// MCP config, plugin availability, exact environment bindings, and manager for one request. pub struct McpRuntimeSnapshot { config: Arc, + plugins_available: bool, manager: Arc, runtime_context: McpRuntimeContext, available_environment_ids: Vec, @@ -16,12 +17,14 @@ pub struct McpRuntimeSnapshot { impl McpRuntimeSnapshot { pub(crate) fn new( config: Arc, + plugins_available: bool, manager: Arc, runtime_context: McpRuntimeContext, available_environment_ids: Vec, ) -> Self { Self { config, + plugins_available, manager, runtime_context, available_environment_ids, @@ -32,6 +35,10 @@ impl McpRuntimeSnapshot { self.config.as_ref() } + pub(crate) fn plugins_available(&self) -> bool { + self.plugins_available + } + pub fn manager(&self) -> &McpConnectionManager { self.manager.as_ref() } @@ -86,6 +93,7 @@ impl McpRuntimeSnapshot { ); Arc::new(Self::new( Arc::new(mcp_config), + /*plugins_available*/ false, Arc::new(manager), runtime_context, Vec::new(), diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 978768ba00..560dcf5985 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -24,7 +24,6 @@ use crate::config::resolve_tool_suggest_config_from_layer_stack; use crate::connectors; use crate::context::ApprovedCommandPrefixSaved; use crate::context::AppsInstructions; -use crate::context::AvailablePluginsInstructions; use crate::context::AvailableSkillsInstructions; use crate::context::CollaborationModeInstructions; use crate::context::ContextualUserFragment; @@ -3306,11 +3305,6 @@ impl Session { { contextual_user_sections.push(recommended_plugins.render()); } - if let Some(plugin_instructions) = - AvailablePluginsInstructions::from_plugins(loaded_plugins.capability_summaries()) - { - developer_sections.push(plugin_instructions.render()); - } let context_contributors = self.services.extensions.context_contributors().to_vec(); for contributor in &context_contributors { for fragment in contributor diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 5e7046b148..48a9ee447e 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -679,7 +679,7 @@ impl Session { let mcp_runtime_context_for_auth = mcp_runtime_context.clone(); let auth_and_mcp_fut = async move { let auth = auth_manager_clone.auth().await; - let mcp_config = mcp_manager_for_mcp + let mcp_projection = mcp_manager_for_mcp .runtime_config_for_step( &config_for_mcp, mcp_thread_init_for_startup, @@ -687,8 +687,9 @@ impl Session { /*available_environment_ids*/ &[], ) .await; - let mcp_servers = codex_mcp::effective_mcp_servers(&mcp_config, auth.as_ref()); - let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config); + let mcp_config = &mcp_projection.config; + let mcp_servers = codex_mcp::effective_mcp_servers(mcp_config, auth.as_ref()); + let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(mcp_config); let auth_statuses = compute_auth_statuses( mcp_servers.iter(), config_for_mcp.mcp_oauth_credentials_store_mode, @@ -699,7 +700,7 @@ impl Session { .await; ( auth, - mcp_config, + mcp_projection, mcp_servers, auth_statuses, tool_plugin_provenance, @@ -714,7 +715,7 @@ impl Session { let ( thread_persistence_result, state_db_ctx, - (auth, mcp_config, mcp_servers, auth_statuses, tool_plugin_provenance), + (auth, mcp_projection, mcp_servers, auth_statuses, tool_plugin_provenance), ) = tokio::join!(thread_persistence_fut, state_db_fut, auth_and_mcp_fut); let mut live_thread_init = @@ -1208,7 +1209,10 @@ impl Session { sess.services.mcp_manager.codex_apps_tools_cache(), codex_apps_tools_cache_key(auth), config.prefix_mcp_tool_names(), - mcp_config.client_elicitation_capability.clone(), + mcp_projection + .config + .client_elicitation_capability + .clone(), sess.services .supports_openai_form_elicitation .load(std::sync::atomic::Ordering::Relaxed), @@ -1224,7 +1228,8 @@ impl Session { .await; sess.services .install_mcp_connection_manager( - Arc::new(mcp_config), + Arc::new(mcp_projection.config), + mcp_projection.plugins_available, mcp_runtime_context, /*available_environment_ids*/ Vec::new(), mcp_connection_manager, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ece9d446b5..9ae29a0917 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -7729,6 +7729,91 @@ async fn refresh_mcp_servers_keeps_the_previous_runtime_alive() { ); } +#[tokio::test] +async fn plugin_availability_change_reuses_the_mcp_manager() { + struct ReadyPluginContributor; + + impl codex_extension_api::McpServerContributor for ReadyPluginContributor { + fn id(&self) -> &'static str { + "ready_plugin_test" + } + + fn contribute<'a>( + &'a self, + context: codex_extension_api::McpServerContributionContext<'a, Config>, + ) -> codex_extension_api::ExtensionFuture<'a, Vec> + { + Box::pin(async move { + let available = context + .available_environment_ids() + .is_some_and(|ids| ids.iter().any(|id| id == "executor")); + available + .then( + || codex_extension_api::McpServerContribution::SelectedPluginPackage { + plugin_id: "skill-only".to_string(), + plugin_display_name: "Skill Only".to_string(), + connector_ids: Vec::new(), + }, + ) + .into_iter() + .collect() + }) + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let mut registry = codex_extension_api::ExtensionRegistryBuilder::new(); + registry.mcp_server_contributor(Arc::new(ReadyPluginContributor)); + let registry = Arc::new(registry.build()); + session.services.extensions = Arc::clone(®istry); + session.services.mcp_manager = Arc::new(McpManager::new_with_extensions( + Arc::clone(&session.services.plugins_manager), + registry, + )); + let session = Arc::new(session); + session + .refresh_mcp_servers_now( + &turn_context, + &turn_context.config, + /*elicitation_reviewer*/ None, + ) + .await; + let old_runtime = session.services.latest_mcp_runtime(); + let old_manager = old_runtime.manager_arc(); + + let selected_root = codex_protocol::capabilities::SelectedCapabilityRoot { + id: "skill-only".to_string(), + location: codex_protocol::capabilities::CapabilityRootLocation::Environment { + environment_id: "executor".to_string(), + path: PathUri::from_host_native_path(turn_context.config.cwd.as_path()) + .expect("selected capability root URI"), + }, + }; + let environment = Arc::clone( + &turn_context + .environments + .primary() + .expect("ready test environment") + .environment, + ); + let captured_environments = HashMap::from([("executor".to_string(), Some(environment))]); + let resolved_roots = session + .services + .turn_environments + .environment_manager() + .resolve_selected_capability_roots(&[selected_root], &captured_environments) + .await; + + let new_runtime = session + .mcp_runtime_for_step(&turn_context, &turn_context.environments, &resolved_roots) + .await; + + assert!(!old_runtime.plugins_available()); + assert!(new_runtime.plugins_available()); + assert!(!Arc::ptr_eq(&old_runtime, &new_runtime)); + assert!(Arc::ptr_eq(&old_manager, &new_runtime.manager_arc())); +} + #[tokio::test] async fn built_tools_uses_the_step_mcp_runtime() -> anyhow::Result<()> { let (session, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs index 10d6a5d0d1..a78116d457 100644 --- a/codex-rs/core/src/session/world_state.rs +++ b/codex-rs/core/src/session/world_state.rs @@ -2,6 +2,7 @@ use super::session::Session; use super::step_context::StepContext; use crate::context::world_state::AgentsMdState; use crate::context::world_state::EnvironmentsState; +use crate::context::world_state::PluginsInstructionsState; use crate::context::world_state::WorldState; use codex_extension_api::WorldStateContributionInput; @@ -35,6 +36,9 @@ impl Session { .with_subagents(environment_subagents), ); } + world_state.add_section(PluginsInstructionsState::new( + step_context.mcp.plugins_available(), + )); let environments = step_context.environments.to_selections(); let ready_selected_capability_roots = step_context .selected_capability_roots diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index a611b94887..c4b67a629b 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -107,18 +107,25 @@ impl SessionServices { pub(crate) async fn install_mcp_connection_manager( &self, config: Arc, + plugins_available: bool, runtime_context: McpRuntimeContext, available_environment_ids: Vec, manager: McpConnectionManager, ) -> Result<()> { - let runtime = - self.publish_mcp_runtime(config, runtime_context, available_environment_ids, manager); + let runtime = self.publish_mcp_runtime( + config, + plugins_available, + runtime_context, + available_environment_ids, + manager, + ); runtime.manager().validate_required_servers().await } pub(crate) fn publish_mcp_runtime( &self, config: Arc, + plugins_available: bool, runtime_context: McpRuntimeContext, available_environment_ids: Vec, manager: McpConnectionManager, @@ -129,6 +136,7 @@ impl SessionServices { self.mcp_connection_manager.store(Arc::clone(&manager)); let runtime = Arc::new(McpRuntimeSnapshot::new( config, + plugins_available, manager, runtime_context, available_environment_ids, diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 4f0da0c9c7..3c1d0146e7 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -699,11 +699,11 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors() .collect::>() }; assert_eq!( - selected_servers(&first_resolved), + selected_servers(&first_resolved.config), std::collections::BTreeMap::from([("selected-a".to_string(), "env-a".to_string())]) ); assert_eq!( - selected_servers(&second_resolved), + selected_servers(&second_resolved.config), std::collections::BTreeMap::from([("selected-b".to_string(), "env-b".to_string())]) ); } diff --git a/codex-rs/ext/extension-api/src/contributors/mcp.rs b/codex-rs/ext/extension-api/src/contributors/mcp.rs index 499657f556..3fe648a1e9 100644 --- a/codex-rs/ext/extension-api/src/contributors/mcp.rs +++ b/codex-rs/ext/extension-api/src/contributors/mcp.rs @@ -93,8 +93,8 @@ pub enum McpServerContribution { selection_order: usize, config: Box, }, - /// Adds connector IDs declared by a plugin selected for this thread. - SelectedPluginConnectors { + /// Records a plugin selected for this thread and any connector IDs it declares. + SelectedPluginPackage { plugin_id: String, plugin_display_name: String, connector_ids: Vec, diff --git a/codex-rs/ext/mcp/src/executor_plugin.rs b/codex-rs/ext/mcp/src/executor_plugin.rs index 32637b4f47..98cfcd3615 100644 --- a/codex-rs/ext/mcp/src/executor_plugin.rs +++ b/codex-rs/ext/mcp/src/executor_plugin.rs @@ -186,13 +186,12 @@ impl McpServerContributor for SelectedExecutorPluginMcpContributor { config: Box::new(config), } })); - if !plugin.connector_ids.is_empty() { - contributions.push(McpServerContribution::SelectedPluginConnectors { - plugin_id: plugin.plugin_id, - plugin_display_name: plugin.plugin_display_name, - connector_ids: plugin.connector_ids, - }); - } + // Keep the package visible even when it contributes only skills. + contributions.push(McpServerContribution::SelectedPluginPackage { + plugin_id: plugin.plugin_id, + plugin_display_name: plugin.plugin_display_name, + connector_ids: plugin.connector_ids, + }); } contributions diff --git a/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs b/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs index 65a4248a32..da5c1fb6ad 100644 --- a/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs +++ b/codex-rs/ext/mcp/tests/executor_plugin_mcp.rs @@ -25,6 +25,13 @@ struct ContributionSummary { enabled: bool, } +#[derive(Debug, PartialEq, Eq)] +struct PackageSummary { + plugin_id: String, + plugin_display_name: String, + connector_ids: Vec, +} + #[tokio::test] async fn selected_plugin_servers_use_managed_requirements_for_the_selected_root_id() -> TestResult { let codex_home = tempfile::tempdir()?; @@ -92,10 +99,87 @@ command = "expected-command" Ok(()) } +#[tokio::test] +async fn selected_plugin_package_is_contributed_without_servers_or_connectors() -> TestResult { + let codex_home = tempfile::tempdir()?; + let plugin_root = tempfile::tempdir()?; + std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?; + std::fs::create_dir_all(plugin_root.path().join("skills/deploy"))?; + std::fs::write( + plugin_root.path().join(".codex-plugin/plugin.json"), + r#"{"name":"skill-only","interface":{"displayName":"Skill Only"}}"#, + )?; + std::fs::write( + plugin_root.path().join("skills/deploy/SKILL.md"), + "---\nname: deploy\ndescription: Deploy the project.\n---\n", + )?; + let config = ConfigBuilder::default() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .build() + .await?; + + let contributions = raw_selected_plugin_contributions(&config, plugin_root.path()).await?; + let package = contributions.into_iter().find_map(|contribution| { + let McpServerContribution::SelectedPluginPackage { + plugin_id, + plugin_display_name, + connector_ids, + } = contribution + else { + return None; + }; + Some(PackageSummary { + plugin_id, + plugin_display_name, + connector_ids, + }) + }); + + assert_eq!( + package, + Some(PackageSummary { + plugin_id: "selected-root".to_string(), + plugin_display_name: "Skill Only".to_string(), + connector_ids: Vec::new(), + }) + ); + Ok(()) +} + async fn selected_plugin_contributions( config: &Config, plugin_root: &std::path::Path, ) -> Result, Box> { + Ok(raw_selected_plugin_contributions(config, plugin_root) + .await? + .into_iter() + .filter_map(|contribution| match contribution { + McpServerContribution::SelectedPlugin { + name, + plugin_id, + plugin_display_name, + selection_order, + config, + } => Some(ContributionSummary { + name, + plugin_id, + plugin_display_name, + selection_order, + enabled: config.enabled, + }), + McpServerContribution::SelectedPluginPackage { .. } => None, + McpServerContribution::Set { .. } | McpServerContribution::Remove { .. } => { + panic!("expected selected plugin contribution") + } + }) + .collect()) +} + +async fn raw_selected_plugin_contributions( + config: &Config, + plugin_root: &std::path::Path, +) -> Result, Box> { let mut builder = ExtensionRegistryBuilder::new(); codex_mcp_extension::install_executor_plugins( &mut builder, @@ -120,27 +204,5 @@ async fn selected_plugin_contributions( &thread_store, &available_environment_ids, )) - .await - .into_iter() - .map(|contribution| match contribution { - McpServerContribution::SelectedPlugin { - name, - plugin_id, - plugin_display_name, - selection_order, - config, - } => ContributionSummary { - name, - plugin_id, - plugin_display_name, - selection_order, - enabled: config.enabled, - }, - McpServerContribution::Set { .. } - | McpServerContribution::SelectedPluginConnectors { .. } - | McpServerContribution::Remove { .. } => { - panic!("expected selected plugin contribution") - } - }) - .collect()) + .await) } From bce481fdcb1c9ea454c677ed123ab1b07a9644ff Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Mon, 6 Jul 2026 10:55:35 -0400 Subject: [PATCH 07/17] Fix cancelled review leaving MCP startup busy (#31189) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Cancelling an inline review could leave the TUI stuck in MCP startup state, so subsequent `/review` commands were rejected as though another task were still running. Specifically, the child’s “Starting MCP servers” event was incorrectly forwarded to the parent TUI, so the parent was marking itself as busy. This keeps delegate-session MCP startup events inside the delegate instead of exposing them as parent-session state. ## Reproduction Here's the before -- notice that after I cancel the first review, I'm prevented from running `/review` again: https://github.com/user-attachments/assets/571a0793-3253-4bcc-8f10-3782d176162f And the after -- notice that after I cancel, I can immediately start a new `/review`: https://github.com/user-attachments/assets/dd98b1d7-6a71-4a1f-a4b2-3295bc4848e5 --- codex-rs/core/src/codex_delegate.rs | 10 +-- codex-rs/core/src/codex_delegate_tests.rs | 65 ++++++++++------ codex-rs/core/tests/suite/review.rs | 90 +++++++++++++++++++++++ 3 files changed, 139 insertions(+), 26 deletions(-) diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index a671f0dd74..4cba4bddc5 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -299,11 +299,11 @@ async fn forward_events( match event { Event { id: _, - msg: EventMsg::TokenCount(_), - } => {} - Event { - id: _, - msg: EventMsg::SessionConfigured(_), + msg: + EventMsg::TokenCount(_) + | EventMsg::SessionConfigured(_) + | EventMsg::McpStartupUpdate(_) + | EventMsg::McpStartupComplete(_), } => {} Event { id, diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 9513dcc56c..5cb2251a4a 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -14,6 +14,9 @@ use codex_protocol::protocol::GuardianAssessmentAction; use codex_protocol::protocol::GuardianAssessmentStatus; use codex_protocol::protocol::GuardianCommandSource; use codex_protocol::protocol::McpInvocation; +use codex_protocol::protocol::McpStartupCompleteEvent; +use codex_protocol::protocol::McpStartupStatus; +use codex_protocol::protocol::McpStartupUpdateEvent; use codex_protocol::protocol::RawResponseItemEvent; use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::TurnAbortReason; @@ -34,8 +37,8 @@ use tokio::sync::watch; use tokio::time::timeout; #[tokio::test] -async fn forward_events_cancelled_while_send_blocked_shuts_down_delegate() { - let (tx_events, rx_events) = bounded(1); +async fn forward_events_filters_private_events_before_blocked_send_is_cancelled() { + let (tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY); let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); let (session, ctx, _rx_evt) = crate::session::tests::make_session_and_context_with_rx().await; @@ -71,33 +74,53 @@ async fn forward_events_cancelled_while_send_blocked_shuts_down_delegate() { cancel.clone(), )); - tx_events - .send(Event { - id: "evt".to_string(), - msg: EventMsg::RawResponseItem(RawResponseItemEvent { - item: ResponseItem::CustomToolCall { - id: None, - status: None, - call_id: "call-1".to_string(), - name: "tool".to_string(), - namespace: None, - input: "{}".to_string(), - internal_chat_message_metadata_passthrough: None, - }, - }), - }) - .await - .unwrap(); + for msg in [ + EventMsg::McpStartupUpdate(McpStartupUpdateEvent { + server: "pending".to_string(), + status: McpStartupStatus::Starting, + }), + EventMsg::McpStartupComplete(McpStartupCompleteEvent::default()), + ] { + tx_events + .send(Event { + id: "delegate-startup".to_string(), + msg, + }) + .await + .unwrap(); + } + let visible_msg = EventMsg::RawResponseItem(RawResponseItemEvent { + item: ResponseItem::CustomToolCall { + id: None, + status: None, + call_id: "call-1".to_string(), + name: "tool".to_string(), + namespace: None, + input: "{}".to_string(), + internal_chat_message_metadata_passthrough: None, + }, + }); + for id in ["visible-1", "visible-2", "blocked"] { + tx_events + .send(Event { + id: id.to_string(), + msg: visible_msg.clone(), + }) + .await + .unwrap(); + } drop(tx_events); + let received = rx_out.recv().await.expect("prefilled event missing"); + assert_eq!(received.id, "full"); + let received = rx_out.recv().await.expect("visible event missing"); + assert_eq!(received.id, "visible-1"); cancel.cancel(); timeout(std::time::Duration::from_millis(1000), forward) .await .expect("forward_events hung") .expect("forward_events join error"); - let received = rx_out.recv().await.expect("prefilled event missing"); - assert_eq!("full", received.id); let mut ops = Vec::new(); while let Ok(sub) = rx_sub.try_recv() { ops.push(sub.op); diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index af44baf6ca..e403b7e1ff 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -29,6 +29,7 @@ use core_test_support::wait_for_event; use pretty_assertions::assert_eq; use std::path::PathBuf; use std::sync::Arc; +use std::time::Duration; use tempfile::TempDir; use tokio::io::AsyncWriteExt as _; use uuid::Uuid; @@ -200,6 +201,95 @@ async fn review_op_emits_lifecycle_and_review_output() { server.verify().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cancelled_review_does_not_forward_delegate_mcp_startup() { + skip_if_no_network!(); + + let server = start_mock_server().await; + let request_log = responses::mount_response_once( + &server, + responses::sse_response(responses::sse(vec![responses::ev_response_created( + "resp-1", + )])) + .set_delay(Duration::from_secs(30)), + ) + .await; + let codex_home = Arc::new(TempDir::new().unwrap()); + let codex = new_conversation_for_server(&server, codex_home.clone(), |_| {}).await; + + // Consume the parent session's own empty startup round before starting the review. + wait_for_event(&codex, |event| { + matches!(event, EventMsg::McpStartupComplete(_)) + }) + .await; + + codex + .submit(Op::Review { + review_request: ReviewRequest { + target: ReviewTarget::Custom { + instructions: "Cancel this review".to_string(), + }, + user_facing_hint: None, + }, + }) + .await + .unwrap(); + + tokio::time::timeout(Duration::from_secs(5), async { + loop { + match codex.next_event().await.expect("review event").msg { + event @ (EventMsg::McpStartupUpdate(_) | EventMsg::McpStartupComplete(_)) => { + panic!("review forwarded delegate MCP startup: {event:?}") + } + EventMsg::EnteredReviewMode(_) => break, + _ => {} + } + } + }) + .await + .expect("timed out waiting for review entry"); + + tokio::time::timeout(Duration::from_secs(5), async { + while request_log.requests().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .expect("review request did not reach the server"); + + codex.submit(Op::Interrupt).await.unwrap(); + + let mut exited_review = false; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + match codex + .next_event() + .await + .expect("review cancellation event") + .msg + { + event @ (EventMsg::McpStartupUpdate(_) | EventMsg::McpStartupComplete(_)) => { + panic!("cancelled review forwarded delegate MCP startup: {event:?}") + } + EventMsg::ExitedReviewMode(ExitedReviewModeEvent { review_output }) => { + assert_eq!(review_output, None); + exited_review = true; + } + EventMsg::TurnAborted(_) if exited_review => break, + EventMsg::TurnAborted(_) => panic!("review turn aborted before review mode exited"), + _ => {} + } + } + }) + .await + .expect("timed out waiting for review cancellation"); + + assert_eq!(request_log.requests().len(), 1); + + let _codex_home_guard = codex_home; + server.verify().await; +} + /// When the model returns plain text that is not JSON, ensure the child /// lifecycle still occurs and the plain text is surfaced via /// ExitedReviewMode(Some(..)) as the overall_explanation. From 8917244f7dcc1a945f3d5eba3dea53f6dbb16349 Mon Sep 17 00:00:00 2001 From: Alexi Christakis <167903946+alexi-openai@users.noreply.github.com> Date: Mon, 6 Jul 2026 09:12:45 -0700 Subject: [PATCH 08/17] [core] Support interleaved response items (#30876) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - preserve reasoning item IDs on summary part and text delta events - track streamed response items by ID so reasoning summaries can continue after later items begin - keep TUI output complete and deduplicated when reasoning and final-answer events interleave ## Stack - **1/2: this PR — interleaved item support** - 2/2: #30752 — wire reasoning summary delivery configuration through the CLI and app-server ## Validation - just test -p codex-api preserves_reasoning_summary_item_ids - just test -p codex-core interleaved_reasoning_summary_events_keep_reasoning_item_metadata - just test -p codex-tui live_reasoning_summary_is_not_rendered_twice_when_item_completes - just fix -p codex-api -p codex-core -p codex-tui - just fmt --- codex-rs/codex-api/src/common.rs | 2 + codex-rs/codex-api/src/sse/responses.rs | 46 ++++++- codex-rs/core/src/session/turn.rs | 76 ++++++++---- codex-rs/core/tests/common/responses.rs | 13 +- codex-rs/core/tests/suite/apply_patch_cli.rs | 1 + codex-rs/core/tests/suite/codex_delegate.rs | 2 +- codex-rs/core/tests/suite/items.rs | 112 ++++++++++++++---- codex-rs/core/tests/suite/otel.rs | 2 +- .../src/chatwidget/tests/history_replay.rs | 73 +++++++----- 9 files changed, 246 insertions(+), 81 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index f00cd742e6..cbd93caf5d 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -101,6 +101,7 @@ pub enum ResponseEvent { delta: String, }, ReasoningSummaryDelta { + item_id: String, delta: String, summary_index: i64, }, @@ -109,6 +110,7 @@ pub enum ResponseEvent { content_index: i64, }, ReasoningSummaryPartAdded { + item_id: String, summary_index: i64, }, RateLimits(RateLimitSnapshot), diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index bd742dfa14..bc32fc41c5 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -351,8 +351,11 @@ pub fn process_responses_event( } } "response.reasoning_summary_text.delta" => { - if let (Some(delta), Some(summary_index)) = (event.delta, event.summary_index) { + if let (Some(item_id), Some(delta), Some(summary_index)) = + (event.item_id, event.delta, event.summary_index) + { return Ok(Some(ResponseEvent::ReasoningSummaryDelta { + item_id, delta, summary_index, })); @@ -444,8 +447,9 @@ pub fn process_responses_event( } } "response.reasoning_summary_part.added" => { - if let Some(summary_index) = event.summary_index { + if let (Some(item_id), Some(summary_index)) = (event.item_id, event.summary_index) { return Ok(Some(ResponseEvent::ReasoningSummaryPartAdded { + item_id, summary_index, })); } @@ -796,6 +800,44 @@ mod tests { } } + #[tokio::test] + async fn preserves_reasoning_summary_item_ids() { + let events = run_sse(vec![ + json!({ + "type": "response.reasoning_summary_part.added", + "item_id": "reasoning-1", + "summary_index": 0 + }), + json!({ + "type": "response.reasoning_summary_text.delta", + "item_id": "reasoning-1", + "summary_index": 0, + "delta": "Checking" + }), + json!({ + "type": "response.completed", + "response": { "id": "resp1" } + }), + ]) + .await; + + assert_matches!( + &events[0], + ResponseEvent::ReasoningSummaryPartAdded { + item_id, + summary_index: 0, + } if item_id == "reasoning-1" + ); + assert_matches!( + &events[1], + ResponseEvent::ReasoningSummaryDelta { + item_id, + delta, + summary_index: 0, + } if item_id == "reasoning-1" && delta == "Checking" + ); + } + #[tokio::test] async fn error_when_missing_completed() { let item1 = json!({ diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index f16b525002..1031c42919 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -1928,6 +1928,7 @@ async fn try_run_sampling_request( let mut needs_follow_up = false; let mut last_agent_message: Option = None; let mut active_item: Option = None; + let mut streamed_items = HashMap::::new(); let mut active_tool_argument_diff_consumer: Option<( String, Box, @@ -1986,18 +1987,44 @@ async fn try_run_sampling_request( match event { ResponseEvent::Created => {} ResponseEvent::OutputItemDone(item) => { - if let Some((_, mut consumer)) = active_tool_argument_diff_consumer.take() + let completes_active_tool_call = active_tool_argument_diff_consumer + .as_ref() + .is_some_and(|(active_call_id, _)| { + matches!( + &item, + ResponseItem::CustomToolCall { call_id, .. } + if call_id == active_call_id + ) + }); + if completes_active_tool_call + && let Some((_, mut consumer)) = active_tool_argument_diff_consumer.take() && let Ok(Some(event)) = consumer.finish() { sess.send_event(&turn_context, event).await; } - let previously_active_item = active_item.take(); - let previously_streamed_item = if active_item_is_streaming_to_client { - previously_active_item - } else { - None + let completed_item_id = item.id().map(str::to_owned); + let is_tool_call = matches!( + &item, + ResponseItem::LocalShellCall { .. } + | ResponseItem::FunctionCall { .. } + | ResponseItem::ToolSearchCall { .. } + | ResponseItem::CustomToolCall { .. } + ); + if completed_item_id.is_none() && !is_tool_call { + warn!("dropping non-tool output_item.done event without item ID"); + continue; + } + let completes_active_item = match (&completed_item_id, active_item.as_ref()) { + (Some(completed_item_id), Some(active)) => completed_item_id == &active.id(), + _ => false, }; - active_item_is_streaming_to_client = false; + let previously_streamed_item = completed_item_id + .as_deref() + .and_then(|item_id| streamed_items.remove(item_id)); + if completes_active_item { + active_item = None; + active_item_is_streaming_to_client = false; + } if let Some(previous) = previously_streamed_item.as_ref() && matches!(previous, TurnItem::AgentMessage(_)) { @@ -2152,6 +2179,7 @@ async fn try_run_sampling_request( ) .await; } + streamed_items.insert(turn_item.id(), turn_item.clone()); } active_item = Some(turn_item); active_item_is_streaming_to_client = stream_item_to_client; @@ -2288,39 +2316,47 @@ async fn try_run_sampling_request( } } ResponseEvent::ReasoningSummaryDelta { + item_id, delta, summary_index, } => { - if let Some(active) = active_item.as_ref() { - if !active_item_is_streaming_to_client { - continue; - } + if defer_streamed_turn_items_for_contributors { + continue; + } + if streamed_items.contains_key(&item_id) { let event = ReasoningContentDeltaEvent { thread_id: sess.thread_id.to_string(), turn_id: turn_context.sub_id.clone(), - item_id: active.id(), + item_id, delta, summary_index, }; sess.send_event(&turn_context, EventMsg::ReasoningContentDelta(event)) .await; } else { - error_or_panic("ReasoningSummaryDelta without active item".to_string()); + error_or_panic(format!( + "ReasoningSummaryDelta without streamed item {item_id}" + )); } } - ResponseEvent::ReasoningSummaryPartAdded { summary_index } => { - if let Some(active) = active_item.as_ref() { - if !active_item_is_streaming_to_client { - continue; - } + ResponseEvent::ReasoningSummaryPartAdded { + item_id, + summary_index, + } => { + if defer_streamed_turn_items_for_contributors { + continue; + } + if streamed_items.contains_key(&item_id) { let event = EventMsg::AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent { - item_id: active.id(), + item_id, summary_index, }); sess.send_event(&turn_context, event).await; } else { - error_or_panic("ReasoningSummaryPartAdded without active item".to_string()); + error_or_panic(format!( + "ReasoningSummaryPartAdded without streamed item {item_id}" + )); } } ResponseEvent::ReasoningContentDelta { diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 9569df1c90..45d4cb3d99 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -784,11 +784,20 @@ pub fn ev_reasoning_item_added(id: &str, summary: &[&str]) -> Value { }) } -pub fn ev_reasoning_summary_text_delta(delta: &str) -> Value { +pub fn ev_reasoning_summary_part_added(item_id: &str, summary_index: i64) -> Value { + serde_json::json!({ + "type": "response.reasoning_summary_part.added", + "item_id": item_id, + "summary_index": summary_index, + }) +} + +pub fn ev_reasoning_summary_text_delta(item_id: &str, summary_index: i64, delta: &str) -> Value { serde_json::json!({ "type": "response.reasoning_summary_text.delta", + "item_id": item_id, "delta": delta, - "summary_index": 0, + "summary_index": summary_index, }) } diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index d8142723b4..92f583c470 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -1198,6 +1198,7 @@ async fn apply_patch_custom_tool_streaming_emits_updated_changes() -> Result<()> "call_id": call_id, "delta": "*** Add File: streamed.txt\n+hello", }), + ev_assistant_message("unrelated-message", ""), json!({ "type": "response.custom_tool_call_input.delta", "call_id": call_id, diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs index f5db9856df..7dab8a0688 100644 --- a/codex-rs/core/tests/suite/codex_delegate.rs +++ b/codex-rs/core/tests/suite/codex_delegate.rs @@ -204,7 +204,7 @@ async fn codex_delegate_ignores_legacy_deltas() { let sse_stream = sse(vec![ ev_response_created("resp-1"), ev_reasoning_item_added("reason-1", &["initial"]), - ev_reasoning_summary_text_delta("think-1"), + ev_reasoning_summary_text_delta("reason-1", /*summary_index*/ 0, "think-1"), ev_completed("resp-1"), ]); diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 515d496b8b..b29696fdad 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -20,17 +20,20 @@ use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::PathBufExt; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_image_generation_call; use core_test_support::responses::ev_message_item_added; use core_test_support::responses::ev_output_text_delta; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::ev_reasoning_item_added; +use core_test_support::responses::ev_reasoning_summary_part_added; use core_test_support::responses::ev_reasoning_summary_text_delta; use core_test_support::responses::ev_reasoning_text_delta; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_web_search_call_added_partial; use core_test_support::responses::ev_web_search_call_done; use core_test_support::responses::mount_sse_once; +use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -1085,21 +1088,45 @@ async fn plan_mode_handles_missing_plan_close_tag() -> anyhow::Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { +async fn interleaved_reasoning_summary_events_keep_reasoning_item_metadata() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; let TestCodex { codex, .. } = test_codex().build(&server).await?; - let stream = sse(vec![ - ev_response_created("resp-1"), - ev_reasoning_item_added("reasoning-1", &[""]), - ev_reasoning_summary_text_delta("step one"), - ev_reasoning_item("reasoning-1", &["step one"], &[]), - ev_completed("resp-1"), - ]); - mount_sse_once(&server, stream).await; + mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_reasoning_item_added("reasoning-1", &[""]), + ev_reasoning_summary_part_added("reasoning-1", /*summary_index*/ 0), + ev_reasoning_summary_text_delta( + "reasoning-1", + /*summary_index*/ 0, + "step one", + ), + ev_reasoning_item("", &["ignored"], &[]), + ev_function_call("call-1", "unknown_tool", "{}"), + ev_reasoning_summary_part_added("reasoning-1", /*summary_index*/ 1), + ev_reasoning_summary_text_delta( + "reasoning-1", + /*summary_index*/ 1, + "step two", + ), + ev_reasoning_item("reasoning-1", &["step one", "step two"], &[]), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_message_item_added("message-1", ""), + ev_output_text_delta("Done"), + ev_assistant_message("message-1", "Done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; codex .submit(Op::UserInput { @@ -1114,22 +1141,59 @@ async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { }) .await?; - let reasoning_item = wait_for_event_match(&codex, |ev| match ev { - EventMsg::ItemStarted(ItemStartedEvent { - item: TurnItem::Reasoning(item), - .. - }) => Some(item.clone()), - _ => None, - }) - .await; + let mut reasoning_started = Vec::new(); + let mut reasoning_completed = Vec::new(); + let mut messages_started = Vec::new(); + let mut messages_completed = Vec::new(); + let mut summary_deltas = Vec::new(); + let mut summary_sections = Vec::new(); + loop { + match wait_for_event(&codex, |_| true).await { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::Reasoning(item), + .. + }) => reasoning_started.push(item.id), + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::Reasoning(item), + .. + }) => reasoning_completed.push(item.id), + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::AgentMessage(item), + .. + }) => messages_started.push(item.id), + EventMsg::ItemCompleted(ItemCompletedEvent { + item: TurnItem::AgentMessage(item), + .. + }) => messages_completed.push(item.id), + EventMsg::ReasoningContentDelta(event) => { + summary_deltas.push((event.item_id, event.delta, event.summary_index)); + } + EventMsg::AgentReasoningSectionBreak(event) => { + summary_sections.push((event.item_id, event.summary_index)); + } + EventMsg::TurnComplete(_) => break, + _ => {} + } + } - let delta_event = wait_for_event_match(&codex, |ev| match ev { - EventMsg::ReasoningContentDelta(event) => Some(event.clone()), - _ => None, - }) - .await; - assert_eq!(delta_event.item_id, reasoning_item.id); - assert_eq!(delta_event.delta, "step one"); + assert_eq!(reasoning_started, vec!["reasoning-1"]); + assert_eq!(reasoning_completed, vec!["reasoning-1"]); + assert_eq!(messages_started, vec!["message-1"]); + assert_eq!(messages_completed, vec!["message-1"]); + assert_eq!( + summary_deltas, + vec![ + ("reasoning-1".to_string(), "step one".to_string(), 0), + ("reasoning-1".to_string(), "step two".to_string(), 1), + ] + ); + assert_eq!( + summary_sections, + vec![ + ("reasoning-1".to_string(), 0), + ("reasoning-1".to_string(), 1) + ] + ); Ok(()) } diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index 4a2b2993ad..060a9079a9 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -821,7 +821,7 @@ async fn record_responses_sets_span_fields_for_response_events() { ev_message_item_added("msg-added", "hi there"), ev_reasoning_item_added("reasoning-1", &["summary"]), ev_output_text_delta("delta"), - ev_reasoning_summary_text_delta("summary-delta"), + ev_reasoning_summary_text_delta("reasoning-1", /*summary_index*/ 0, "summary-delta"), ev_reasoning_text_delta("raw-delta"), ev_function_call("call-1", "fn", "{\"key\":\"value\"}"), ev_assistant_message("msg-1", "agent"), diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index f8626dfcc0..300978cf4d 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -995,34 +995,30 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; chat.show_welcome_banner = false; - chat.handle_server_notification( - ServerNotification::TurnStarted(TurnStartedNotification { - thread_id: "thread-1".to_string(), - turn: AppServerTurn { - id: "turn-1".to_string(), - items_view: codex_app_server_protocol::TurnItemsView::Full, - items: Vec::new(), - status: AppServerTurnStatus::InProgress, - error: None, - started_at: Some(0), - completed_at: None, - duration_ms: None, - }, - }), - /*replay_kind*/ None, - ); - let _ = drain_insert_history(&mut rx); + handle_turn_started(&mut chat, "turn-1"); + while rx.try_recv().is_ok() {} + handle_agent_reasoning_delta(&mut chat, "**Step one**\nFirst summary"); + handle_agent_message_delta(&mut chat, "Final answer"); + complete_assistant_message( + &mut chat, + "msg-1", + "Final answer", + Some(MessagePhase::FinalAnswer), + ); chat.handle_server_notification( - ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification { - thread_id: "thread-1".to_string(), - turn_id: "turn-1".to_string(), - item_id: "reasoning-1".to_string(), - delta: "Summary only".to_string(), - summary_index: 0, - }), + ServerNotification::ReasoningSummaryPartAdded( + codex_app_server_protocol::ReasoningSummaryPartAddedNotification { + thread_id: chat.thread_id.map(|id| id.to_string()).unwrap_or_default(), + turn_id: "turn-1".to_string(), + item_id: "reasoning-1".to_string(), + summary_index: 1, + }, + ), /*replay_kind*/ None, ); + handle_agent_reasoning_delta(&mut chat, "**Step two**\nSecond summary"); + handle_agent_reasoning_final(&mut chat); chat.handle_server_notification( ServerNotification::ItemCompleted(ItemCompletedNotification { @@ -1031,20 +1027,35 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() { completed_at_ms: 0, item: AppServerThreadItem::Reasoning { id: "reasoning-1".to_string(), - summary: vec!["Summary only".to_string()], + summary: vec![ + "**Step one**\nFirst summary".to_string(), + "**Step two**\nSecond summary".to_string(), + ], content: Vec::new(), }, }), /*replay_kind*/ None, ); - let rendered = match rx.try_recv() { - Ok(AppEvent::InsertHistoryCell(cell)) => { - lines_to_single_string(&cell.transcript_lines(/*width*/ 80)) + let mut consolidated_answer = None; + let mut inserted_history = String::new(); + while let Ok(event) = rx.try_recv() { + match event { + AppEvent::ConsolidateAgentMessage { source, .. } => { + consolidated_answer = Some(source); + } + AppEvent::InsertHistoryCell(cell) => { + inserted_history.push_str(&lines_to_single_string( + &cell.transcript_lines(/*width*/ 80), + )); + } + _ => {} } - other => panic!("expected InsertHistoryCell, got {other:?}"), - }; - assert_eq!(rendered.matches("Summary only").count(), 1); + } + + assert_eq!(consolidated_answer.as_deref(), Some("Final answer")); + assert_eq!(inserted_history.matches("First summary").count(), 1); + assert_eq!(inserted_history.matches("Second summary").count(), 1); } #[tokio::test] From 7094fa467ea3ae596dae32519c3b90ab5390c9cc Mon Sep 17 00:00:00 2001 From: Francis Chalissery Date: Mon, 6 Jul 2026 10:04:26 -0700 Subject: [PATCH 09/17] [codex] Read retry model from buffering events (#31262) ## Summary - deserialize `retry_model` from streamed `safety_buffering` payloads - preserve the existing downstream faster-model API and legacy header fallback - update SSE, WebSocket, and end-to-end safety-buffering coverage ## Root cause Follow-up to #31064. The Responses API emits the retry target as `retry_model`, but the client was looking for `faster_model`, so the payload value was ignored in favor of the compatibility fallback. ## Behavior A non-null `retry_model` from the buffering payload takes precedence. An explicit null leaves the retry target unset, while an omitted field continues to fall back to the existing response header. ## Validation - `just test -p codex-api` (135 tests) - `just test -p codex-core safety_buffering` (2 tests) - `just fix -p codex-api` - `just fmt` - `git diff --check` --- codex-rs/codex-api/src/common.rs | 1 + .../codex-api/src/endpoint/responses_websocket.rs | 2 +- codex-rs/codex-api/src/sse/responses.rs | 14 +++++++------- codex-rs/core/tests/suite/safety_buffering.rs | 2 +- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index cbd93caf5d..7319d13a79 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -123,6 +123,7 @@ pub struct SafetyBuffering { pub reasons: Vec, #[serde(skip)] pub show_buffering_ui: bool, + #[serde(rename = "retry_model")] pub faster_model: Option, } diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index c4c617ac99..7f261bba36 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -1061,7 +1061,7 @@ mod tests { "safety_buffering": { "use_cases": ["cyber"], "reasons": ["user_risk"], - "faster_model": "gpt-fast-wire" + "retry_model": "gpt-fast-wire" } })) .expect("deserialize safety buffering event"); diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index bc32fc41c5..626f460dac 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -236,10 +236,10 @@ impl ResponsesStreamEvent { treatment: &SafetyBufferingTreatment, ) -> Option { let value = self.safety_buffering.as_ref()?; - let faster_model_present = value.as_object()?.contains_key("faster_model"); + let retry_model_present = value.as_object()?.contains_key("retry_model"); let mut buffering: SafetyBuffering = serde_json::from_value(value.clone()).ok()?; buffering.show_buffering_ui = true; - if !faster_model_present { + if !retry_model_present { buffering.faster_model.clone_from(&treatment.faster_model); } Some(buffering) @@ -1405,7 +1405,7 @@ mod tests { "safety_buffering": { "use_cases": ["cyber"], "reasons": ["user_risk"], - "faster_model": "gpt-fast-wire" + "retry_model": "gpt-fast-wire" } }), json!({ @@ -1453,12 +1453,12 @@ mod tests { } #[test] - fn safety_buffering_prefers_wire_faster_model_and_only_falls_back_when_omitted() { + fn safety_buffering_prefers_wire_retry_model_and_only_falls_back_when_omitted() { let treatment = SafetyBufferingTreatment { faster_model: Some("gpt-fast-header".to_string()), }; - for (faster_model, expected_faster_model) in [ + for (retry_model, expected_faster_model) in [ (None, Some("gpt-fast-header")), (Some(Value::Null), None), (Some(json!("gpt-fast-wire")), Some("gpt-fast-wire")), @@ -1470,8 +1470,8 @@ mod tests { "reasons": ["user_risk"] } }); - if let Some(faster_model) = faster_model { - event["safety_buffering"]["faster_model"] = faster_model; + if let Some(retry_model) = retry_model { + event["safety_buffering"]["retry_model"] = retry_model; } let event: ResponsesStreamEvent = serde_json::from_value(event).expect("deserialize safety buffering event"); diff --git a/codex-rs/core/tests/suite/safety_buffering.rs b/codex-rs/core/tests/suite/safety_buffering.rs index 5a8393f864..473cc18ced 100644 --- a/codex-rs/core/tests/suite/safety_buffering.rs +++ b/codex-rs/core/tests/suite/safety_buffering.rs @@ -83,7 +83,7 @@ async fn emits_safety_buffering_with_the_responses_api_model_without_header_gati created["safety_buffering"] = json!({ "use_cases": ["cyber"], "reasons": ["policy-check"], - "faster_model": FASTER_MODEL, + "retry_model": FASTER_MODEL, }); mount_response_once( &server, From 7b4e70d567ca2c15b2db8ac16c729e894843cdd3 Mon Sep 17 00:00:00 2001 From: Alexi Christakis <167903946+alexi-openai@users.noreply.github.com> Date: Mon, 6 Jul 2026 10:09:54 -0700 Subject: [PATCH 10/17] Revert "[core] Support interleaved response items" (#31261) Reverts openai/codex#30876 --- codex-rs/codex-api/src/common.rs | 2 - codex-rs/codex-api/src/sse/responses.rs | 46 +------ codex-rs/core/src/session/turn.rs | 76 ++++-------- codex-rs/core/tests/common/responses.rs | 13 +- codex-rs/core/tests/suite/apply_patch_cli.rs | 1 - codex-rs/core/tests/suite/codex_delegate.rs | 2 +- codex-rs/core/tests/suite/items.rs | 112 ++++-------------- codex-rs/core/tests/suite/otel.rs | 2 +- .../src/chatwidget/tests/history_replay.rs | 73 +++++------- 9 files changed, 81 insertions(+), 246 deletions(-) diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index 7319d13a79..254a5cb38f 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -101,7 +101,6 @@ pub enum ResponseEvent { delta: String, }, ReasoningSummaryDelta { - item_id: String, delta: String, summary_index: i64, }, @@ -110,7 +109,6 @@ pub enum ResponseEvent { content_index: i64, }, ReasoningSummaryPartAdded { - item_id: String, summary_index: i64, }, RateLimits(RateLimitSnapshot), diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index 626f460dac..17d31a02ee 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -351,11 +351,8 @@ pub fn process_responses_event( } } "response.reasoning_summary_text.delta" => { - if let (Some(item_id), Some(delta), Some(summary_index)) = - (event.item_id, event.delta, event.summary_index) - { + if let (Some(delta), Some(summary_index)) = (event.delta, event.summary_index) { return Ok(Some(ResponseEvent::ReasoningSummaryDelta { - item_id, delta, summary_index, })); @@ -447,9 +444,8 @@ pub fn process_responses_event( } } "response.reasoning_summary_part.added" => { - if let (Some(item_id), Some(summary_index)) = (event.item_id, event.summary_index) { + if let Some(summary_index) = event.summary_index { return Ok(Some(ResponseEvent::ReasoningSummaryPartAdded { - item_id, summary_index, })); } @@ -800,44 +796,6 @@ mod tests { } } - #[tokio::test] - async fn preserves_reasoning_summary_item_ids() { - let events = run_sse(vec![ - json!({ - "type": "response.reasoning_summary_part.added", - "item_id": "reasoning-1", - "summary_index": 0 - }), - json!({ - "type": "response.reasoning_summary_text.delta", - "item_id": "reasoning-1", - "summary_index": 0, - "delta": "Checking" - }), - json!({ - "type": "response.completed", - "response": { "id": "resp1" } - }), - ]) - .await; - - assert_matches!( - &events[0], - ResponseEvent::ReasoningSummaryPartAdded { - item_id, - summary_index: 0, - } if item_id == "reasoning-1" - ); - assert_matches!( - &events[1], - ResponseEvent::ReasoningSummaryDelta { - item_id, - delta, - summary_index: 0, - } if item_id == "reasoning-1" && delta == "Checking" - ); - } - #[tokio::test] async fn error_when_missing_completed() { let item1 = json!({ diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 1031c42919..f16b525002 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -1928,7 +1928,6 @@ async fn try_run_sampling_request( let mut needs_follow_up = false; let mut last_agent_message: Option = None; let mut active_item: Option = None; - let mut streamed_items = HashMap::::new(); let mut active_tool_argument_diff_consumer: Option<( String, Box, @@ -1987,44 +1986,18 @@ async fn try_run_sampling_request( match event { ResponseEvent::Created => {} ResponseEvent::OutputItemDone(item) => { - let completes_active_tool_call = active_tool_argument_diff_consumer - .as_ref() - .is_some_and(|(active_call_id, _)| { - matches!( - &item, - ResponseItem::CustomToolCall { call_id, .. } - if call_id == active_call_id - ) - }); - if completes_active_tool_call - && let Some((_, mut consumer)) = active_tool_argument_diff_consumer.take() + if let Some((_, mut consumer)) = active_tool_argument_diff_consumer.take() && let Ok(Some(event)) = consumer.finish() { sess.send_event(&turn_context, event).await; } - let completed_item_id = item.id().map(str::to_owned); - let is_tool_call = matches!( - &item, - ResponseItem::LocalShellCall { .. } - | ResponseItem::FunctionCall { .. } - | ResponseItem::ToolSearchCall { .. } - | ResponseItem::CustomToolCall { .. } - ); - if completed_item_id.is_none() && !is_tool_call { - warn!("dropping non-tool output_item.done event without item ID"); - continue; - } - let completes_active_item = match (&completed_item_id, active_item.as_ref()) { - (Some(completed_item_id), Some(active)) => completed_item_id == &active.id(), - _ => false, + let previously_active_item = active_item.take(); + let previously_streamed_item = if active_item_is_streaming_to_client { + previously_active_item + } else { + None }; - let previously_streamed_item = completed_item_id - .as_deref() - .and_then(|item_id| streamed_items.remove(item_id)); - if completes_active_item { - active_item = None; - active_item_is_streaming_to_client = false; - } + active_item_is_streaming_to_client = false; if let Some(previous) = previously_streamed_item.as_ref() && matches!(previous, TurnItem::AgentMessage(_)) { @@ -2179,7 +2152,6 @@ async fn try_run_sampling_request( ) .await; } - streamed_items.insert(turn_item.id(), turn_item.clone()); } active_item = Some(turn_item); active_item_is_streaming_to_client = stream_item_to_client; @@ -2316,47 +2288,39 @@ async fn try_run_sampling_request( } } ResponseEvent::ReasoningSummaryDelta { - item_id, delta, summary_index, } => { - if defer_streamed_turn_items_for_contributors { - continue; - } - if streamed_items.contains_key(&item_id) { + if let Some(active) = active_item.as_ref() { + if !active_item_is_streaming_to_client { + continue; + } let event = ReasoningContentDeltaEvent { thread_id: sess.thread_id.to_string(), turn_id: turn_context.sub_id.clone(), - item_id, + item_id: active.id(), delta, summary_index, }; sess.send_event(&turn_context, EventMsg::ReasoningContentDelta(event)) .await; } else { - error_or_panic(format!( - "ReasoningSummaryDelta without streamed item {item_id}" - )); + error_or_panic("ReasoningSummaryDelta without active item".to_string()); } } - ResponseEvent::ReasoningSummaryPartAdded { - item_id, - summary_index, - } => { - if defer_streamed_turn_items_for_contributors { - continue; - } - if streamed_items.contains_key(&item_id) { + ResponseEvent::ReasoningSummaryPartAdded { summary_index } => { + if let Some(active) = active_item.as_ref() { + if !active_item_is_streaming_to_client { + continue; + } let event = EventMsg::AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent { - item_id, + item_id: active.id(), summary_index, }); sess.send_event(&turn_context, event).await; } else { - error_or_panic(format!( - "ReasoningSummaryPartAdded without streamed item {item_id}" - )); + error_or_panic("ReasoningSummaryPartAdded without active item".to_string()); } } ResponseEvent::ReasoningContentDelta { diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 45d4cb3d99..9569df1c90 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -784,20 +784,11 @@ pub fn ev_reasoning_item_added(id: &str, summary: &[&str]) -> Value { }) } -pub fn ev_reasoning_summary_part_added(item_id: &str, summary_index: i64) -> Value { - serde_json::json!({ - "type": "response.reasoning_summary_part.added", - "item_id": item_id, - "summary_index": summary_index, - }) -} - -pub fn ev_reasoning_summary_text_delta(item_id: &str, summary_index: i64, delta: &str) -> Value { +pub fn ev_reasoning_summary_text_delta(delta: &str) -> Value { serde_json::json!({ "type": "response.reasoning_summary_text.delta", - "item_id": item_id, "delta": delta, - "summary_index": summary_index, + "summary_index": 0, }) } diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 92f583c470..d8142723b4 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -1198,7 +1198,6 @@ async fn apply_patch_custom_tool_streaming_emits_updated_changes() -> Result<()> "call_id": call_id, "delta": "*** Add File: streamed.txt\n+hello", }), - ev_assistant_message("unrelated-message", ""), json!({ "type": "response.custom_tool_call_input.delta", "call_id": call_id, diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs index 7dab8a0688..f5db9856df 100644 --- a/codex-rs/core/tests/suite/codex_delegate.rs +++ b/codex-rs/core/tests/suite/codex_delegate.rs @@ -204,7 +204,7 @@ async fn codex_delegate_ignores_legacy_deltas() { let sse_stream = sse(vec![ ev_response_created("resp-1"), ev_reasoning_item_added("reason-1", &["initial"]), - ev_reasoning_summary_text_delta("reason-1", /*summary_index*/ 0, "think-1"), + ev_reasoning_summary_text_delta("think-1"), ev_completed("resp-1"), ]); diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index b29696fdad..515d496b8b 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -20,20 +20,17 @@ use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::PathBufExt; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_image_generation_call; use core_test_support::responses::ev_message_item_added; use core_test_support::responses::ev_output_text_delta; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::ev_reasoning_item_added; -use core_test_support::responses::ev_reasoning_summary_part_added; use core_test_support::responses::ev_reasoning_summary_text_delta; use core_test_support::responses::ev_reasoning_text_delta; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_web_search_call_added_partial; use core_test_support::responses::ev_web_search_call_done; use core_test_support::responses::mount_sse_once; -use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -1088,45 +1085,21 @@ async fn plan_mode_handles_missing_plan_close_tag() -> anyhow::Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn interleaved_reasoning_summary_events_keep_reasoning_item_metadata() -> anyhow::Result<()> { +async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; let TestCodex { codex, .. } = test_codex().build(&server).await?; - mount_sse_sequence( - &server, - vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_reasoning_item_added("reasoning-1", &[""]), - ev_reasoning_summary_part_added("reasoning-1", /*summary_index*/ 0), - ev_reasoning_summary_text_delta( - "reasoning-1", - /*summary_index*/ 0, - "step one", - ), - ev_reasoning_item("", &["ignored"], &[]), - ev_function_call("call-1", "unknown_tool", "{}"), - ev_reasoning_summary_part_added("reasoning-1", /*summary_index*/ 1), - ev_reasoning_summary_text_delta( - "reasoning-1", - /*summary_index*/ 1, - "step two", - ), - ev_reasoning_item("reasoning-1", &["step one", "step two"], &[]), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_message_item_added("message-1", ""), - ev_output_text_delta("Done"), - ev_assistant_message("message-1", "Done"), - ev_completed("resp-2"), - ]), - ], - ) - .await; + let stream = sse(vec![ + ev_response_created("resp-1"), + ev_reasoning_item_added("reasoning-1", &[""]), + ev_reasoning_summary_text_delta("step one"), + ev_reasoning_item("reasoning-1", &["step one"], &[]), + ev_completed("resp-1"), + ]); + mount_sse_once(&server, stream).await; codex .submit(Op::UserInput { @@ -1141,59 +1114,22 @@ async fn interleaved_reasoning_summary_events_keep_reasoning_item_metadata() -> }) .await?; - let mut reasoning_started = Vec::new(); - let mut reasoning_completed = Vec::new(); - let mut messages_started = Vec::new(); - let mut messages_completed = Vec::new(); - let mut summary_deltas = Vec::new(); - let mut summary_sections = Vec::new(); - loop { - match wait_for_event(&codex, |_| true).await { - EventMsg::ItemStarted(ItemStartedEvent { - item: TurnItem::Reasoning(item), - .. - }) => reasoning_started.push(item.id), - EventMsg::ItemCompleted(ItemCompletedEvent { - item: TurnItem::Reasoning(item), - .. - }) => reasoning_completed.push(item.id), - EventMsg::ItemStarted(ItemStartedEvent { - item: TurnItem::AgentMessage(item), - .. - }) => messages_started.push(item.id), - EventMsg::ItemCompleted(ItemCompletedEvent { - item: TurnItem::AgentMessage(item), - .. - }) => messages_completed.push(item.id), - EventMsg::ReasoningContentDelta(event) => { - summary_deltas.push((event.item_id, event.delta, event.summary_index)); - } - EventMsg::AgentReasoningSectionBreak(event) => { - summary_sections.push((event.item_id, event.summary_index)); - } - EventMsg::TurnComplete(_) => break, - _ => {} - } - } + let reasoning_item = wait_for_event_match(&codex, |ev| match ev { + EventMsg::ItemStarted(ItemStartedEvent { + item: TurnItem::Reasoning(item), + .. + }) => Some(item.clone()), + _ => None, + }) + .await; - assert_eq!(reasoning_started, vec!["reasoning-1"]); - assert_eq!(reasoning_completed, vec!["reasoning-1"]); - assert_eq!(messages_started, vec!["message-1"]); - assert_eq!(messages_completed, vec!["message-1"]); - assert_eq!( - summary_deltas, - vec![ - ("reasoning-1".to_string(), "step one".to_string(), 0), - ("reasoning-1".to_string(), "step two".to_string(), 1), - ] - ); - assert_eq!( - summary_sections, - vec![ - ("reasoning-1".to_string(), 0), - ("reasoning-1".to_string(), 1) - ] - ); + let delta_event = wait_for_event_match(&codex, |ev| match ev { + EventMsg::ReasoningContentDelta(event) => Some(event.clone()), + _ => None, + }) + .await; + assert_eq!(delta_event.item_id, reasoning_item.id); + assert_eq!(delta_event.delta, "step one"); Ok(()) } diff --git a/codex-rs/core/tests/suite/otel.rs b/codex-rs/core/tests/suite/otel.rs index 060a9079a9..4a2b2993ad 100644 --- a/codex-rs/core/tests/suite/otel.rs +++ b/codex-rs/core/tests/suite/otel.rs @@ -821,7 +821,7 @@ async fn record_responses_sets_span_fields_for_response_events() { ev_message_item_added("msg-added", "hi there"), ev_reasoning_item_added("reasoning-1", &["summary"]), ev_output_text_delta("delta"), - ev_reasoning_summary_text_delta("reasoning-1", /*summary_index*/ 0, "summary-delta"), + ev_reasoning_summary_text_delta("summary-delta"), ev_reasoning_text_delta("raw-delta"), ev_function_call("call-1", "fn", "{\"key\":\"value\"}"), ev_assistant_message("msg-1", "agent"), diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index 300978cf4d..f8626dfcc0 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -995,30 +995,34 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; chat.show_welcome_banner = false; - handle_turn_started(&mut chat, "turn-1"); - while rx.try_recv().is_ok() {} - - handle_agent_reasoning_delta(&mut chat, "**Step one**\nFirst summary"); - handle_agent_message_delta(&mut chat, "Final answer"); - complete_assistant_message( - &mut chat, - "msg-1", - "Final answer", - Some(MessagePhase::FinalAnswer), - ); chat.handle_server_notification( - ServerNotification::ReasoningSummaryPartAdded( - codex_app_server_protocol::ReasoningSummaryPartAddedNotification { - thread_id: chat.thread_id.map(|id| id.to_string()).unwrap_or_default(), - turn_id: "turn-1".to_string(), - item_id: "reasoning-1".to_string(), - summary_index: 1, + ServerNotification::TurnStarted(TurnStartedNotification { + thread_id: "thread-1".to_string(), + turn: AppServerTurn { + id: "turn-1".to_string(), + items_view: codex_app_server_protocol::TurnItemsView::Full, + items: Vec::new(), + status: AppServerTurnStatus::InProgress, + error: None, + started_at: Some(0), + completed_at: None, + duration_ms: None, }, - ), + }), + /*replay_kind*/ None, + ); + let _ = drain_insert_history(&mut rx); + + chat.handle_server_notification( + ServerNotification::ReasoningSummaryTextDelta(ReasoningSummaryTextDeltaNotification { + thread_id: "thread-1".to_string(), + turn_id: "turn-1".to_string(), + item_id: "reasoning-1".to_string(), + delta: "Summary only".to_string(), + summary_index: 0, + }), /*replay_kind*/ None, ); - handle_agent_reasoning_delta(&mut chat, "**Step two**\nSecond summary"); - handle_agent_reasoning_final(&mut chat); chat.handle_server_notification( ServerNotification::ItemCompleted(ItemCompletedNotification { @@ -1027,35 +1031,20 @@ async fn live_reasoning_summary_is_not_rendered_twice_when_item_completes() { completed_at_ms: 0, item: AppServerThreadItem::Reasoning { id: "reasoning-1".to_string(), - summary: vec![ - "**Step one**\nFirst summary".to_string(), - "**Step two**\nSecond summary".to_string(), - ], + summary: vec!["Summary only".to_string()], content: Vec::new(), }, }), /*replay_kind*/ None, ); - let mut consolidated_answer = None; - let mut inserted_history = String::new(); - while let Ok(event) = rx.try_recv() { - match event { - AppEvent::ConsolidateAgentMessage { source, .. } => { - consolidated_answer = Some(source); - } - AppEvent::InsertHistoryCell(cell) => { - inserted_history.push_str(&lines_to_single_string( - &cell.transcript_lines(/*width*/ 80), - )); - } - _ => {} + let rendered = match rx.try_recv() { + Ok(AppEvent::InsertHistoryCell(cell)) => { + lines_to_single_string(&cell.transcript_lines(/*width*/ 80)) } - } - - assert_eq!(consolidated_answer.as_deref(), Some("Final answer")); - assert_eq!(inserted_history.matches("First summary").count(), 1); - assert_eq!(inserted_history.matches("Second summary").count(), 1); + other => panic!("expected InsertHistoryCell, got {other:?}"), + }; + assert_eq!(rendered.matches("Summary only").count(), 1); } #[tokio::test] From dbf67f34a0a37be77d12e2801575f33946f7d629 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 6 Jul 2026 10:17:15 -0700 Subject: [PATCH 11/17] Emit exec-policy warnings for freshly loaded thread config (#31253) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why App-server initialization captures exec-policy parse warnings only once. Each `thread/start` then reloads config for that thread's cwd and rereads its `.rules` files, so rules that become malformed after initialization—or belong to a different project—are dropped without a fresh warning to the requesting client. ## What changed - Validate exec-policy rules against the freshly loaded per-thread config during `thread/start`. - Send the existing structured `configWarning` only to the connection that requested the thread. - Preserve nonfatal startup and avoid repeating an identical warning already delivered during initialization. This is intentionally separate from the TUI `legacy_core` cleanup in #31179 and the managed-requirements fallback fix in #31188. --- codex-rs/app-server/README.md | 2 +- codex-rs/app-server/src/lib.rs | 19 +-- codex-rs/app-server/src/message_processor.rs | 3 +- .../request_processors/thread_processor.rs | 21 +++ .../suite/v2/connection_handling_websocket.rs | 103 ++++++++++++++ .../app-server/tests/suite/v2/thread_start.rs | 133 ++++++++++++++++++ 6 files changed, 271 insertions(+), 10 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 43e7dbd3eb..1dfa6b4164 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1301,7 +1301,7 @@ Event notifications are the server-initiated event stream for thread lifecycles, Thread realtime uses a separate thread-scoped notification surface. `thread/realtime/*` notifications are ephemeral transport events, not `ThreadItem`s, and are not returned by `thread/read`, `thread/resume`, or `thread/fork`. -Recoverable configuration and initialization warnings use the existing `configWarning` notification: `{ summary, details?, path?, range? }`. App-server may emit it during initialization for config parsing and related setup diagnostics. +Recoverable configuration and initialization warnings use the existing `configWarning` notification: `{ summary, details?, path?, range? }`. App-server may emit it during initialization for config parsing and related setup diagnostics, or to the requesting connection during `thread/start` when that thread's exec-policy rules fail to parse. Generic runtime warnings use the `warning` notification: `{ threadId?, message }`. App-server emits this for non-fatal warnings from the core event stream, including cases where not all enabled skills are included in the model-visible skills list for a session. diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 0edb57d8a2..fa6b6cd811 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -320,6 +320,16 @@ fn exec_policy_warning_location(err: &ExecPolicyError) -> (Option, Optio } } +fn exec_policy_config_warning(err: &ExecPolicyError) -> ConfigWarningNotification { + let (path, range) = exec_policy_warning_location(err); + ConfigWarningNotification { + summary: "Error parsing rules; custom rules not applied.".to_string(), + details: Some(err.to_string()), + path, + range, + } +} + fn app_text_range(range: &CoreTextRange) -> AppTextRange { AppTextRange { start: AppTextPosition { @@ -612,14 +622,7 @@ pub async fn run_main_with_transport_options( } if let Ok(Some(err)) = check_execpolicy_for_warnings(&config.config_layer_stack).await { - let (path, range) = exec_policy_warning_location(&err); - let message = ConfigWarningNotification { - summary: "Error parsing rules; custom rules not applied.".to_string(), - details: Some(err.to_string()), - path, - range, - }; - config_warnings.push(message); + config_warnings.push(exec_policy_config_warning(&err)); } if let Some(warning) = project_config_warning(&config) { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 375307e804..6ae73784ff 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -447,7 +447,7 @@ impl MessageProcessor { outgoing.clone(), analytics_events_client.clone(), Arc::clone(&config), - config_warnings, + config_warnings.clone(), rpc_transport, ); let marketplace_processor = MarketplaceRequestProcessor::new( @@ -495,6 +495,7 @@ impl MessageProcessor { state_db.clone(), log_db, Arc::clone(&skills_watcher), + config_warnings, ); let turn_processor = TurnRequestProcessor::new( auth_manager.clone(), diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index b78c53a383..af8525873f 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -364,6 +364,7 @@ pub(crate) struct ThreadRequestProcessor { pub(super) log_db: Option, pub(super) background_tasks: TaskTracker, pub(super) skills_watcher: Arc, + pub(super) initial_config_warnings: Arc>, } /// Outcome of trying to satisfy a resume request from an already loaded thread. @@ -395,6 +396,7 @@ impl ThreadRequestProcessor { state_db: Option, log_db: Option, skills_watcher: Arc, + initial_config_warnings: Vec, ) -> Self { Self { auth_manager, @@ -413,6 +415,7 @@ impl ThreadRequestProcessor { log_db, background_tasks: TaskTracker::new(), skills_watcher, + initial_config_warnings: Arc::new(initial_config_warnings), } } @@ -968,6 +971,7 @@ impl ThreadRequestProcessor { }; let request_trace = request_context.request_trace(); let config_manager = self.config_manager.clone(); + let initial_config_warnings = Arc::clone(&self.initial_config_warnings); let outgoing = Arc::clone(&listener_task_context.outgoing); let error_request_id = request_id.clone(); let thread_start_task = async move { @@ -990,6 +994,7 @@ impl ThreadRequestProcessor { allow_provider_model_fallback, experimental_raw_events, request_trace, + initial_config_warnings, ) .await { @@ -1066,6 +1071,7 @@ impl ThreadRequestProcessor { allow_provider_model_fallback: bool, experimental_raw_events: bool, request_trace: Option, + initial_config_warnings: Arc>, ) -> Result<(), JSONRPCErrorError> { let thread_start_started_at = std::time::Instant::now(); let requested_cwd = typesafe_overrides.cwd.clone(); @@ -1139,6 +1145,21 @@ impl ThreadRequestProcessor { .map_err(|err| config_load_error(&err))?; } + if let Ok(Some(err)) = + codex_core::check_execpolicy_for_warnings(&config.config_layer_stack).await + { + let notification = crate::exec_policy_config_warning(&err); + if !initial_config_warnings.contains(¬ification) { + listener_task_context + .outgoing + .send_server_notification_to_connections( + &[request_id.connection_id], + ServerNotification::ConfigWarning(notification), + ) + .await; + } + } + let environments = environments.unwrap_or_else(|| { listener_task_context .thread_manager diff --git a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs index 648d60f3b5..ece66c8405 100644 --- a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs +++ b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket.rs @@ -7,6 +7,7 @@ use app_test_support::to_response; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use codex_app_server_protocol::ClientInfo; +use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::InitializeParams; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCMessage; @@ -18,6 +19,8 @@ use codex_app_server_protocol::ThreadLoadedListParams; use codex_app_server_protocol::ThreadLoadedListResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; +use codex_core::config::set_project_trust_level; +use codex_protocol::config_types::TrustLevel; use futures::SinkExt; use futures::StreamExt; use hmac::Hmac; @@ -104,6 +107,106 @@ async fn websocket_transport_routes_per_connection_handshake_and_responses() -> Ok(()) } +#[tokio::test] +async fn thread_start_routes_project_exec_policy_warning_to_requester() -> Result<()> { + let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri(), "never")?; + + let project = TempDir::new()?; + std::fs::create_dir(project.path().join(".git"))?; + let rules_dir = project.path().join(".codex/rules"); + std::fs::create_dir_all(&rules_dir)?; + let rules_path = rules_dir.join("broken.rules"); + std::fs::write(&rules_path, "prefix_rule(")?; + set_project_trust_level(codex_home.path(), project.path(), TrustLevel::Trusted)?; + + let (mut process, bind_addr) = spawn_websocket_server(codex_home.path()).await?; + let mut requester = connect_websocket(bind_addr).await?; + let mut other_client = connect_websocket(bind_addr).await?; + + send_initialize_request(&mut requester, /*id*/ 1, "requester").await?; + read_response_for_id(&mut requester, /*id*/ 1).await?; + send_initialize_request(&mut other_client, /*id*/ 2, "other_client").await?; + read_response_for_id(&mut other_client, /*id*/ 2).await?; + + send_request( + &mut requester, + "thread/start", + /*id*/ 3, + Some(serde_json::to_value(ThreadStartParams { + cwd: Some(project.path().display().to_string()), + model: Some("mock-model".to_string()), + ..Default::default() + })?), + ) + .await?; + + let target_id = RequestId::Integer(3); + let warning_summary = "Error parsing rules; custom rules not applied."; + let is_exec_policy_warning = |notification: &JSONRPCNotification| { + notification.method == "configWarning" + && notification + .params + .as_ref() + .and_then(|params| params.get("summary")) + .and_then(serde_json::Value::as_str) + == Some(warning_summary) + }; + let mut response = None; + let mut warning = None; + while response.is_none() || warning.is_none() { + match read_jsonrpc_message(&mut requester).await? { + JSONRPCMessage::Response(candidate) if candidate.id == target_id => { + response = Some(candidate); + } + JSONRPCMessage::Notification(candidate) if is_exec_policy_warning(&candidate) => { + warning = Some(candidate); + } + _ => {} + } + } + + let _: ThreadStartResponse = to_response(response.context("missing thread/start response")?)?; + let warning: ConfigWarningNotification = serde_json::from_value( + warning + .context("missing exec-policy configWarning")? + .params + .context("configWarning should include params")?, + )?; + assert_eq!( + warning + .path + .as_deref() + .map(Path::new) + .and_then(Path::file_name), + Some(std::ffi::OsStr::new("broken.rules")) + ); + + match timeout(Duration::from_millis(250), async { + loop { + let message = read_jsonrpc_message(&mut other_client).await?; + if let JSONRPCMessage::Notification(notification) = message + && is_exec_policy_warning(¬ification) + { + return Ok::<_, anyhow::Error>(notification); + } + } + }) + .await + { + Ok(Ok(_)) => bail!("exec-policy configWarning leaked to another connection"), + Ok(Err(err)) => return Err(err), + Err(_) => {} + } + + process + .kill() + .await + .context("failed to stop websocket app-server process")?; + Ok(()) +} + #[tokio::test] async fn websocket_transport_serves_health_endpoints_on_same_listener() -> Result<()> { let server = create_mock_responses_server_sequence_unchecked(Vec::new()).await; diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index f717dd0014..f96653b02a 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -7,14 +7,18 @@ use app_test_support::create_mock_responses_server_repeating_assistant; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; use codex_app_server_protocol::AskForApproval; +use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCMessage; +use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::McpServerStartupState; use codex_app_server_protocol::McpServerStatusUpdatedNotification; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SandboxMode; use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::TextPosition; +use codex_app_server_protocol::TextRange; use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ThreadSource; use codex_app_server_protocol::ThreadStartParams; @@ -54,6 +58,17 @@ use super::analytics::wait_for_analytics_payload; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); const INVALID_REQUEST_ERROR_CODE: i64 = -32600; +const EXEC_POLICY_PARSE_WARNING_SUMMARY: &str = "Error parsing rules; custom rules not applied."; + +fn is_exec_policy_config_warning(notification: &JSONRPCNotification) -> bool { + notification.method == "configWarning" + && notification + .params + .as_ref() + .and_then(|params| params.get("summary")) + .and_then(Value::as_str) + == Some(EXEC_POLICY_PARSE_WARNING_SUMMARY) +} async fn start_thread_with_model( mcp: &mut TestAppServer, @@ -104,6 +119,124 @@ model = "gpt-5.4-mini" Ok(()) } +#[tokio::test] +async fn thread_start_warns_for_exec_policy_parse_failure_after_initialize() -> Result<()> { + let codex_home = TempDir::new()?; + let mut mcp = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let rules_dir = codex_home.path().join("rules"); + std::fs::create_dir_all(&rules_dir)?; + let rules_path = rules_dir.join("broken.rules"); + std::fs::write(&rules_path, "prefix_rule(")?; + let rules_path = std::fs::canonicalize(rules_path)?; + + let request_id = mcp + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let response = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let _: ThreadStartResponse = to_response(response)?; + + let notification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_matching_notification( + "exec-policy configWarning", + is_exec_policy_config_warning, + ), + ) + .await??; + let notification: ServerNotification = notification.try_into()?; + let ServerNotification::ConfigWarning(warning) = notification else { + anyhow::bail!("unexpected notification variant"); + }; + let ConfigWarningNotification { + summary, + details, + path, + range, + } = warning; + assert_eq!( + (summary, range), + ( + "Error parsing rules; custom rules not applied.".to_string(), + Some(TextRange { + start: TextPosition { + line: 1, + column: 13, + }, + end: TextPosition { + line: 1, + column: 13, + }, + }), + ) + ); + let path = path.context("warning should include a path")?; + assert_eq!( + normalize_path_for_comparison(path), + normalize_path_for_comparison(&rules_path) + ); + let details = details.context("warning should include details")?; + assert!( + details.contains("failed to parse rules file") && details.contains("broken.rules"), + "unexpected warning details: {details}" + ); + assert!( + details.contains("Parse error"), + "unexpected warning details: {details}" + ); + + Ok(()) +} + +#[tokio::test] +async fn thread_start_does_not_repeat_initialize_exec_policy_warning() -> Result<()> { + let codex_home = TempDir::new()?; + let rules_dir = codex_home.path().join("rules"); + std::fs::create_dir_all(&rules_dir)?; + std::fs::write(rules_dir.join("broken.rules"), "prefix_rule(")?; + + let mut mcp = TestAppServer::new_with_auto_env(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_matching_notification( + "initialize exec-policy configWarning", + is_exec_policy_config_warning, + ), + ) + .await??; + + let request_id = mcp + .send_thread_start_request_with_auto_env(ThreadStartParams::default()) + .await?; + let response = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let _: ThreadStartResponse = to_response(response)?; + + let duplicate_warning = timeout( + std::time::Duration::from_millis(250), + mcp.read_stream_until_matching_notification( + "duplicate exec-policy configWarning", + is_exec_policy_config_warning, + ), + ) + .await; + assert!( + duplicate_warning.is_err(), + "thread/start repeated the initialize exec-policy warning" + ); + + Ok(()) +} + #[tokio::test] async fn thread_start_provider_model_fallback_uses_bedrock_static_catalog() -> Result<()> { let codex_home = TempDir::new()?; From 8f5bb6171e0b6a64ed01d9b7cf865604ad79ec46 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 6 Jul 2026 10:22:25 -0700 Subject: [PATCH 12/17] Remove TUI exec-policy core exports (#31179) ## Why The TUI still reached through `codex_app_server_client::legacy_core` to validate exec-policy rules during local startup. The app server already owns this validation and reports parse failures through `configWarning`, so the duplicate TUI preflight preserved an unnecessary core dependency and could inspect the wrong machine when connected to a remote app server. ## What changed - Remove the TUI's direct exec-policy startup check. - Remove the two exec-policy re-exports from `legacy_core`. - Rely on the app server's existing config-warning flow for malformed custom rules in both embedded and remote sessions. --- codex-rs/app-server-client/src/lib.rs | 3 --- codex-rs/app-server/src/in_process.rs | 12 +++++++++++- codex-rs/tui/src/lib.rs | 14 -------------- 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/codex-rs/app-server-client/src/lib.rs b/codex-rs/app-server-client/src/lib.rs index b7a958eff1..4eec8a2348 100644 --- a/codex-rs/app-server-client/src/lib.rs +++ b/codex-rs/app-server-client/src/lib.rs @@ -78,9 +78,6 @@ pub use crate::remote::RemoteAppServerEndpoint; /// 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::check_execpolicy_for_warnings; - pub use codex_core::format_exec_policy_error_with_source; - pub mod config { pub use codex_core::config::*; diff --git a/codex-rs/app-server/src/in_process.rs b/codex-rs/app-server/src/in_process.rs index 938d539a9f..d8a2bc2276 100644 --- a/codex-rs/app-server/src/in_process.rs +++ b/codex-rs/app-server/src/in_process.rs @@ -80,6 +80,7 @@ use codex_arg0::Arg0DispatchPaths; use codex_config::CloudConfigBundleLoader; use codex_config::LoaderOverrides; use codex_config::ThreadConfigLoader; +use codex_core::check_execpolicy_for_warnings; use codex_core::config::Config; use codex_core::resolve_installation_id; use codex_exec_server::EnvironmentManager; @@ -349,7 +350,16 @@ impl InProcessClientHandle { /// This function sends `initialize` followed by `initialized` before returning /// the handle, so callers receive a ready-to-use runtime. If initialize fails, /// the runtime is shut down and an `InvalidData` error is returned. -pub async fn start(args: InProcessStartArgs) -> IoResult { +pub async fn start(mut args: InProcessStartArgs) -> IoResult { + if let Ok(Some(err)) = check_execpolicy_for_warnings(&args.config.config_layer_stack).await { + let (path, range) = crate::exec_policy_warning_location(&err); + args.config_warnings.push(ConfigWarningNotification { + summary: "Error parsing rules; custom rules not applied.".to_string(), + details: Some(err.to_string()), + path, + range, + }); + } let initialize = args.initialize.clone(); let client = start_uninitialized(args).await?; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 96f442a88c..dc8262f7db 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -3,7 +3,6 @@ // alternate‑screen mode starts; that file opts‑out locally via `allow`. #![deny(clippy::print_stdout, clippy::print_stderr)] #![deny(clippy::disallowed_methods)] -use crate::legacy_core::check_execpolicy_for_warnings; use crate::legacy_core::config::Config; use crate::legacy_core::config::ConfigBuilder; use crate::legacy_core::config::ConfigOverrides; @@ -13,7 +12,6 @@ use crate::legacy_core::config::resolve_bootstrap_auth_keyring_backend_kind; use crate::legacy_core::config::resolve_bootstrap_auth_route_config; use crate::legacy_core::config::resolve_oss_provider; use crate::legacy_core::config::resolve_profile_v2_config_path; -use crate::legacy_core::format_exec_policy_error_with_source; use crate::session_resume::ResolveCwdOutcome; use crate::session_resume::resolve_cwd_for_resume_or_fork; pub use crate::startup_error::LocalStateDbStartupError; @@ -1141,18 +1139,6 @@ pub async fn run_main( .as_table() .is_some_and(|table| table.contains_key("log_dir")); - #[allow(clippy::print_stderr)] - match check_execpolicy_for_warnings(&config.config_layer_stack).await { - Ok(None) => {} - Ok(Some(err)) | Err(err) => { - eprintln!( - "Error loading rules:\n{}", - format_exec_policy_error_with_source(&err) - ); - std::process::exit(1); - } - } - set_default_client_residency_requirement(config.enforce_residency.value()); if let Some(warning) = add_dir_warning_message( From 8268cbfb0e5f39cb4efff928264fe8f29ddacafb Mon Sep 17 00:00:00 2001 From: canvrno-oai Date: Mon, 6 Jul 2026 10:27:39 -0700 Subject: [PATCH 13/17] Conditional codex_home dotenv (#29959) ## Summary Adds conditional dotenv overlays under `CODEX_HOME`. After loading the current `.env`, Codex discovers `.env.*` files in lexicographic order and applies each overlay when its TCP condition passes. Evaluation and environment mutation occur during single-threaded startup, before Codex creates its runtime, workers, sessions, or network clients. ## Supported behavior - TCP connectivity checks using either: - Explicit `host` and `port`. - A URL or authority stored in an overlay assignment referenced by `from`. - Direct negation of a TCP check using `not`. - Setting dotenv assignments when a condition passes. - Unsetting variables with `# codex-env-unset`. - A default 500 ms connection timeout with a maximum of 5 seconds. - Ignores filenames ending in `~` or a case-insensitive final suffix of `bak`, `back`, `backup`, `bkp`, `old`, `orig`, `original`, `save`, `saved`, `disable`, `disabled`, `inactive`, `off`, `tmp`, `temp`, `swp`, `swo`, `example`, `sample`, `template`, or `dist`. - Fail-closed handling of malformed overlays without exposing environment values. - Case-insensitive protection against setting or unsetting `CODEX_*` variables. Files without a `# codex-env-if:` directive as their first non-empty line are ignored. ## Usage Set variables when an endpoint is reachable: ```dotenv # ~/.codex/.env.10-proxy-on # codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY","timeout_ms":500} HTTPS_PROXY=http://proxy.example.com:8080 HTTP_PROXY=http://proxy.example.com:8080 ALL_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1,.example.com ``` Unset variables when the endpoint is unreachable: ```dotenv # ~/.codex/.env.20-proxy-off # codex-env-if: {"not":{"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":500}} # codex-env-unset: ["HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY"] ``` Each overlay is evaluated independently. A full Codex restart is required after changing overlays or moving between networks. The timeout bounds TCP connection attempts but does not bound synchronous DNS resolution. ## Testing ```console just test -p codex-arg0 ``` For manual validation: 1. Configure an overlay with a reachable TCP endpoint and a test assignment. 2. Start Codex and verify the assignment is present in a spawned command. 3. Restart Codex with the endpoint unreachable and verify a negated overlay removes inherited variables. 4. Verify malformed overlays are skipped and `CODEX_*` variables remain unchanged. ## Future ideas: - File-existence conditions. - Environment-variable equality conditions. - Operating-system conditions. - General condition composition with `all`, `any`, and arbitrarily nested `not`. --- codex-rs/Cargo.lock | 3 + codex-rs/arg0/Cargo.toml | 5 +- .../conditional_dotenv_tests.rs | 281 +++++++++++ codex-rs/arg0/src/conditional_dotenv/mod.rs | 465 ++++++++++++++++++ codex-rs/arg0/src/lib.rs | 24 +- 5 files changed, 771 insertions(+), 7 deletions(-) create mode 100644 codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs create mode 100644 codex-rs/arg0/src/conditional_dotenv/mod.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 6ac51d403f..e590d17497 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2227,8 +2227,11 @@ dependencies = [ "codex-windows-sandbox", "dotenvy", "pretty_assertions", + "serde", + "serde_json", "tempfile", "tokio", + "url", ] [[package]] diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index bb45db4552..400e3fbb9c 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -23,8 +23,11 @@ codex-shell-escalation = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-home-dir = { workspace = true } dotenvy = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true, features = ["rt-multi-thread"] } +tokio = { workspace = true, features = ["net", "rt-multi-thread", "time"] } +url = { workspace = true } [target.'cfg(windows)'.dependencies] codex-windows-sandbox = { workspace = true } diff --git a/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs b/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs new file mode 100644 index 0000000000..f4b5dfb1e6 --- /dev/null +++ b/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs @@ -0,0 +1,281 @@ +use super::*; +use pretty_assertions::assert_eq; +use std::cell::Cell; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::fs; +use std::time::Duration; + +#[derive(Debug, Default, PartialEq, Eq)] +struct TestEnvironment(BTreeMap); + +impl StartupEnvironment for TestEnvironment { + fn set(&mut self, key: &str, value: &str) { + self.0.insert(key.to_string(), value.to_string()); + } + + fn remove(&mut self, key: &str) { + self.0.remove(key); + } +} + +fn write_overlay(codex_home: &Path, name: &str, contents: &str) -> std::io::Result<()> { + fs::write(codex_home.join(name), contents) +} + +fn test_environment(values: [(&str, &str); N]) -> TestEnvironment { + TestEnvironment(BTreeMap::from( + values.map(|(key, value)| (key.to_string(), value.to_string())), + )) +} + +#[test] +fn proxy_overlays_set_or_unset_environment_for_network() -> anyhow::Result<()> { + let codex_home = tempfile::tempdir()?; + write_overlay( + codex_home.path(), + ".env.10-proxy-on", + r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY","timeout_ms":500} +HTTPS_PROXY=http://user:password@proxy.example.com:8080 +HTTP_PROXY=http://proxy.example.com:8080 +ALL_PROXY=http://proxy.example.com:8080 +NO_PROXY=localhost,127.0.0.1,.example.com +"#, + )?; + write_overlay( + codex_home.path(), + ".env.20-proxy-off", + r#"# codex-env-if: {"not":{"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":500}} +# codex-env-unset: ["HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY"] +"#, + )?; + + let on_network_calls = Cell::new(0); + let on_network_connector = |host: &str, port: u16, timeout: Duration| { + on_network_calls.set(on_network_calls.get() + 1); + assert_eq!(host, "proxy.example.com"); + assert_eq!(port, 8080); + assert_eq!(timeout, Duration::from_millis(500)); + true + }; + let mut on_network_environment = test_environment([ + ("HTTPS_PROXY", "http://stale.example.com:8080"), + ("UNRELATED", "preserved"), + ]); + + let warnings = load_conditional_dotenv_overlays( + codex_home.path(), + &mut on_network_environment, + &on_network_connector, + ); + + assert_eq!(on_network_calls.get(), 2); + assert_eq!(warnings, Vec::::new()); + assert_eq!( + on_network_environment, + test_environment([ + ("ALL_PROXY", "http://proxy.example.com:8080"), + ("HTTPS_PROXY", "http://user:password@proxy.example.com:8080"), + ("HTTP_PROXY", "http://proxy.example.com:8080"), + ("NO_PROXY", "localhost,127.0.0.1,.example.com"), + ("UNRELATED", "preserved"), + ]) + ); + + let off_network_calls = Cell::new(0); + let off_network_connector = |host: &str, port: u16, timeout: Duration| { + off_network_calls.set(off_network_calls.get() + 1); + assert_eq!(host, "proxy.example.com"); + assert_eq!(port, 8080); + assert_eq!(timeout, Duration::from_millis(500)); + false + }; + let mut off_network_environment = test_environment([ + ("ALL_PROXY", "http://inherited.example.com:8080"), + ("HTTPS_PROXY", "http://inherited.example.com:8080"), + ("HTTP_PROXY", "http://inherited.example.com:8080"), + ("NO_PROXY", "localhost"), + ("UNRELATED", "preserved"), + ]); + + let warnings = load_conditional_dotenv_overlays( + codex_home.path(), + &mut off_network_environment, + &off_network_connector, + ); + + assert_eq!(off_network_calls.get(), 2); + assert_eq!(warnings, Vec::::new()); + assert_eq!( + off_network_environment, + test_environment([("UNRELATED", "preserved")]) + ); + Ok(()) +} + +#[test] +fn overlay_filters_reserved_names_for_set_and_unset() -> anyhow::Result<()> { + let codex_home = tempfile::tempdir()?; + write_overlay( + codex_home.path(), + ".env.proxy", + r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} +# codex-env-unset: ["ALL_PROXY","codex_internal"] +HTTP_PROXY=http://proxy.example.com:8080 +codex_internal=changed +"#, + )?; + let mut environment = test_environment([ + ("ALL_PROXY", "http://old.example.com:8080"), + ("codex_internal", "preserved"), + ]); + + let warnings = + load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &|_, _, _| true); + + assert_eq!(warnings, Vec::::new()); + assert_eq!( + environment, + test_environment([ + ("HTTP_PROXY", "http://proxy.example.com:8080"), + ("codex_internal", "preserved"), + ]) + ); + Ok(()) +} + +#[test] +fn invalid_timeout_fails_closed_without_blocking_valid_overlays() -> anyhow::Result<()> { + let codex_home = tempfile::tempdir()?; + write_overlay(codex_home.path(), ".env.example", "SHOULD_NOT_LOAD=1\n")?; + write_overlay( + codex_home.path(), + ".env.10-timeout", + r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":5001} +SHOULD_NOT_LOAD=2 +"#, + )?; + write_overlay( + codex_home.path(), + ".env.20-maximum-timeout", + r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":5000} +MAXIMUM_TIMEOUT=loaded +"#, + )?; + write_overlay( + codex_home.path(), + ".env.30-default-timeout", + r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} +DEFAULT_TIMEOUT=loaded +"#, + )?; + let observed_timeouts = RefCell::new(Vec::new()); + let connector = |_: &str, _: u16, timeout: Duration| { + observed_timeouts.borrow_mut().push(timeout); + true + }; + let mut environment = TestEnvironment::default(); + + let warnings = + load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &connector); + + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains(".env.10-timeout")); + assert_eq!( + observed_timeouts.into_inner(), + vec![Duration::from_millis(5000), Duration::from_millis(500)] + ); + assert_eq!( + environment, + test_environment([("DEFAULT_TIMEOUT", "loaded"), ("MAXIMUM_TIMEOUT", "loaded"),]) + ); + Ok(()) +} + +#[test] +fn invalid_from_sources_fail_closed_without_connecting() -> anyhow::Result<()> { + let codex_home = tempfile::tempdir()?; + write_overlay( + codex_home.path(), + ".env.10-missing-source", + r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY"} +SHOULD_NOT_LOAD=1 +"#, + )?; + write_overlay( + codex_home.path(), + ".env.20-invalid-source", + r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY"} +HTTPS_PROXY="not a url" +"#, + )?; + let connector_called = Cell::new(false); + let connector = |_: &str, _: u16, _: Duration| { + connector_called.set(true); + true + }; + let mut environment = TestEnvironment::default(); + + let warnings = + load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &connector); + + assert!(!connector_called.get()); + assert_eq!(warnings.len(), 2); + assert_eq!(environment, TestEnvironment::default()); + Ok(()) +} + +#[test] +fn directives_inside_multiline_values_are_not_scanned() -> anyhow::Result<()> { + let codex_home = tempfile::tempdir()?; + write_overlay( + codex_home.path(), + ".env.multiline", + r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} +# codex-env-unset: ["HTTP_PROXY"] +MESSAGE='before +# codex-env-unset: ["ALL_PROXY"] +# codex-env-if: {"not":{"type":"tcp_connect","host":"other.example.com","port":8080}} +after' +"#, + )?; + let mut environment = test_environment([ + ("ALL_PROXY", "http://proxy.example.com:8080"), + ("HTTP_PROXY", "http://proxy.example.com:8080"), + ]); + + let warnings = + load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &|_, _, _| true); + + assert_eq!(warnings, Vec::::new()); + assert_eq!( + environment, + test_environment([ + ("ALL_PROXY", "http://proxy.example.com:8080"), + ( + "MESSAGE", + "before\n# codex-env-unset: [\"ALL_PROXY\"]\n# codex-env-if: {\"not\":{\"type\":\"tcp_connect\",\"host\":\"other.example.com\",\"port\":8080}}\nafter", + ), + ]) + ); + Ok(()) +} + +#[test] +fn endpoint_parser_supports_urls_bare_authorities_and_known_default_ports() { + assert_eq!( + [ + "http://user:password@proxy.example.com:8080", + "proxy.example.com:8080", + "https://proxy.example.com", + "http://[::1]:8080", + ] + .map(parse_endpoint), + [ + Some(("proxy.example.com".to_string(), 8080)), + Some(("proxy.example.com".to_string(), 8080)), + Some(("proxy.example.com".to_string(), 443)), + Some(("::1".to_string(), 8080)), + ] + ); +} diff --git a/codex-rs/arg0/src/conditional_dotenv/mod.rs b/codex-rs/arg0/src/conditional_dotenv/mod.rs new file mode 100644 index 0000000000..c3ed40179e --- /dev/null +++ b/codex-rs/arg0/src/conditional_dotenv/mod.rs @@ -0,0 +1,465 @@ +//! Loads TCP-gated dotenv overlays from `CODEX_HOME` during single-threaded startup. +//! +//! Example `~/.codex/.env.corporate-proxy`: +//! +//! ```dotenv +//! # codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY","timeout_ms":500} +//! HTTPS_PROXY=http://proxy.example.com:8080 +//! HTTP_PROXY=http://proxy.example.com:8080 +//! ALL_PROXY=http://proxy.example.com:8080 +//! NO_PROXY=localhost,127.0.0.1,.example.com +//! ``` +//! +//! A TCP condition can be inverted with `{"not":{"type":"tcp_connect",...}}`, which allows a +//! second overlay to unset proxy variables when the endpoint is unreachable. + +use crate::is_reserved_env_var; +use serde::Deserialize; +use std::ffi::OsString; +use std::net::ToSocketAddrs; +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::time::Duration; +use std::time::Instant; +use url::Url; + +pub(crate) const TCP_CONNECT_HELPER_ARG1: &str = "--codex-run-as-tcp-connect-probe"; + +const CONDITIONAL_DOTENV_PREFIX: &str = ".env."; +const CONDITION_DIRECTIVE_PREFIX: &str = "# codex-env-if:"; +const UNSET_DIRECTIVE_PREFIX: &str = "# codex-env-unset:"; +const DEFAULT_TCP_CONNECT_TIMEOUT_MS: u64 = 500; +const MAX_TCP_CONNECT_TIMEOUT_MS: u64 = 5_000; +const TCP_CONNECT_HELPER_POLL_INTERVAL: Duration = Duration::from_millis(10); +const IGNORED_CONDITIONAL_DOTENV_SUFFIXES: &[&str] = &[ + "bak", "back", "backup", "bkp", "old", "orig", "original", "save", "saved", "disable", + "disabled", "inactive", "off", "tmp", "temp", "swp", "swo", "example", "sample", "template", + "dist", +]; + +type TcpConnector<'a> = dyn Fn(&str, u16, Duration) -> bool + 'a; + +pub(crate) fn load(codex_home: &Path) { + let mut environment = ProcessEnvironment; + + for warning in + load_conditional_dotenv_overlays(codex_home, &mut environment, &system_tcp_connect) + { + eprintln!("WARNING: skipped conditional dotenv overlay: {warning}"); + } +} + +/// Runs an OS-resolved TCP probe in the child process used by [`system_tcp_connect`]. +/// +/// This exits before dotenv loading, so its resolver and connection tasks cannot race with the +/// parent's environment mutation. +pub(crate) fn run_tcp_connect_helper(mut args: impl Iterator) -> ! { + let host = args.next().and_then(|value| value.into_string().ok()); + let port = args + .next() + .and_then(|value| value.into_string().ok()) + .and_then(|value| value.parse::().ok()); + let timeout = args + .next() + .and_then(|value| value.into_string().ok()) + .and_then(|value| value.parse::().ok()) + .and_then(|timeout_ms| tcp_connect_timeout(Some(timeout_ms)).ok()); + let connected = match (host, port, timeout) { + (Some(host), Some(port), Some(timeout)) => direct_tcp_connect(&host, port, timeout), + _ => false, + }; + let exit_code = if connected { 0 } else { 1 }; + std::process::exit(exit_code); +} + +fn load_conditional_dotenv_overlays( + codex_home: &Path, + environment: &mut dyn StartupEnvironment, + tcp_connect: &TcpConnector<'_>, +) -> Vec { + let paths = match conditional_dotenv_paths(codex_home) { + Ok(paths) => paths, + Err(err) => { + return vec![format!( + "could not discover overlays in {}: {err}", + codex_home.display() + )]; + } + }; + let mut warnings = Vec::new(); + + for path in paths { + let overlay = match parse_conditional_dotenv(&path) { + Ok(Some(overlay)) => overlay, + Ok(None) => continue, + Err(err) => { + warnings.push(format!("{}: {err}", path.display())); + continue; + } + }; + match evaluate_condition(&overlay.condition, &overlay.entries, tcp_connect) { + Ok(true) => apply_overlay(overlay, environment), + Ok(false) => {} + Err(err) => warnings.push(format!("{}: {err}", path.display())), + } + } + + warnings +} + +fn conditional_dotenv_paths(codex_home: &Path) -> std::io::Result> { + let entries = match std::fs::read_dir(codex_home) { + Ok(entries) => entries, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(err) => return Err(err), + }; + let mut paths = Vec::new(); + + for entry in entries { + let entry = entry?; + let file_name = entry.file_name(); + let Some(file_name) = file_name.to_str() else { + continue; + }; + let is_ignored = file_name.ends_with('~') + || file_name.rsplit_once('.').is_some_and(|(_, suffix)| { + IGNORED_CONDITIONAL_DOTENV_SUFFIXES + .iter() + .any(|ignored| suffix.eq_ignore_ascii_case(ignored)) + }); + if file_name.starts_with(CONDITIONAL_DOTENV_PREFIX) + && file_name.len() > CONDITIONAL_DOTENV_PREFIX.len() + && !is_ignored + && entry.path().is_file() + { + paths.push(entry.path()); + } + } + + paths.sort(); + Ok(paths) +} + +fn parse_conditional_dotenv(path: &Path) -> Result, String> { + let contents = + std::fs::read_to_string(path).map_err(|err| format!("could not read file: {err}"))?; + let contents = contents.strip_prefix('\u{feff}').unwrap_or(&contents); + let mut lines = contents + .lines() + .map(|line| line.trim_start_matches('\u{feff}').trim()); + let Some(first_line) = lines.find(|line| !line.is_empty()) else { + return Ok(None); + }; + let Some(condition_json) = first_line.strip_prefix(CONDITION_DIRECTIVE_PREFIX) else { + return Ok(None); + }; + let condition_json = condition_json.trim(); + if condition_json.is_empty() { + return Err("condition directive is empty".to_string()); + } + let condition = serde_json::from_str(condition_json) + .map_err(|err| format!("condition directive is invalid: {err}"))?; + + let mut unset = None; + for line in lines { + if !line.is_empty() && !line.starts_with('#') { + break; + } + if line.starts_with(CONDITION_DIRECTIVE_PREFIX) { + return Err("exactly one condition directive is required".to_string()); + } + if let Some(unset_json) = line.strip_prefix(UNSET_DIRECTIVE_PREFIX) { + if unset.is_some() { + return Err("multiple unset directives are not supported".to_string()); + } + let keys: Vec = serde_json::from_str(unset_json.trim()) + .map_err(|err| format!("unset directive is invalid: {err}"))?; + if let Some(key) = keys.iter().find(|key| !is_valid_env_var_name(key)) { + return Err(format!( + "unset directive contains invalid environment variable name `{key}`" + )); + } + unset = Some(keys); + } + } + + let entries = dotenvy::from_read_iter(contents.as_bytes()) + .collect::, _>>() + .map_err(|_| "file contains an invalid dotenv assignment".to_string())?; + if entries.iter().any(|(_, value)| value.contains('\0')) { + return Err("file contains a dotenv value with a NUL byte".to_string()); + } + + Ok(Some(ConditionalDotenv { + condition, + unset: unset.unwrap_or_default(), + entries, + })) +} + +fn evaluate_condition( + condition: &Condition, + overlay_entries: &[(String, String)], + tcp_connect: &TcpConnector<'_>, +) -> Result { + match condition { + Condition::TcpConnect(condition) => { + evaluate_tcp_connect(condition, overlay_entries, tcp_connect) + } + Condition::Not { not } => { + evaluate_tcp_connect(not, overlay_entries, tcp_connect).map(|connected| !connected) + } + } +} + +fn evaluate_tcp_connect( + condition: &TcpConnectCondition, + overlay_entries: &[(String, String)], + tcp_connect: &TcpConnector<'_>, +) -> Result { + match condition { + TcpConnectCondition::TcpConnect { + from, + host, + port, + timeout_ms, + } => { + let target = parse_tcp_connect_target(from.as_deref(), host.as_deref(), *port)?; + let (host, port) = match target { + TcpConnectTarget::FromVariable(from) => { + let value = overlay_entries + .iter() + .rev() + .find_map(|(key, value)| { + (key == from || (cfg!(windows) && key.eq_ignore_ascii_case(from))) + .then_some(value) + }) + .ok_or_else(|| { + format!( + "tcp_connect source variable `{from}` is not defined in the overlay" + ) + })?; + parse_endpoint(value).ok_or_else(|| { + format!( + "tcp_connect source variable `{from}` does not contain a valid endpoint" + ) + })? + } + TcpConnectTarget::Explicit { host, port } => (host.to_string(), port), + }; + let timeout = tcp_connect_timeout(*timeout_ms)?; + Ok((tcp_connect)(&host, port, timeout)) + } + } +} + +fn apply_overlay(overlay: ConditionalDotenv, environment: &mut dyn StartupEnvironment) { + for key in overlay.unset { + if !is_reserved_env_var(&key) { + environment.remove(&key); + } + } + for (key, value) in overlay.entries { + if !is_reserved_env_var(&key) { + environment.set(&key, &value); + } + } +} + +enum TcpConnectTarget<'a> { + FromVariable(&'a str), + Explicit { host: &'a str, port: u16 }, +} + +fn parse_tcp_connect_target<'a>( + from: Option<&'a str>, + host: Option<&'a str>, + port: Option, +) -> Result, String> { + match (from, host, port) { + (Some(from), None, None) => { + if !is_valid_env_var_name(from) { + return Err(format!( + "tcp_connect contains invalid source variable name `{from}`" + )); + } + Ok(TcpConnectTarget::FromVariable(from)) + } + (None, Some(host), Some(port)) => { + if host.is_empty() { + return Err("tcp_connect host must not be empty".to_string()); + } + if port == 0 { + return Err("tcp_connect port must be greater than zero".to_string()); + } + Ok(TcpConnectTarget::Explicit { host, port }) + } + (Some(_), _, _) => Err( + "tcp_connect must specify either `from` or `host` and `port`, but not both".to_string(), + ), + (None, _, _) => { + Err("tcp_connect requires either `from` or both `host` and `port`".to_string()) + } + } +} + +fn tcp_connect_timeout(timeout_ms: Option) -> Result { + let timeout_ms = timeout_ms.unwrap_or(DEFAULT_TCP_CONNECT_TIMEOUT_MS); + if !(1..=MAX_TCP_CONNECT_TIMEOUT_MS).contains(&timeout_ms) { + return Err(format!( + "tcp_connect timeout_ms must be between 1 and {MAX_TCP_CONNECT_TIMEOUT_MS}" + )); + } + Ok(Duration::from_millis(timeout_ms)) +} + +fn parse_endpoint(value: &str) -> Option<(String, u16)> { + let value = value.trim(); + let parsed = if value.contains("://") { + Url::parse(value).ok()? + } else { + Url::parse(&format!("http://{value}")).ok()? + }; + let host = match parsed.host()? { + url::Host::Ipv6(address) => address.to_string(), + host => host.to_string(), + }; + let port = parsed.port_or_known_default()?; + (port != 0).then_some((host, port)) +} + +fn system_tcp_connect(host: &str, port: u16, timeout: Duration) -> bool { + // `getaddrinfo` cannot be cancelled portably. Isolate it in a child that can be killed and + // reaped without introducing a resolver thread into the environment-mutating parent. + let Ok(current_exe) = std::env::current_exe() else { + return false; + }; + let Ok(mut child) = Command::new(current_exe) + .arg(TCP_CONNECT_HELPER_ARG1) + .arg(host) + .arg(port.to_string()) + .arg(timeout.as_millis().to_string()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + else { + return false; + }; + + let deadline = Instant::now() + timeout; + loop { + match child.try_wait() { + Ok(Some(status)) => return status.success(), + Ok(None) => {} + Err(_) => break, + } + + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + std::thread::sleep(remaining.min(TCP_CONNECT_HELPER_POLL_INTERVAL)); + } + + let _ = child.kill(); + let _ = child.wait(); + false +} + +fn direct_tcp_connect(host: &str, port: u16, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + let Ok(addresses) = (host, port) + .to_socket_addrs() + .map(Iterator::collect::>) + else { + return false; + }; + if deadline.saturating_duration_since(Instant::now()).is_zero() { + return false; + } + + let Ok(runtime) = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + else { + return false; + }; + runtime.block_on(async move { + tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), async move { + let mut attempts = tokio::task::JoinSet::new(); + for address in addresses { + attempts.spawn(tokio::net::TcpStream::connect(address)); + } + while let Some(result) = attempts.join_next().await { + if matches!(result, Ok(Ok(_))) { + return true; + } + } + false + }) + .await + .unwrap_or(false) + }) +} + +fn is_valid_env_var_name(key: &str) -> bool { + let mut chars = key.chars(); + chars + .next() + .is_some_and(|first| first.is_ascii_alphabetic() || first == '_') + && chars.all(|character| { + character.is_ascii_alphanumeric() || character == '_' || character == '.' + }) +} + +/// Minimal environment interface used to test overlay application without mutating the test +/// process environment. +trait StartupEnvironment { + fn set(&mut self, key: &str, value: &str); + fn remove(&mut self, key: &str); +} + +struct ProcessEnvironment; + +impl StartupEnvironment for ProcessEnvironment { + fn set(&mut self, key: &str, value: &str) { + // Safety: this loader runs from arg0_dispatch before Codex creates any threads. + unsafe { std::env::set_var(key, value) }; + } + + fn remove(&mut self, key: &str) { + // Safety: this loader runs from arg0_dispatch before Codex creates any threads. + unsafe { std::env::remove_var(key) }; + } +} + +struct ConditionalDotenv { + condition: Condition, + unset: Vec, + entries: Vec<(String, String)>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged, deny_unknown_fields)] +enum Condition { + TcpConnect(TcpConnectCondition), + Not { not: TcpConnectCondition }, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum TcpConnectCondition { + TcpConnect { + from: Option, + host: Option, + port: Option, + timeout_ms: Option, + }, +} + +#[cfg(test)] +#[path = "conditional_dotenv_tests.rs"] +mod tests; diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index 1c28f81d8c..3833449822 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -15,6 +15,8 @@ use codex_windows_sandbox::CODEX_WINDOWS_SANDBOX_ARG1; use std::os::unix::fs::symlink; use tempfile::TempDir; +mod conditional_dotenv; + const APPLY_PATCH_ARG0: &str = "apply_patch"; const MISSPELLED_APPLY_PATCH_ARG0: &str = "applypatch"; #[cfg(unix)] @@ -98,6 +100,9 @@ pub fn arg0_dispatch() -> Option { } let argv1 = args.next().unwrap_or_default(); + if argv1 == conditional_dotenv::TCP_CONNECT_HELPER_ARG1 { + conditional_dotenv::run_tcp_connect_helper(args); + } if argv1 == CODEX_FS_HELPER_ARG1 { codex_exec_server::run_fs_helper_main(); } @@ -191,7 +196,7 @@ fn prepare_path_env_var_with_aliases( /// `codex-linux-sandbox` we *directly* execute /// [`codex_linux_sandbox::run_main`] (which never returns). Otherwise we: /// -/// 1. Load `.env` values from `~/.codex/.env` before creating any threads. +/// 1. Load `.env` and matching conditional dotenv values from `~/.codex` before creating threads. /// 2. Spawn a main runtime thread with a controlled stack size. /// 3. Construct a Tokio multi-thread runtime. /// 4. Capture the current executable path and derive the @@ -285,16 +290,18 @@ fn build_runtime() -> anyhow::Result { const ILLEGAL_ENV_VAR_PREFIX: &str = "CODEX_"; -/// Load env vars from ~/.codex/.env. +/// Load base and conditional env vars from the startup Codex home. /// /// Security: Do not allow `.env` files to create or modify any variables /// with names starting with `CODEX_`. fn load_dotenv() { - if let Ok(codex_home) = find_codex_home() - && let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) - { + let Ok(codex_home) = find_codex_home() else { + return; + }; + if let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) { set_filtered(iter); } + conditional_dotenv::load(codex_home.as_path()); } /// Helper to set vars from a dotenvy iterator while filtering out `CODEX_` keys. @@ -303,7 +310,7 @@ where I: IntoIterator>, { for (key, value) in iter.into_iter().flatten() { - if !key.to_ascii_uppercase().starts_with(ILLEGAL_ENV_VAR_PREFIX) { + if !is_reserved_env_var(&key) { // It is safe to call set_var() because our process is // single-threaded at this point in its execution. unsafe { std::env::set_var(&key, &value) }; @@ -311,6 +318,11 @@ where } } +fn is_reserved_env_var(key: &str) -> bool { + key.get(..ILLEGAL_ENV_VAR_PREFIX.len()) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case(ILLEGAL_ENV_VAR_PREFIX)) +} + /// Creates a temporary directory with either: /// /// - UNIX: `apply_patch` symlink to the current executable From 84fe70c30e88a1828a510804341202bab629d507 Mon Sep 17 00:00:00 2001 From: Channing Conger Date: Mon, 6 Jul 2026 11:20:32 -0700 Subject: [PATCH 14/17] elicitations: Move to shared ElicitationService (#30627) ## Why Code-mode tool results could return to the model while an MCP elicitation was still waiting for user input. This differed from parallel tool calling and could let the model continue before the user resolved the request. We need one session-level view of outstanding elicitations so tool runtimes can consistently hold results until every pending elicitation is resolved. ## What changed - Added a counted, session-owned ElicitationService with RAII registrations. - Registered both core-originated and server-originated MCP elicitations with the service. - Migrated out-of-band elicitation tracking and unified exec timeout pausing to the shared service. - Made code-mode functions.exec and functions.wait capture their runtime result normally, then hold it before returning while an elicitation is outstanding. - Kept terminate: true immediate; only its result is held. - Preserved model-visible wall time across the elicitation hold. - Kept the behavior session-scoped, with concurrent elicitations holding the pause until all registrations are released. --- .../src/protocol/v2/thread.rs | 4 +- codex-rs/codex-mcp/src/connection_manager.rs | 3 + .../codex-mcp/src/connection_manager_tests.rs | 24 +++++ codex-rs/codex-mcp/src/elicitation.rs | 33 ++++++ codex-rs/codex-mcp/src/lib.rs | 1 + codex-rs/codex-mcp/src/mcp/mod.rs | 2 + codex-rs/core/src/codex_thread.rs | 47 ++++---- codex-rs/core/src/connectors.rs | 1 + codex-rs/core/src/elicitation.rs | 100 ++++++++++++++++++ codex-rs/core/src/elicitation_tests.rs | 19 ++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/mcp_tool_call_tests.rs | 1 + codex-rs/core/src/session/mcp.rs | 7 ++ codex-rs/core/src/session/mod.rs | 8 +- codex-rs/core/src/session/session.rs | 7 +- codex-rs/core/src/session/tests.rs | 4 +- codex-rs/core/src/state/service.rs | 2 + .../src/tools/code_mode/execute_handler.rs | 1 + .../core/src/tools/code_mode/wait_handler.rs | 1 + codex-rs/core/src/unified_exec/mod_tests.rs | 7 +- .../core/src/unified_exec/process_manager.rs | 8 +- codex-rs/core/tests/suite/code_mode.rs | 70 ++++++++++++ 22 files changed, 302 insertions(+), 49 deletions(-) create mode 100644 codex-rs/core/src/elicitation.rs create mode 100644 codex-rs/core/src/elicitation_tests.rs diff --git a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs index 7cd03930d8..367a4a64c8 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -685,7 +685,7 @@ pub struct ThreadIncrementElicitationParams { #[ts(export_to = "v2/")] pub struct ThreadIncrementElicitationResponse { /// Current out-of-band elicitation count after the increment. - pub count: u64, + pub count: i64, /// Whether timeout accounting is paused after applying the increment. pub paused: bool, } @@ -705,7 +705,7 @@ pub struct ThreadDecrementElicitationParams { #[ts(export_to = "v2/")] pub struct ThreadDecrementElicitationResponse { /// Current out-of-band elicitation count after the decrement. - pub count: u64, + pub count: i64, /// Whether timeout accounting remains paused after applying the decrement. pub paused: bool, } diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index c76e3c3c08..2143e3b577 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -142,6 +142,7 @@ impl McpConnectionManager { tool_plugin_provenance: ToolPluginProvenance, auth: Option<&CodexAuth>, elicitation_reviewer: Option, + elicitation_lifecycle: Option, elicitation_router: ElicitationRequestRouter, ) -> Self { let mut required_servers = mcp_servers @@ -157,6 +158,7 @@ impl McpConnectionManager { approval_policy.value(), initial_permission_profile, elicitation_reviewer, + elicitation_lifecycle, elicitation_router, ); let tool_plugin_provenance = Arc::new(tool_plugin_provenance); @@ -360,6 +362,7 @@ impl McpConnectionManager { approval_policy.value(), permission_profile.clone(), /*reviewer*/ None, + /*lifecycle*/ None, ElicitationRequestRouter::default(), ), startup_cancellation_token: CancellationToken::new(), diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index 1f61ab700e..41fc19a594 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -2,6 +2,7 @@ use super::*; use crate::codex_apps_cache::CodexAppsToolsCache; use crate::codex_apps_cache::CodexAppsToolsCacheContext; use crate::declared_openai_file_input_param_names; +use crate::elicitation::ElicitationLifecycle; use crate::elicitation::ElicitationRequestManager; use crate::elicitation::ElicitationRequestRouter; use crate::elicitation::elicitation_is_rejected_by_policy; @@ -323,6 +324,7 @@ async fn disabled_permissions_auto_accept_elicitation_with_empty_form_schema() { AskForApproval::Never, PermissionProfile::Disabled, /*reviewer*/ None, + /*lifecycle*/ None, ElicitationRequestRouter::default(), ); let (tx_event, _rx_event) = async_channel::bounded(1); @@ -359,6 +361,7 @@ async fn disabled_permissions_do_not_auto_accept_elicitation_with_requested_fiel AskForApproval::Never, PermissionProfile::Disabled, /*reviewer*/ None, + /*lifecycle*/ None, ElicitationRequestRouter::default(), ); let (tx_event, _rx_event) = async_channel::bounded(1); @@ -395,17 +398,35 @@ async fn disabled_permissions_do_not_auto_accept_elicitation_with_requested_fiel #[tokio::test] async fn shared_elicitation_router_targets_the_exact_pending_request() { + struct Registration(Arc); + + impl Drop for Registration { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } + } + let router = ElicitationRequestRouter::default(); + let outstanding = Arc::new(AtomicUsize::new(0)); + let lifecycle = ElicitationLifecycle::new({ + let outstanding = outstanding.clone(); + move || { + outstanding.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Registration(outstanding.clone()) + } + }); let manager_a = ElicitationRequestManager::new( AskForApproval::OnRequest, PermissionProfile::default(), /*reviewer*/ None, + Some(lifecycle.clone()), router.clone(), ); let manager_b = ElicitationRequestManager::new( AskForApproval::OnRequest, PermissionProfile::default(), /*reviewer*/ None, + Some(lifecycle), router, ); let (tx_event, rx_event) = async_channel::bounded(2); @@ -435,6 +456,7 @@ async fn shared_elicitation_router_targets_the_exact_pending_request() { else { panic!("expected elicitation request"); }; + assert_eq!(outstanding.load(std::sync::atomic::Ordering::SeqCst), 2); let ( codex_protocol::mcp::RequestId::String(request_a_id), codex_protocol::mcp::RequestId::String(request_b_id), @@ -485,6 +507,7 @@ async fn shared_elicitation_router_targets_the_exact_pending_request() { .expect("request B response"), response_b ); + assert_eq!(outstanding.load(std::sync::atomic::Ordering::SeqCst), 0); } #[test] @@ -1539,6 +1562,7 @@ async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() { ToolPluginProvenance::default(), /*auth*/ None, /*elicitation_reviewer*/ None, + /*elicitation_lifecycle*/ None, ElicitationRequestRouter::default(), ) .await; diff --git a/codex-rs/codex-mcp/src/elicitation.rs b/codex-rs/codex-mcp/src/elicitation.rs index e4fcf49d22..b6bb7fa791 100644 --- a/codex-rs/codex-mcp/src/elicitation.rs +++ b/codex-rs/codex-mcp/src/elicitation.rs @@ -52,6 +52,33 @@ pub trait ElicitationReviewer: Send + Sync { pub type ElicitationReviewerHandle = Arc; +/// Holds an owner-provided registration while an MCP elicitation is waiting for a response. +#[derive(Clone)] +pub struct ElicitationLifecycle { + register: Arc Box + Send + Sync>, +} + +impl ElicitationLifecycle { + pub fn new(register: impl Fn() -> T + Send + Sync + 'static) -> Self + where + T: Send + Sync + 'static, + { + Self { + register: Arc::new(move || Box::new(register())), + } + } + + fn start(&self) -> ActiveElicitation { + ActiveElicitation { + _registration: (self.register)(), + } + } +} + +struct ActiveElicitation { + _registration: Box, +} + /// Routes model-visible elicitation response tokens to their exact pending responders. /// /// One router is shared by every MCP runtime created for a thread. The public response token is @@ -86,6 +113,7 @@ pub(crate) struct ElicitationRequestManager { pub(crate) permission_profile: Arc>, auto_deny: Arc>, reviewer: Option, + lifecycle: Option, } impl ElicitationRequestManager { @@ -93,6 +121,7 @@ impl ElicitationRequestManager { approval_policy: AskForApproval, permission_profile: PermissionProfile, reviewer: Option, + lifecycle: Option, router: ElicitationRequestRouter, ) -> Self { Self { @@ -101,6 +130,7 @@ impl ElicitationRequestManager { permission_profile: Arc::new(StdMutex::new(permission_profile)), auto_deny: Arc::new(StdMutex::new(false)), reviewer, + lifecycle, } } @@ -140,6 +170,7 @@ impl ElicitationRequestManager { let permission_profile = self.permission_profile.clone(); let auto_deny = self.auto_deny.clone(); let reviewer = self.reviewer.clone(); + let lifecycle = self.lifecycle.clone(); Box::new(move |id, elicitation| { let router = router.clone(); let tx_event = tx_event.clone(); @@ -148,6 +179,7 @@ impl ElicitationRequestManager { let permission_profile = permission_profile.clone(); let auto_deny = auto_deny.clone(); let reviewer = reviewer.clone(); + let lifecycle = lifecycle.clone(); async move { let auto_deny = auto_deny .lock() @@ -249,6 +281,7 @@ impl ElicitationRequestManager { }, }; let (tx, rx) = oneshot::channel(); + let _active_elicitation = lifecycle.as_ref().map(ElicitationLifecycle::start); { let mut lock = router.requests.lock().await; lock.insert((server_name.clone(), routed_request_id), tx); diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index eda7ac2399..77128d7970 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -1,5 +1,6 @@ pub use connection_manager::McpConnectionManager; pub use connection_manager::tool_is_model_visible; +pub use elicitation::ElicitationLifecycle; pub use elicitation::ElicitationRequestRouter; pub use elicitation::ElicitationReviewRequest; pub use elicitation::ElicitationReviewer; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index ffb797f26e..87ea25dd9f 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -339,6 +339,7 @@ pub async fn read_mcp_resource( tool_plugin_provenance(config), auth, /*elicitation_reviewer*/ None, + /*elicitation_lifecycle*/ None, crate::elicitation::ElicitationRequestRouter::default(), ) .await; @@ -416,6 +417,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail( tool_plugin_provenance, auth, /*elicitation_reviewer*/ None, + /*elicitation_lifecycle*/ None, crate::elicitation::ElicitationRequestRouter::default(), ) .await; diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 4a562092f1..c80268e2f9 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -1,5 +1,6 @@ use crate::agent::AgentStatus; use crate::config::ConstraintResult; +use crate::elicitation::ElicitationRegistration; use crate::session::Codex; use crate::session::SessionSettingsUpdate; use crate::session::SteerInputError; @@ -162,7 +163,13 @@ pub struct CodexThread { pub(crate) session_source: SessionSource, session_configured: SessionConfiguredEvent, rollout_path: Option, - out_of_band_elicitation_count: Mutex, + out_of_band_elicitations: Mutex, +} + +#[derive(Default)] +struct OutOfBandElicitations { + count: i64, + registration: Option, } #[derive(Debug, Eq, PartialEq)] @@ -187,7 +194,7 @@ impl CodexThread { session_source, session_configured, rollout_path, - out_of_band_elicitation_count: Mutex::new(0), + out_of_band_elicitations: Mutex::new(OutOfBandElicitations::default()), } } @@ -655,38 +662,30 @@ impl CodexThread { self.codex.enabled(feature) } - pub async fn increment_out_of_band_elicitation_count(&self) -> CodexResult { - let mut guard = self.out_of_band_elicitation_count.lock().await; - let was_zero = *guard == 0; - *guard = guard.checked_add(1).ok_or_else(|| { + pub async fn increment_out_of_band_elicitation_count(&self) -> CodexResult { + let mut elicitations = self.out_of_band_elicitations.lock().await; + let incremented = elicitations.count.checked_add(1).ok_or_else(|| { CodexErr::Fatal("out-of-band elicitation count overflowed".to_string()) })?; - - if was_zero { - self.codex - .session - .set_out_of_band_elicitation_pause_state(/*paused*/ true); + if elicitations.count == 0 { + elicitations.registration = Some(self.codex.session.services.elicitations.register()); } - - Ok(*guard) + elicitations.count = incremented; + Ok(incremented) } - pub async fn decrement_out_of_band_elicitation_count(&self) -> CodexResult { - let mut guard = self.out_of_band_elicitation_count.lock().await; - if *guard == 0 { + pub async fn decrement_out_of_band_elicitation_count(&self) -> CodexResult { + let mut elicitations = self.out_of_band_elicitations.lock().await; + if elicitations.count == 0 { return Err(CodexErr::InvalidRequest( "out-of-band elicitation count is already zero".to_string(), )); } - *guard -= 1; - let now_zero = *guard == 0; - if now_zero { - self.codex - .session - .set_out_of_band_elicitation_pause_state(/*paused*/ false); + elicitations.count -= 1; + if elicitations.count == 0 { + elicitations.registration = None; } - - Ok(*guard) + Ok(elicitations.count) } } diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index b45cc841a1..805d56b648 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -283,6 +283,7 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager( ToolPluginProvenance::default(), auth.as_ref(), /*elicitation_reviewer*/ None, + /*elicitation_lifecycle*/ None, codex_mcp::ElicitationRequestRouter::default(), ) .await; diff --git a/codex-rs/core/src/elicitation.rs b/codex-rs/core/src/elicitation.rs new file mode 100644 index 0000000000..b29207af46 --- /dev/null +++ b/codex-rs/core/src/elicitation.rs @@ -0,0 +1,100 @@ +use std::sync::Arc; +use std::sync::Mutex; + +use tokio::sync::watch; + +/// Coordinates user elicitations that pause tool-result delivery for a session. +/// +/// Registrations are counted so concurrent elicitations keep the session paused until all of them +/// finish. Consumers can subscribe to pause timeout progress or wait before returning an already +/// captured result. +#[derive(Clone)] +pub(crate) struct ElicitationService { + inner: Arc, +} + +struct Inner { + state: Mutex, + paused: watch::Sender, +} + +#[derive(Default)] +struct State { + outstanding: i64, +} + +pub(crate) struct ElicitationRegistration { + service: ElicitationService, +} + +impl ElicitationService { + pub(crate) fn new() -> Self { + let (paused, _paused_rx) = watch::channel(false); + Self { + inner: Arc::new(Inner { + state: Mutex::new(State::default()), + paused, + }), + } + } + + pub(crate) fn register(&self) -> ElicitationRegistration { + self.increment(); + ElicitationRegistration { + service: self.clone(), + } + } + + fn increment(&self) { + let mut state = self + .inner + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let was_clear = state.outstanding == 0; + assert_ne!( + state.outstanding, + i64::MAX, + "outstanding elicitation count overflowed" + ); + state.outstanding += 1; + if was_clear { + self.inner.paused.send_replace(true); + } + } + + pub(crate) fn subscribe(&self) -> watch::Receiver { + self.inner.paused.subscribe() + } + + pub(crate) async fn wait_until_clear(&self) { + let mut paused = self.subscribe(); + let _ = paused.wait_for(|paused| !*paused).await; + } + + fn decrement(&self) { + let mut state = self + .inner + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + assert!( + state.outstanding > 0, + "elicitation registration count underflowed" + ); + state.outstanding -= 1; + if state.outstanding == 0 { + self.inner.paused.send_replace(false); + } + } +} + +impl Drop for ElicitationRegistration { + fn drop(&mut self) { + self.service.decrement(); + } +} + +#[cfg(test)] +#[path = "elicitation_tests.rs"] +mod tests; diff --git a/codex-rs/core/src/elicitation_tests.rs b/codex-rs/core/src/elicitation_tests.rs new file mode 100644 index 0000000000..eefe1f5394 --- /dev/null +++ b/codex-rs/core/src/elicitation_tests.rs @@ -0,0 +1,19 @@ +use super::*; + +#[tokio::test] +async fn wait_until_clear_waits_for_every_registration() { + let service = ElicitationService::new(); + let first = service.register(); + let second = service.register(); + let waiting = tokio::spawn({ + let service = service.clone(); + async move { service.wait_until_clear().await } + }); + + drop(first); + tokio::task::yield_now().await; + assert!(!waiting.is_finished()); + + drop(second); + waiting.await.expect("elicitation waiter should complete"); +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index df8753a386..91ccbd6e63 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -40,6 +40,7 @@ pub mod connectors; pub mod context; mod context_manager; mod current_time; +mod elicitation; mod environment_selection; pub mod exec; pub mod exec_env; diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 6b642b1cd0..f68d32ff4e 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1439,6 +1439,7 @@ async fn host_owned_codex_apps_manager( codex_mcp::ToolPluginProvenance::default(), auth.as_ref(), /*elicitation_reviewer*/ None, + /*elicitation_lifecycle*/ None, codex_mcp::ElicitationRequestRouter::default(), ) .await; diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index 4cfb0a36de..3f5e92eca7 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -195,6 +195,11 @@ impl Session { Arc::new(GuardianMcpElicitationReviewer::new(self)) } + pub(crate) fn mcp_elicitation_lifecycle(&self) -> codex_mcp::ElicitationLifecycle { + let elicitations = self.services.elicitations.clone(); + codex_mcp::ElicitationLifecycle::new(move || elicitations.register()) + } + #[expect( clippy::await_holding_invalid_type, reason = "active turn checks and turn state updates must remain atomic" @@ -222,6 +227,7 @@ impl Session { }; } + let _elicitation = self.services.elicitations.register(); let (tx_response, rx_response) = oneshot::channel(); let prev_entry = { let mut active = self.active_turn.lock().await; @@ -377,6 +383,7 @@ impl Session { tool_plugin_provenance, auth.as_ref(), elicitation_reviewer, + Some(self.mcp_elicitation_lifecycle()), current_runtime.manager().elicitation_router(), ) .await; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 560dcf5985..ec3fa12f39 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -1141,12 +1141,8 @@ impl Session { state.session_configuration.codex_home().clone() } - pub(crate) fn subscribe_out_of_band_elicitation_pause_state(&self) -> watch::Receiver { - self.out_of_band_elicitation_paused.subscribe() - } - - pub(crate) fn set_out_of_band_elicitation_pause_state(&self, paused: bool) { - self.out_of_band_elicitation_paused.send_replace(paused); + pub(crate) fn subscribe_elicitation_pause_state(&self) -> watch::Receiver { + self.services.elicitations.subscribe() } pub(crate) fn get_tx_event(&self) -> Sender { diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 48a9ee447e..2261eaa495 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -30,7 +30,6 @@ pub(crate) struct Session { pub(crate) installation_id: String, pub(super) tx_event: Sender, pub(super) agent_status: watch::Sender, - pub(super) out_of_band_elicitation_paused: watch::Sender, pub(super) state: Mutex, /// Serializes rebuild/apply cycles for the running proxy; each cycle /// rebuilds from the current SessionState while holding this lock. @@ -1057,6 +1056,7 @@ impl Session { unified_exec_manager: UnifiedExecProcessManager::new( config.background_terminal_max_timeout, ), + elicitations: crate::elicitation::ElicitationService::new(), shell_zsh_path: config.zsh_path.clone(), main_execve_wrapper_exe: config.main_execve_wrapper_exe.clone(), analytics_events_client, @@ -1125,15 +1125,11 @@ impl Session { tool_search_handler_cache: Default::default(), turn_environments: Arc::clone(&turn_environments), }; - let (out_of_band_elicitation_paused, _out_of_band_elicitation_paused_rx) = - watch::channel(false); - let sess = Arc::new(Session { thread_id, installation_id, tx_event: tx_event.clone(), agent_status, - out_of_band_elicitation_paused, state: Mutex::new(state), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), @@ -1219,6 +1215,7 @@ impl Session { tool_plugin_provenance, auth, Some(sess.mcp_elicitation_reviewer()), + Some(sess.mcp_elicitation_lifecycle()), codex_mcp::ElicitationRequestRouter::default(), ) .instrument(info_span!( diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 9ae29a0917..582a58f2ab 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -5384,6 +5384,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { unified_exec_manager: UnifiedExecProcessManager::new( config.background_terminal_max_timeout, ), + elicitations: crate::elicitation::ElicitationService::new(), shell_zsh_path: None, main_execve_wrapper_exe: config.main_execve_wrapper_exe.clone(), analytics_events_client: AnalyticsEventsClient::new( @@ -5494,7 +5495,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { installation_id: "11111111-1111-4111-8111-111111111111".to_string(), tx_event, agent_status: agent_status_tx, - out_of_band_elicitation_paused: watch::channel(false).0, state: Mutex::new(state), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), @@ -7510,6 +7510,7 @@ where unified_exec_manager: UnifiedExecProcessManager::new( config.background_terminal_max_timeout, ), + elicitations: crate::elicitation::ElicitationService::new(), shell_zsh_path: None, main_execve_wrapper_exe: config.main_execve_wrapper_exe.clone(), analytics_events_client: AnalyticsEventsClient::new( @@ -7620,7 +7621,6 @@ where installation_id: "11111111-1111-4111-8111-111111111111".to_string(), tx_event, agent_status: agent_status_tx, - out_of_band_elicitation_paused: watch::channel(false).0, state: Mutex::new(state), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index c4b67a629b..43f411e31b 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -10,6 +10,7 @@ use crate::client::ModelClient; use crate::config::NetworkProxyAuditMetadata; use crate::config::StartedNetworkProxy; use crate::current_time::TimeProvider; +use crate::elicitation::ElicitationService; use crate::environment_selection::ThreadEnvironments; use crate::exec_policy::ExecPolicyManager; use crate::guardian::GuardianRejection; @@ -55,6 +56,7 @@ pub(crate) struct SessionServices { pub(crate) mcp_projection_lock: Mutex<()>, pub(crate) mcp_startup_cancellation_token: Mutex, pub(crate) unified_exec_manager: UnifiedExecProcessManager, + pub(crate) elicitations: ElicitationService, #[cfg_attr(not(unix), allow(dead_code))] pub(crate) shell_zsh_path: Option, #[cfg_attr(not(unix), allow(dead_code))] diff --git a/codex-rs/core/src/tools/code_mode/execute_handler.rs b/codex-rs/core/src/tools/code_mode/execute_handler.rs index 2e46c1bd6b..8374ae1ca4 100644 --- a/codex-rs/core/src/tools/code_mode/execute_handler.rs +++ b/codex-rs/core/src/tools/code_mode/execute_handler.rs @@ -85,6 +85,7 @@ impl CodeModeExecuteHandler { .code_mode_service .finish_cell_dispatch(&cell_id); } + exec.session.services.elicitations.wait_until_clear().await; handle_runtime_response(&exec, response, args.max_output_tokens, started_at) .await .map_err(FunctionCallError::RespondToModel) diff --git a/codex-rs/core/src/tools/code_mode/wait_handler.rs b/codex-rs/core/src/tools/code_mode/wait_handler.rs index 953391a573..c3c867f3ef 100644 --- a/codex-rs/core/src/tools/code_mode/wait_handler.rs +++ b/codex-rs/core/src/tools/code_mode/wait_handler.rs @@ -120,6 +120,7 @@ impl CodeModeWaitHandler { .code_mode_service .finish_cell_dispatch(runtime_cell_id); } + exec.session.services.elicitations.wait_until_clear().await; handle_runtime_response(&exec, wait_response.into(), args.max_tokens, started_at) .await .map(boxed_tool_output) diff --git a/codex-rs/core/src/unified_exec/mod_tests.rs b/codex-rs/core/src/unified_exec/mod_tests.rs index 54ee788e3b..81403c8e52 100644 --- a/codex-rs/core/src/unified_exec/mod_tests.rs +++ b/codex-rs/core/src/unified_exec/mod_tests.rs @@ -160,7 +160,7 @@ async fn exec_command_with_tty( &output_closed, &output_closed_notify, &cancellation_token, - Some(session.subscribe_out_of_band_elicitation_pause_state()), + Some(session.subscribe_elicitation_pause_state()), deadline, ) .await; @@ -515,12 +515,11 @@ async fn unified_exec_pause_blocks_yield_timeout() -> anyhow::Result<()> { skip_if_sandbox!(Ok(())); let (session, turn) = test_session_and_turn().await; - session.set_out_of_band_elicitation_pause_state(/*paused*/ true); + let elicitation = session.services.elicitations.register(); - let paused_session = Arc::clone(&session); tokio::spawn(async move { tokio::time::sleep(Duration::from_secs(2)).await; - paused_session.set_out_of_band_elicitation_pause_state(/*paused*/ false); + drop(elicitation); }); let started = tokio::time::Instant::now(); diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index ef22918cd2..a895708f79 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -493,11 +493,7 @@ impl UnifiedExecProcessManager { &output_closed, &output_closed_notify, &cancellation_token, - Some( - context - .session - .subscribe_out_of_band_elicitation_pause_state(), - ), + Some(context.session.subscribe_elicitation_pause_state()), deadline, ) .await; @@ -839,7 +835,7 @@ impl UnifiedExecProcessManager { let pause_state = entry .session .upgrade() - .map(|session| session.subscribe_out_of_band_elicitation_pause_state()); + .map(|session| session.subscribe_elicitation_pause_state()); let session = entry.session.upgrade(); Ok(PreparedProcessHandles { diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 26c041d8f7..9293b506ef 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -521,6 +521,76 @@ text(JSON.stringify(await tools.exec_command({ cmd: "printf code_mode_exec_marke Ok(()) } +#[tokio::test] +async fn code_mode_exec_holds_captured_result_during_elicitation() -> Result<()> { + let server = responses::start_mock_server().await; + let mut builder = test_codex() + .with_model("test-gpt-5.1-codex") + .with_config(|config| { + let _ = config.features.enable(Feature::CodeMode); + }); + let test = builder.build(&server).await?; + + let first_mock = responses::mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_custom_tool_call("call-1", "exec", "text('captured');"), + ev_completed("resp-1"), + ]), + ) + .await; + let second_mock = responses::mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ) + .await; + + assert_eq!( + test.codex.increment_out_of_band_elicitation_count().await?, + 1 + ); + assert_eq!( + test.codex.increment_out_of_band_elicitation_count().await?, + 2 + ); + let release_elicitation = async { + tokio::time::timeout(Duration::from_secs(5), async { + while first_mock.requests().is_empty() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("initial response request should arrive"); + tokio::time::sleep(Duration::from_millis(250)).await; + assert!( + second_mock.requests().is_empty(), + "captured exec result should not return during an elicitation" + ); + assert_eq!( + test.codex.decrement_out_of_band_elicitation_count().await?, + 1 + ); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + second_mock.requests().is_empty(), + "captured exec result should wait for every elicitation" + ); + assert_eq!( + test.codex.decrement_out_of_band_elicitation_count().await?, + 0 + ); + Ok::<(), anyhow::Error>(()) + }; + + tokio::try_join!(test.submit_turn("run code mode"), release_elicitation)?; + second_mock.single_request(); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn code_mode_only_restricts_prompt_tools() -> Result<()> { skip_if_no_network!(Ok(())); From a86d525e4d28b299d2522cbef844675203e86084 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Mon, 6 Jul 2026 11:44:08 -0700 Subject: [PATCH 15/17] core: trace executor skill discovery (#30318) ## Why Make it easier to measure the performance of different parts of skill loading. ## What - Add spans for step-context capture, world-state construction, executor catalog snapshot/root loading, and environment skill loading. - Record the discovered environment skill count. - Trace outbound exec-server requests with client kind and RPC method fields. - Update trace propagation tests to assert that requests keep the parent trace id while creating their own child span. --- .../core-skills/src/loader/environment.rs | 7 +++++++ codex-rs/core/src/session/mod.rs | 1 + codex-rs/core/src/session/world_state.rs | 1 + codex-rs/exec-server/src/client.rs | 11 +++++++++- codex-rs/exec-server/src/rpc.rs | 21 ++++++++++++++++++- codex-rs/ext/skills/src/state.rs | 7 +++++++ 6 files changed, 46 insertions(+), 2 deletions(-) diff --git a/codex-rs/core-skills/src/loader/environment.rs b/codex-rs/core-skills/src/loader/environment.rs index 049b500585..3d50bafe1f 100644 --- a/codex-rs/core-skills/src/loader/environment.rs +++ b/codex-rs/core-skills/src/loader/environment.rs @@ -143,6 +143,12 @@ pub struct EnvironmentSkillLoadOutcome { } /// Discovers skills without converting environment-owned paths to host paths. +#[tracing::instrument( + name = "skills.environment.load", + level = "info", + skip_all, + fields(skill_count = tracing::field::Empty) +)] pub async fn load_environment_skills_from_root( file_system: &dyn ExecutorFileSystem, root: &PathUri, @@ -235,6 +241,7 @@ pub async fn load_environment_skills_from_root( warnings: vec![format!("failed to walk skills root {root}: {error:#}")], }, }; + tracing::Span::current().record("skill_count", discovery.skills.len()); outcome.warnings.extend(discovery.warnings); if discovery.skills.is_empty() { return outcome; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index ec3fa12f39..d4cfd9e05d 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2829,6 +2829,7 @@ impl Session { /// This may refresh filesystem-derived state. Normal turns should call it only from /// `run_turn` and pass the result down; standalone request or history boundaries may capture /// their own step. + #[tracing::instrument(name = "step_context.capture", level = "info", skip_all)] pub(crate) async fn capture_step_context( self: &Arc, turn_context: Arc, diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs index a78116d457..89684e9e50 100644 --- a/codex-rs/core/src/session/world_state.rs +++ b/codex-rs/core/src/session/world_state.rs @@ -7,6 +7,7 @@ use crate::context::world_state::WorldState; use codex_extension_api::WorldStateContributionInput; impl Session { + #[tracing::instrument(name = "world_state.build", level = "info", skip_all)] pub(crate) async fn build_world_state_for_step( &self, step_context: &StepContext, diff --git a/codex-rs/exec-server/src/client.rs b/codex-rs/exec-server/src/client.rs index 82412a58e6..5590fd3b5e 100644 --- a/codex-rs/exec-server/src/client.rs +++ b/codex-rs/exec-server/src/client.rs @@ -1394,7 +1394,16 @@ mod tests { assert_eq!(session.process_id(), &process_id); let trace = server.await.expect("server task").expect("trace context"); - assert_eq!(trace, expected_trace); + let expected_traceparent = expected_trace + .traceparent + .as_deref() + .expect("parent traceparent"); + let traceparent = trace.traceparent.as_deref().expect("request traceparent"); + let expected_parts = expected_traceparent.split('-').collect::>(); + let parts = traceparent.split('-').collect::>(); + assert_eq!(parts[1], expected_parts[1]); + assert_ne!(parts[2], expected_parts[2]); + assert_eq!(trace.tracestate, expected_trace.tracestate); } async fn accept_websocket(listener: &TcpListener) -> WebSocketStream { diff --git a/codex-rs/exec-server/src/rpc.rs b/codex-rs/exec-server/src/rpc.rs index 46a0bd14e8..e762fe8b66 100644 --- a/codex-rs/exec-server/src/rpc.rs +++ b/codex-rs/exec-server/src/rpc.rs @@ -342,6 +342,16 @@ impl RpcClient { drain_pending(&self.pending).await; } + #[tracing::instrument( + name = "codex.exec_server.request", + level = "info", + skip_all, + fields( + otel.kind = "client", + otel.name = method, + method, + ) + )] pub(crate) async fn call(&self, method: &str, params: &P) -> Result where P: Serialize, @@ -803,6 +813,15 @@ mod tests { .expect("RPC response"); assert_eq!(response, serde_json::json!({})); let trace = server.await.expect("server task").expect("trace context"); - assert_eq!(trace, expected_trace); + let expected_traceparent = expected_trace + .traceparent + .as_deref() + .expect("parent traceparent"); + let traceparent = trace.traceparent.as_deref().expect("request traceparent"); + let expected_parts = expected_traceparent.split('-').collect::>(); + let parts = traceparent.split('-').collect::>(); + assert_eq!(parts[1], expected_parts[1]); + assert_ne!(parts[2], expected_parts[2]); + assert_eq!(trace.tracestate, expected_trace.tracestate); } } diff --git a/codex-rs/ext/skills/src/state.rs b/codex-rs/ext/skills/src/state.rs index 2f1a84c46b..2094f34496 100644 --- a/codex-rs/ext/skills/src/state.rs +++ b/codex-rs/ext/skills/src/state.rs @@ -66,6 +66,12 @@ impl SkillsThreadState { /// Environment availability only controls whether the root is projected into the current /// step; it never invalidates the cache. There is intentionally no filesystem watcher or /// content-based invalidation because selected environment roots are treated as stable. + #[tracing::instrument( + name = "skills.executor.catalog_snapshot", + level = "info", + skip_all, + fields(root_count = query.executor_roots.len()) + )] pub(crate) async fn executor_catalog_snapshot( &self, providers: &SkillProviders, @@ -157,6 +163,7 @@ impl SkillsThreadState { next_cache } + #[tracing::instrument(name = "skills.executor.catalog_root", level = "info", skip_all)] async fn executor_root_catalog( &self, providers: &SkillProviders, From 2e20d2ef4445145f2c156021b864d59e0a04cb64 Mon Sep 17 00:00:00 2001 From: canvrno-oai Date: Mon, 6 Jul 2026 12:17:16 -0700 Subject: [PATCH 16/17] Revert "Conditional codex_home dotenv" (#31276) ## Summary - Revert the conditional `CODEX_HOME` dotenv behavior introduced in #29959. - Restore the previous startup and configuration behavior --- codex-rs/Cargo.lock | 3 - codex-rs/arg0/Cargo.toml | 5 +- .../conditional_dotenv_tests.rs | 281 ----------- codex-rs/arg0/src/conditional_dotenv/mod.rs | 465 ------------------ codex-rs/arg0/src/lib.rs | 24 +- 5 files changed, 7 insertions(+), 771 deletions(-) delete mode 100644 codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs delete mode 100644 codex-rs/arg0/src/conditional_dotenv/mod.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index e590d17497..6ac51d403f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2227,11 +2227,8 @@ dependencies = [ "codex-windows-sandbox", "dotenvy", "pretty_assertions", - "serde", - "serde_json", "tempfile", "tokio", - "url", ] [[package]] diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index 400e3fbb9c..bb45db4552 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -23,11 +23,8 @@ codex-shell-escalation = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-home-dir = { workspace = true } dotenvy = { workspace = true } -serde = { workspace = true, features = ["derive"] } -serde_json = { workspace = true } tempfile = { workspace = true } -tokio = { workspace = true, features = ["net", "rt-multi-thread", "time"] } -url = { workspace = true } +tokio = { workspace = true, features = ["rt-multi-thread"] } [target.'cfg(windows)'.dependencies] codex-windows-sandbox = { workspace = true } diff --git a/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs b/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs deleted file mode 100644 index f4b5dfb1e6..0000000000 --- a/codex-rs/arg0/src/conditional_dotenv/conditional_dotenv_tests.rs +++ /dev/null @@ -1,281 +0,0 @@ -use super::*; -use pretty_assertions::assert_eq; -use std::cell::Cell; -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::fs; -use std::time::Duration; - -#[derive(Debug, Default, PartialEq, Eq)] -struct TestEnvironment(BTreeMap); - -impl StartupEnvironment for TestEnvironment { - fn set(&mut self, key: &str, value: &str) { - self.0.insert(key.to_string(), value.to_string()); - } - - fn remove(&mut self, key: &str) { - self.0.remove(key); - } -} - -fn write_overlay(codex_home: &Path, name: &str, contents: &str) -> std::io::Result<()> { - fs::write(codex_home.join(name), contents) -} - -fn test_environment(values: [(&str, &str); N]) -> TestEnvironment { - TestEnvironment(BTreeMap::from( - values.map(|(key, value)| (key.to_string(), value.to_string())), - )) -} - -#[test] -fn proxy_overlays_set_or_unset_environment_for_network() -> anyhow::Result<()> { - let codex_home = tempfile::tempdir()?; - write_overlay( - codex_home.path(), - ".env.10-proxy-on", - r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY","timeout_ms":500} -HTTPS_PROXY=http://user:password@proxy.example.com:8080 -HTTP_PROXY=http://proxy.example.com:8080 -ALL_PROXY=http://proxy.example.com:8080 -NO_PROXY=localhost,127.0.0.1,.example.com -"#, - )?; - write_overlay( - codex_home.path(), - ".env.20-proxy-off", - r#"# codex-env-if: {"not":{"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":500}} -# codex-env-unset: ["HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY"] -"#, - )?; - - let on_network_calls = Cell::new(0); - let on_network_connector = |host: &str, port: u16, timeout: Duration| { - on_network_calls.set(on_network_calls.get() + 1); - assert_eq!(host, "proxy.example.com"); - assert_eq!(port, 8080); - assert_eq!(timeout, Duration::from_millis(500)); - true - }; - let mut on_network_environment = test_environment([ - ("HTTPS_PROXY", "http://stale.example.com:8080"), - ("UNRELATED", "preserved"), - ]); - - let warnings = load_conditional_dotenv_overlays( - codex_home.path(), - &mut on_network_environment, - &on_network_connector, - ); - - assert_eq!(on_network_calls.get(), 2); - assert_eq!(warnings, Vec::::new()); - assert_eq!( - on_network_environment, - test_environment([ - ("ALL_PROXY", "http://proxy.example.com:8080"), - ("HTTPS_PROXY", "http://user:password@proxy.example.com:8080"), - ("HTTP_PROXY", "http://proxy.example.com:8080"), - ("NO_PROXY", "localhost,127.0.0.1,.example.com"), - ("UNRELATED", "preserved"), - ]) - ); - - let off_network_calls = Cell::new(0); - let off_network_connector = |host: &str, port: u16, timeout: Duration| { - off_network_calls.set(off_network_calls.get() + 1); - assert_eq!(host, "proxy.example.com"); - assert_eq!(port, 8080); - assert_eq!(timeout, Duration::from_millis(500)); - false - }; - let mut off_network_environment = test_environment([ - ("ALL_PROXY", "http://inherited.example.com:8080"), - ("HTTPS_PROXY", "http://inherited.example.com:8080"), - ("HTTP_PROXY", "http://inherited.example.com:8080"), - ("NO_PROXY", "localhost"), - ("UNRELATED", "preserved"), - ]); - - let warnings = load_conditional_dotenv_overlays( - codex_home.path(), - &mut off_network_environment, - &off_network_connector, - ); - - assert_eq!(off_network_calls.get(), 2); - assert_eq!(warnings, Vec::::new()); - assert_eq!( - off_network_environment, - test_environment([("UNRELATED", "preserved")]) - ); - Ok(()) -} - -#[test] -fn overlay_filters_reserved_names_for_set_and_unset() -> anyhow::Result<()> { - let codex_home = tempfile::tempdir()?; - write_overlay( - codex_home.path(), - ".env.proxy", - r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} -# codex-env-unset: ["ALL_PROXY","codex_internal"] -HTTP_PROXY=http://proxy.example.com:8080 -codex_internal=changed -"#, - )?; - let mut environment = test_environment([ - ("ALL_PROXY", "http://old.example.com:8080"), - ("codex_internal", "preserved"), - ]); - - let warnings = - load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &|_, _, _| true); - - assert_eq!(warnings, Vec::::new()); - assert_eq!( - environment, - test_environment([ - ("HTTP_PROXY", "http://proxy.example.com:8080"), - ("codex_internal", "preserved"), - ]) - ); - Ok(()) -} - -#[test] -fn invalid_timeout_fails_closed_without_blocking_valid_overlays() -> anyhow::Result<()> { - let codex_home = tempfile::tempdir()?; - write_overlay(codex_home.path(), ".env.example", "SHOULD_NOT_LOAD=1\n")?; - write_overlay( - codex_home.path(), - ".env.10-timeout", - r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":5001} -SHOULD_NOT_LOAD=2 -"#, - )?; - write_overlay( - codex_home.path(), - ".env.20-maximum-timeout", - r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080,"timeout_ms":5000} -MAXIMUM_TIMEOUT=loaded -"#, - )?; - write_overlay( - codex_home.path(), - ".env.30-default-timeout", - r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} -DEFAULT_TIMEOUT=loaded -"#, - )?; - let observed_timeouts = RefCell::new(Vec::new()); - let connector = |_: &str, _: u16, timeout: Duration| { - observed_timeouts.borrow_mut().push(timeout); - true - }; - let mut environment = TestEnvironment::default(); - - let warnings = - load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &connector); - - assert_eq!(warnings.len(), 1); - assert!(warnings[0].contains(".env.10-timeout")); - assert_eq!( - observed_timeouts.into_inner(), - vec![Duration::from_millis(5000), Duration::from_millis(500)] - ); - assert_eq!( - environment, - test_environment([("DEFAULT_TIMEOUT", "loaded"), ("MAXIMUM_TIMEOUT", "loaded"),]) - ); - Ok(()) -} - -#[test] -fn invalid_from_sources_fail_closed_without_connecting() -> anyhow::Result<()> { - let codex_home = tempfile::tempdir()?; - write_overlay( - codex_home.path(), - ".env.10-missing-source", - r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY"} -SHOULD_NOT_LOAD=1 -"#, - )?; - write_overlay( - codex_home.path(), - ".env.20-invalid-source", - r#"# codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY"} -HTTPS_PROXY="not a url" -"#, - )?; - let connector_called = Cell::new(false); - let connector = |_: &str, _: u16, _: Duration| { - connector_called.set(true); - true - }; - let mut environment = TestEnvironment::default(); - - let warnings = - load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &connector); - - assert!(!connector_called.get()); - assert_eq!(warnings.len(), 2); - assert_eq!(environment, TestEnvironment::default()); - Ok(()) -} - -#[test] -fn directives_inside_multiline_values_are_not_scanned() -> anyhow::Result<()> { - let codex_home = tempfile::tempdir()?; - write_overlay( - codex_home.path(), - ".env.multiline", - r#"# codex-env-if: {"type":"tcp_connect","host":"proxy.example.com","port":8080} -# codex-env-unset: ["HTTP_PROXY"] -MESSAGE='before -# codex-env-unset: ["ALL_PROXY"] -# codex-env-if: {"not":{"type":"tcp_connect","host":"other.example.com","port":8080}} -after' -"#, - )?; - let mut environment = test_environment([ - ("ALL_PROXY", "http://proxy.example.com:8080"), - ("HTTP_PROXY", "http://proxy.example.com:8080"), - ]); - - let warnings = - load_conditional_dotenv_overlays(codex_home.path(), &mut environment, &|_, _, _| true); - - assert_eq!(warnings, Vec::::new()); - assert_eq!( - environment, - test_environment([ - ("ALL_PROXY", "http://proxy.example.com:8080"), - ( - "MESSAGE", - "before\n# codex-env-unset: [\"ALL_PROXY\"]\n# codex-env-if: {\"not\":{\"type\":\"tcp_connect\",\"host\":\"other.example.com\",\"port\":8080}}\nafter", - ), - ]) - ); - Ok(()) -} - -#[test] -fn endpoint_parser_supports_urls_bare_authorities_and_known_default_ports() { - assert_eq!( - [ - "http://user:password@proxy.example.com:8080", - "proxy.example.com:8080", - "https://proxy.example.com", - "http://[::1]:8080", - ] - .map(parse_endpoint), - [ - Some(("proxy.example.com".to_string(), 8080)), - Some(("proxy.example.com".to_string(), 8080)), - Some(("proxy.example.com".to_string(), 443)), - Some(("::1".to_string(), 8080)), - ] - ); -} diff --git a/codex-rs/arg0/src/conditional_dotenv/mod.rs b/codex-rs/arg0/src/conditional_dotenv/mod.rs deleted file mode 100644 index c3ed40179e..0000000000 --- a/codex-rs/arg0/src/conditional_dotenv/mod.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! Loads TCP-gated dotenv overlays from `CODEX_HOME` during single-threaded startup. -//! -//! Example `~/.codex/.env.corporate-proxy`: -//! -//! ```dotenv -//! # codex-env-if: {"type":"tcp_connect","from":"HTTPS_PROXY","timeout_ms":500} -//! HTTPS_PROXY=http://proxy.example.com:8080 -//! HTTP_PROXY=http://proxy.example.com:8080 -//! ALL_PROXY=http://proxy.example.com:8080 -//! NO_PROXY=localhost,127.0.0.1,.example.com -//! ``` -//! -//! A TCP condition can be inverted with `{"not":{"type":"tcp_connect",...}}`, which allows a -//! second overlay to unset proxy variables when the endpoint is unreachable. - -use crate::is_reserved_env_var; -use serde::Deserialize; -use std::ffi::OsString; -use std::net::ToSocketAddrs; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; -use std::process::Stdio; -use std::time::Duration; -use std::time::Instant; -use url::Url; - -pub(crate) const TCP_CONNECT_HELPER_ARG1: &str = "--codex-run-as-tcp-connect-probe"; - -const CONDITIONAL_DOTENV_PREFIX: &str = ".env."; -const CONDITION_DIRECTIVE_PREFIX: &str = "# codex-env-if:"; -const UNSET_DIRECTIVE_PREFIX: &str = "# codex-env-unset:"; -const DEFAULT_TCP_CONNECT_TIMEOUT_MS: u64 = 500; -const MAX_TCP_CONNECT_TIMEOUT_MS: u64 = 5_000; -const TCP_CONNECT_HELPER_POLL_INTERVAL: Duration = Duration::from_millis(10); -const IGNORED_CONDITIONAL_DOTENV_SUFFIXES: &[&str] = &[ - "bak", "back", "backup", "bkp", "old", "orig", "original", "save", "saved", "disable", - "disabled", "inactive", "off", "tmp", "temp", "swp", "swo", "example", "sample", "template", - "dist", -]; - -type TcpConnector<'a> = dyn Fn(&str, u16, Duration) -> bool + 'a; - -pub(crate) fn load(codex_home: &Path) { - let mut environment = ProcessEnvironment; - - for warning in - load_conditional_dotenv_overlays(codex_home, &mut environment, &system_tcp_connect) - { - eprintln!("WARNING: skipped conditional dotenv overlay: {warning}"); - } -} - -/// Runs an OS-resolved TCP probe in the child process used by [`system_tcp_connect`]. -/// -/// This exits before dotenv loading, so its resolver and connection tasks cannot race with the -/// parent's environment mutation. -pub(crate) fn run_tcp_connect_helper(mut args: impl Iterator) -> ! { - let host = args.next().and_then(|value| value.into_string().ok()); - let port = args - .next() - .and_then(|value| value.into_string().ok()) - .and_then(|value| value.parse::().ok()); - let timeout = args - .next() - .and_then(|value| value.into_string().ok()) - .and_then(|value| value.parse::().ok()) - .and_then(|timeout_ms| tcp_connect_timeout(Some(timeout_ms)).ok()); - let connected = match (host, port, timeout) { - (Some(host), Some(port), Some(timeout)) => direct_tcp_connect(&host, port, timeout), - _ => false, - }; - let exit_code = if connected { 0 } else { 1 }; - std::process::exit(exit_code); -} - -fn load_conditional_dotenv_overlays( - codex_home: &Path, - environment: &mut dyn StartupEnvironment, - tcp_connect: &TcpConnector<'_>, -) -> Vec { - let paths = match conditional_dotenv_paths(codex_home) { - Ok(paths) => paths, - Err(err) => { - return vec![format!( - "could not discover overlays in {}: {err}", - codex_home.display() - )]; - } - }; - let mut warnings = Vec::new(); - - for path in paths { - let overlay = match parse_conditional_dotenv(&path) { - Ok(Some(overlay)) => overlay, - Ok(None) => continue, - Err(err) => { - warnings.push(format!("{}: {err}", path.display())); - continue; - } - }; - match evaluate_condition(&overlay.condition, &overlay.entries, tcp_connect) { - Ok(true) => apply_overlay(overlay, environment), - Ok(false) => {} - Err(err) => warnings.push(format!("{}: {err}", path.display())), - } - } - - warnings -} - -fn conditional_dotenv_paths(codex_home: &Path) -> std::io::Result> { - let entries = match std::fs::read_dir(codex_home) { - Ok(entries) => entries, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(err) => return Err(err), - }; - let mut paths = Vec::new(); - - for entry in entries { - let entry = entry?; - let file_name = entry.file_name(); - let Some(file_name) = file_name.to_str() else { - continue; - }; - let is_ignored = file_name.ends_with('~') - || file_name.rsplit_once('.').is_some_and(|(_, suffix)| { - IGNORED_CONDITIONAL_DOTENV_SUFFIXES - .iter() - .any(|ignored| suffix.eq_ignore_ascii_case(ignored)) - }); - if file_name.starts_with(CONDITIONAL_DOTENV_PREFIX) - && file_name.len() > CONDITIONAL_DOTENV_PREFIX.len() - && !is_ignored - && entry.path().is_file() - { - paths.push(entry.path()); - } - } - - paths.sort(); - Ok(paths) -} - -fn parse_conditional_dotenv(path: &Path) -> Result, String> { - let contents = - std::fs::read_to_string(path).map_err(|err| format!("could not read file: {err}"))?; - let contents = contents.strip_prefix('\u{feff}').unwrap_or(&contents); - let mut lines = contents - .lines() - .map(|line| line.trim_start_matches('\u{feff}').trim()); - let Some(first_line) = lines.find(|line| !line.is_empty()) else { - return Ok(None); - }; - let Some(condition_json) = first_line.strip_prefix(CONDITION_DIRECTIVE_PREFIX) else { - return Ok(None); - }; - let condition_json = condition_json.trim(); - if condition_json.is_empty() { - return Err("condition directive is empty".to_string()); - } - let condition = serde_json::from_str(condition_json) - .map_err(|err| format!("condition directive is invalid: {err}"))?; - - let mut unset = None; - for line in lines { - if !line.is_empty() && !line.starts_with('#') { - break; - } - if line.starts_with(CONDITION_DIRECTIVE_PREFIX) { - return Err("exactly one condition directive is required".to_string()); - } - if let Some(unset_json) = line.strip_prefix(UNSET_DIRECTIVE_PREFIX) { - if unset.is_some() { - return Err("multiple unset directives are not supported".to_string()); - } - let keys: Vec = serde_json::from_str(unset_json.trim()) - .map_err(|err| format!("unset directive is invalid: {err}"))?; - if let Some(key) = keys.iter().find(|key| !is_valid_env_var_name(key)) { - return Err(format!( - "unset directive contains invalid environment variable name `{key}`" - )); - } - unset = Some(keys); - } - } - - let entries = dotenvy::from_read_iter(contents.as_bytes()) - .collect::, _>>() - .map_err(|_| "file contains an invalid dotenv assignment".to_string())?; - if entries.iter().any(|(_, value)| value.contains('\0')) { - return Err("file contains a dotenv value with a NUL byte".to_string()); - } - - Ok(Some(ConditionalDotenv { - condition, - unset: unset.unwrap_or_default(), - entries, - })) -} - -fn evaluate_condition( - condition: &Condition, - overlay_entries: &[(String, String)], - tcp_connect: &TcpConnector<'_>, -) -> Result { - match condition { - Condition::TcpConnect(condition) => { - evaluate_tcp_connect(condition, overlay_entries, tcp_connect) - } - Condition::Not { not } => { - evaluate_tcp_connect(not, overlay_entries, tcp_connect).map(|connected| !connected) - } - } -} - -fn evaluate_tcp_connect( - condition: &TcpConnectCondition, - overlay_entries: &[(String, String)], - tcp_connect: &TcpConnector<'_>, -) -> Result { - match condition { - TcpConnectCondition::TcpConnect { - from, - host, - port, - timeout_ms, - } => { - let target = parse_tcp_connect_target(from.as_deref(), host.as_deref(), *port)?; - let (host, port) = match target { - TcpConnectTarget::FromVariable(from) => { - let value = overlay_entries - .iter() - .rev() - .find_map(|(key, value)| { - (key == from || (cfg!(windows) && key.eq_ignore_ascii_case(from))) - .then_some(value) - }) - .ok_or_else(|| { - format!( - "tcp_connect source variable `{from}` is not defined in the overlay" - ) - })?; - parse_endpoint(value).ok_or_else(|| { - format!( - "tcp_connect source variable `{from}` does not contain a valid endpoint" - ) - })? - } - TcpConnectTarget::Explicit { host, port } => (host.to_string(), port), - }; - let timeout = tcp_connect_timeout(*timeout_ms)?; - Ok((tcp_connect)(&host, port, timeout)) - } - } -} - -fn apply_overlay(overlay: ConditionalDotenv, environment: &mut dyn StartupEnvironment) { - for key in overlay.unset { - if !is_reserved_env_var(&key) { - environment.remove(&key); - } - } - for (key, value) in overlay.entries { - if !is_reserved_env_var(&key) { - environment.set(&key, &value); - } - } -} - -enum TcpConnectTarget<'a> { - FromVariable(&'a str), - Explicit { host: &'a str, port: u16 }, -} - -fn parse_tcp_connect_target<'a>( - from: Option<&'a str>, - host: Option<&'a str>, - port: Option, -) -> Result, String> { - match (from, host, port) { - (Some(from), None, None) => { - if !is_valid_env_var_name(from) { - return Err(format!( - "tcp_connect contains invalid source variable name `{from}`" - )); - } - Ok(TcpConnectTarget::FromVariable(from)) - } - (None, Some(host), Some(port)) => { - if host.is_empty() { - return Err("tcp_connect host must not be empty".to_string()); - } - if port == 0 { - return Err("tcp_connect port must be greater than zero".to_string()); - } - Ok(TcpConnectTarget::Explicit { host, port }) - } - (Some(_), _, _) => Err( - "tcp_connect must specify either `from` or `host` and `port`, but not both".to_string(), - ), - (None, _, _) => { - Err("tcp_connect requires either `from` or both `host` and `port`".to_string()) - } - } -} - -fn tcp_connect_timeout(timeout_ms: Option) -> Result { - let timeout_ms = timeout_ms.unwrap_or(DEFAULT_TCP_CONNECT_TIMEOUT_MS); - if !(1..=MAX_TCP_CONNECT_TIMEOUT_MS).contains(&timeout_ms) { - return Err(format!( - "tcp_connect timeout_ms must be between 1 and {MAX_TCP_CONNECT_TIMEOUT_MS}" - )); - } - Ok(Duration::from_millis(timeout_ms)) -} - -fn parse_endpoint(value: &str) -> Option<(String, u16)> { - let value = value.trim(); - let parsed = if value.contains("://") { - Url::parse(value).ok()? - } else { - Url::parse(&format!("http://{value}")).ok()? - }; - let host = match parsed.host()? { - url::Host::Ipv6(address) => address.to_string(), - host => host.to_string(), - }; - let port = parsed.port_or_known_default()?; - (port != 0).then_some((host, port)) -} - -fn system_tcp_connect(host: &str, port: u16, timeout: Duration) -> bool { - // `getaddrinfo` cannot be cancelled portably. Isolate it in a child that can be killed and - // reaped without introducing a resolver thread into the environment-mutating parent. - let Ok(current_exe) = std::env::current_exe() else { - return false; - }; - let Ok(mut child) = Command::new(current_exe) - .arg(TCP_CONNECT_HELPER_ARG1) - .arg(host) - .arg(port.to_string()) - .arg(timeout.as_millis().to_string()) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - else { - return false; - }; - - let deadline = Instant::now() + timeout; - loop { - match child.try_wait() { - Ok(Some(status)) => return status.success(), - Ok(None) => {} - Err(_) => break, - } - - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - break; - } - std::thread::sleep(remaining.min(TCP_CONNECT_HELPER_POLL_INTERVAL)); - } - - let _ = child.kill(); - let _ = child.wait(); - false -} - -fn direct_tcp_connect(host: &str, port: u16, timeout: Duration) -> bool { - let deadline = Instant::now() + timeout; - let Ok(addresses) = (host, port) - .to_socket_addrs() - .map(Iterator::collect::>) - else { - return false; - }; - if deadline.saturating_duration_since(Instant::now()).is_zero() { - return false; - } - - let Ok(runtime) = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - else { - return false; - }; - runtime.block_on(async move { - tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), async move { - let mut attempts = tokio::task::JoinSet::new(); - for address in addresses { - attempts.spawn(tokio::net::TcpStream::connect(address)); - } - while let Some(result) = attempts.join_next().await { - if matches!(result, Ok(Ok(_))) { - return true; - } - } - false - }) - .await - .unwrap_or(false) - }) -} - -fn is_valid_env_var_name(key: &str) -> bool { - let mut chars = key.chars(); - chars - .next() - .is_some_and(|first| first.is_ascii_alphabetic() || first == '_') - && chars.all(|character| { - character.is_ascii_alphanumeric() || character == '_' || character == '.' - }) -} - -/// Minimal environment interface used to test overlay application without mutating the test -/// process environment. -trait StartupEnvironment { - fn set(&mut self, key: &str, value: &str); - fn remove(&mut self, key: &str); -} - -struct ProcessEnvironment; - -impl StartupEnvironment for ProcessEnvironment { - fn set(&mut self, key: &str, value: &str) { - // Safety: this loader runs from arg0_dispatch before Codex creates any threads. - unsafe { std::env::set_var(key, value) }; - } - - fn remove(&mut self, key: &str) { - // Safety: this loader runs from arg0_dispatch before Codex creates any threads. - unsafe { std::env::remove_var(key) }; - } -} - -struct ConditionalDotenv { - condition: Condition, - unset: Vec, - entries: Vec<(String, String)>, -} - -#[derive(Debug, Deserialize)] -#[serde(untagged, deny_unknown_fields)] -enum Condition { - TcpConnect(TcpConnectCondition), - Not { not: TcpConnectCondition }, -} - -#[derive(Debug, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum TcpConnectCondition { - TcpConnect { - from: Option, - host: Option, - port: Option, - timeout_ms: Option, - }, -} - -#[cfg(test)] -#[path = "conditional_dotenv_tests.rs"] -mod tests; diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index 3833449822..1c28f81d8c 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -15,8 +15,6 @@ use codex_windows_sandbox::CODEX_WINDOWS_SANDBOX_ARG1; use std::os::unix::fs::symlink; use tempfile::TempDir; -mod conditional_dotenv; - const APPLY_PATCH_ARG0: &str = "apply_patch"; const MISSPELLED_APPLY_PATCH_ARG0: &str = "applypatch"; #[cfg(unix)] @@ -100,9 +98,6 @@ pub fn arg0_dispatch() -> Option { } let argv1 = args.next().unwrap_or_default(); - if argv1 == conditional_dotenv::TCP_CONNECT_HELPER_ARG1 { - conditional_dotenv::run_tcp_connect_helper(args); - } if argv1 == CODEX_FS_HELPER_ARG1 { codex_exec_server::run_fs_helper_main(); } @@ -196,7 +191,7 @@ fn prepare_path_env_var_with_aliases( /// `codex-linux-sandbox` we *directly* execute /// [`codex_linux_sandbox::run_main`] (which never returns). Otherwise we: /// -/// 1. Load `.env` and matching conditional dotenv values from `~/.codex` before creating threads. +/// 1. Load `.env` values from `~/.codex/.env` before creating any threads. /// 2. Spawn a main runtime thread with a controlled stack size. /// 3. Construct a Tokio multi-thread runtime. /// 4. Capture the current executable path and derive the @@ -290,18 +285,16 @@ fn build_runtime() -> anyhow::Result { const ILLEGAL_ENV_VAR_PREFIX: &str = "CODEX_"; -/// Load base and conditional env vars from the startup Codex home. +/// Load env vars from ~/.codex/.env. /// /// Security: Do not allow `.env` files to create or modify any variables /// with names starting with `CODEX_`. fn load_dotenv() { - let Ok(codex_home) = find_codex_home() else { - return; - }; - if let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) { + if let Ok(codex_home) = find_codex_home() + && let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) + { set_filtered(iter); } - conditional_dotenv::load(codex_home.as_path()); } /// Helper to set vars from a dotenvy iterator while filtering out `CODEX_` keys. @@ -310,7 +303,7 @@ where I: IntoIterator>, { for (key, value) in iter.into_iter().flatten() { - if !is_reserved_env_var(&key) { + if !key.to_ascii_uppercase().starts_with(ILLEGAL_ENV_VAR_PREFIX) { // It is safe to call set_var() because our process is // single-threaded at this point in its execution. unsafe { std::env::set_var(&key, &value) }; @@ -318,11 +311,6 @@ where } } -fn is_reserved_env_var(key: &str) -> bool { - key.get(..ILLEGAL_ENV_VAR_PREFIX.len()) - .is_some_and(|prefix| prefix.eq_ignore_ascii_case(ILLEGAL_ENV_VAR_PREFIX)) -} - /// Creates a temporary directory with either: /// /// - UNIX: `apply_patch` symlink to the current executable From 7affe3e3e476e002b7361ffbf644f8b40bad7a8f Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Mon, 6 Jul 2026 12:22:40 -0700 Subject: [PATCH 17/17] refactor(protocol): isolate legacy item fanout (#30956) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Stack 1. [#30956](https://github.com/openai/codex/pull/30956) — isolate legacy item fanout ← **this PR** 2. [#30283](https://github.com/openai/codex/pull/30283) — emit canonical `TurnItem` lifecycle 3. [#30188](https://github.com/openai/codex/pull/30188) — persist canonical items for paginated threads ## Description Move legacy `EventMsg` projection code out of the canonical item and protocol schema modules into `protocol/src/legacy_events.rs`. This is a behavior-neutral extraction. It keeps the existing `HasLegacyEvent` API and the existing legacy projections unchanged, while giving compatibility fanout a single home. ## Why Canonical `TurnItem` types and wire event schemas should not own the implementation details for legacy compatibility projections. Isolating that code makes the boundary explicit and keeps follow-up canonical lifecycle work easier to review. --- codex-rs/protocol/src/items.rs | 189 ---------------- codex-rs/protocol/src/legacy_events.rs | 289 +++++++++++++++++++++++++ codex-rs/protocol/src/lib.rs | 1 + codex-rs/protocol/src/protocol.rs | 74 +------ 4 files changed, 292 insertions(+), 261 deletions(-) create mode 100644 codex-rs/protocol/src/legacy_events.rs diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index c319573446..820c3b774b 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -10,26 +10,12 @@ use crate::models::ResponseItem; use crate::models::WebSearchAction; use crate::openai_models::ReasoningEffort as ReasoningEffortConfig; use crate::parse_command::ParsedCommand; -use crate::protocol::AgentMessageEvent; -use crate::protocol::AgentReasoningEvent; -use crate::protocol::AgentReasoningRawContentEvent; use crate::protocol::AgentStatus; use crate::protocol::CollabAgentRef; -use crate::protocol::ContextCompactedEvent; -use crate::protocol::EventMsg; use crate::protocol::ExecCommandSource; use crate::protocol::FileChange; -use crate::protocol::ImageGenerationEndEvent; -use crate::protocol::McpInvocation; -use crate::protocol::McpToolCallBeginEvent; -use crate::protocol::McpToolCallEndEvent; -use crate::protocol::PatchApplyBeginEvent; -use crate::protocol::PatchApplyEndEvent; use crate::protocol::PatchApplyStatus; use crate::protocol::SubAgentActivityKind; -use crate::protocol::UserMessageEvent; -use crate::protocol::ViewImageToolCallEvent; -use crate::protocol::WebSearchEndEvent; use crate::user_input::ByteRange; use crate::user_input::TextElement; use crate::user_input::UserInput; @@ -387,10 +373,6 @@ impl ContextCompactionItem { id: uuid::Uuid::new_v4().to_string(), } } - - pub fn as_legacy_event(&self) -> EventMsg { - EventMsg::ContextCompacted(ContextCompactedEvent {}) - } } impl Default for ContextCompactionItem { @@ -408,20 +390,6 @@ impl UserMessageItem { } } - pub fn as_legacy_event(&self) -> EventMsg { - // Legacy user-message events flatten only text inputs into `message` and - // rebase text element ranges onto that concatenated text. - EventMsg::UserMessage(UserMessageEvent { - client_id: self.client_id.clone(), - message: self.message(), - images: Some(self.image_urls()), - image_details: self.image_details(), - local_images: self.local_image_paths(), - local_image_details: self.local_image_details(), - text_elements: self.text_elements(), - }) - } - pub fn message(&self) -> String { self.content .iter() @@ -609,134 +577,6 @@ impl AgentMessageItem { memory_citation: None, } } - - pub fn as_legacy_events(&self) -> Vec { - self.content - .iter() - .map(|c| match c { - AgentMessageContent::Text { text } => EventMsg::AgentMessage(AgentMessageEvent { - message: text.clone(), - phase: self.phase.clone(), - memory_citation: self.memory_citation.clone(), - }), - }) - .collect() - } -} - -impl ReasoningItem { - pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { - let mut events = Vec::new(); - for summary in &self.summary_text { - events.push(EventMsg::AgentReasoning(AgentReasoningEvent { - text: summary.clone(), - })); - } - - if show_raw_agent_reasoning { - for entry in &self.raw_content { - events.push(EventMsg::AgentReasoningRawContent( - AgentReasoningRawContentEvent { - text: entry.clone(), - }, - )); - } - } - - events - } -} - -impl WebSearchItem { - pub fn as_legacy_event(&self) -> EventMsg { - EventMsg::WebSearchEnd(WebSearchEndEvent { - call_id: self.id.clone(), - query: self.query.clone(), - action: self.action.clone(), - }) - } -} - -impl ImageGenerationItem { - pub fn as_legacy_event(&self) -> EventMsg { - EventMsg::ImageGenerationEnd(ImageGenerationEndEvent { - call_id: self.id.clone(), - status: self.status.clone(), - revised_prompt: self.revised_prompt.clone(), - result: self.result.clone(), - saved_path: self.saved_path.clone(), - }) - } -} - -impl FileChangeItem { - pub fn as_legacy_begin_event(&self, turn_id: String) -> EventMsg { - EventMsg::PatchApplyBegin(PatchApplyBeginEvent { - call_id: self.id.clone(), - turn_id, - auto_approved: self.auto_approved.unwrap_or(false), - changes: self.changes.clone(), - }) - } - - pub fn as_legacy_end_event(&self, turn_id: String) -> Option { - let status = self.status.clone()?; - Some(EventMsg::PatchApplyEnd(PatchApplyEndEvent { - call_id: self.id.clone(), - turn_id, - stdout: self.stdout.clone().unwrap_or_default(), - stderr: self.stderr.clone().unwrap_or_default(), - success: status == PatchApplyStatus::Completed, - changes: self.changes.clone(), - status, - })) - } -} - -impl McpToolCallItem { - pub fn as_legacy_begin_event(&self) -> EventMsg { - EventMsg::McpToolCallBegin(McpToolCallBeginEvent { - call_id: self.id.clone(), - invocation: McpInvocation { - server: self.server.clone(), - tool: self.tool.clone(), - arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), - }, - connector_id: self.connector_id.clone(), - mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), - link_id: self.link_id.clone(), - app_name: self.app_name.clone(), - template_id: self.template_id.clone(), - action_name: self.action_name.clone(), - plugin_id: self.plugin_id.clone(), - }) - } - - pub fn as_legacy_end_event(&self) -> Option { - let result = match (&self.result, &self.error) { - (Some(result), _) => Ok(result.clone()), - (None, Some(error)) => Err(error.message.clone()), - (None, None) => return None, - }; - - Some(EventMsg::McpToolCallEnd(McpToolCallEndEvent { - call_id: self.id.clone(), - invocation: McpInvocation { - server: self.server.clone(), - tool: self.tool.clone(), - arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), - }, - mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), - connector_id: self.connector_id.clone(), - link_id: self.link_id.clone(), - app_name: self.app_name.clone(), - template_id: self.template_id.clone(), - action_name: self.action_name.clone(), - plugin_id: self.plugin_id.clone(), - duration: self.duration?, - result, - })) - } } impl TurnItem { @@ -760,35 +600,6 @@ impl TurnItem { TurnItem::ContextCompaction(item) => item.id.clone(), } } - - pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { - match self { - TurnItem::UserMessage(item) => vec![item.as_legacy_event()], - TurnItem::HookPrompt(_) => Vec::new(), - TurnItem::AgentMessage(item) => item.as_legacy_events(), - TurnItem::Plan(_) => Vec::new(), - TurnItem::CommandExecution(_) - | TurnItem::DynamicToolCall(_) - | TurnItem::CollabAgentToolCall(_) => Vec::new(), - TurnItem::SubAgentActivity(_) => Vec::new(), - TurnItem::WebSearch(item) => vec![item.as_legacy_event()], - TurnItem::ImageView(item) => { - vec![EventMsg::ViewImageToolCall(ViewImageToolCallEvent { - call_id: item.id.clone(), - path: item.path.clone(), - })] - } - TurnItem::Sleep(_) => Vec::new(), - TurnItem::ImageGeneration(item) => vec![item.as_legacy_event()], - TurnItem::FileChange(item) => item - .as_legacy_end_event(String::new()) - .into_iter() - .collect(), - TurnItem::McpToolCall(item) => item.as_legacy_end_event().into_iter().collect(), - TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning), - TurnItem::ContextCompaction(item) => vec![item.as_legacy_event()], - } - } } #[cfg(test)] diff --git a/codex-rs/protocol/src/legacy_events.rs b/codex-rs/protocol/src/legacy_events.rs new file mode 100644 index 0000000000..f4a511d367 --- /dev/null +++ b/codex-rs/protocol/src/legacy_events.rs @@ -0,0 +1,289 @@ +use crate::items::AgentMessageContent; +use crate::items::AgentMessageItem; +use crate::items::ContextCompactionItem; +use crate::items::FileChangeItem; +use crate::items::ImageGenerationItem; +use crate::items::McpToolCallItem; +use crate::items::ReasoningItem; +use crate::items::TurnItem; +use crate::items::UserMessageItem; +use crate::items::WebSearchItem; +use crate::protocol::AgentMessageContentDeltaEvent; +use crate::protocol::AgentMessageEvent; +use crate::protocol::AgentReasoningEvent; +use crate::protocol::AgentReasoningRawContentEvent; +use crate::protocol::ContextCompactedEvent; +use crate::protocol::EventMsg; +use crate::protocol::ImageGenerationBeginEvent; +use crate::protocol::ImageGenerationEndEvent; +use crate::protocol::ItemCompletedEvent; +use crate::protocol::ItemStartedEvent; +use crate::protocol::McpInvocation; +use crate::protocol::McpToolCallBeginEvent; +use crate::protocol::McpToolCallEndEvent; +use crate::protocol::PatchApplyBeginEvent; +use crate::protocol::PatchApplyEndEvent; +use crate::protocol::PatchApplyStatus; +use crate::protocol::ReasoningContentDeltaEvent; +use crate::protocol::ReasoningRawContentDeltaEvent; +use crate::protocol::UserMessageEvent; +use crate::protocol::ViewImageToolCallEvent; +use crate::protocol::WebSearchBeginEvent; +use crate::protocol::WebSearchEndEvent; + +/// Converts canonical item lifecycle events back into the legacy raw event stream used by +/// compatibility consumers that have not migrated to `TurnItem`. +pub trait HasLegacyEvent { + fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec; +} + +impl ContextCompactionItem { + pub fn as_legacy_event(&self) -> EventMsg { + EventMsg::ContextCompacted(ContextCompactedEvent {}) + } +} + +impl UserMessageItem { + pub fn as_legacy_event(&self) -> EventMsg { + // Legacy user-message events flatten only text inputs into `message` and + // rebase text element ranges onto that concatenated text. + EventMsg::UserMessage(UserMessageEvent { + client_id: self.client_id.clone(), + message: self.message(), + images: Some(self.image_urls()), + image_details: self.image_details(), + local_images: self.local_image_paths(), + local_image_details: self.local_image_details(), + text_elements: self.text_elements(), + }) + } +} + +impl AgentMessageItem { + pub fn as_legacy_events(&self) -> Vec { + self.content + .iter() + .map(|c| match c { + AgentMessageContent::Text { text } => EventMsg::AgentMessage(AgentMessageEvent { + message: text.clone(), + phase: self.phase.clone(), + memory_citation: self.memory_citation.clone(), + }), + }) + .collect() + } +} + +impl ReasoningItem { + pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { + let mut events = Vec::new(); + for summary in &self.summary_text { + events.push(EventMsg::AgentReasoning(AgentReasoningEvent { + text: summary.clone(), + })); + } + + if show_raw_agent_reasoning { + for entry in &self.raw_content { + events.push(EventMsg::AgentReasoningRawContent( + AgentReasoningRawContentEvent { + text: entry.clone(), + }, + )); + } + } + + events + } +} + +impl WebSearchItem { + pub fn as_legacy_event(&self) -> EventMsg { + EventMsg::WebSearchEnd(WebSearchEndEvent { + call_id: self.id.clone(), + query: self.query.clone(), + action: self.action.clone(), + }) + } +} + +impl ImageGenerationItem { + pub fn as_legacy_event(&self) -> EventMsg { + EventMsg::ImageGenerationEnd(ImageGenerationEndEvent { + call_id: self.id.clone(), + status: self.status.clone(), + revised_prompt: self.revised_prompt.clone(), + result: self.result.clone(), + saved_path: self.saved_path.clone(), + }) + } +} + +impl FileChangeItem { + pub fn as_legacy_begin_event(&self, turn_id: String) -> EventMsg { + EventMsg::PatchApplyBegin(PatchApplyBeginEvent { + call_id: self.id.clone(), + turn_id, + auto_approved: self.auto_approved.unwrap_or(false), + changes: self.changes.clone(), + }) + } + + pub fn as_legacy_end_event(&self, turn_id: String) -> Option { + let status = self.status.clone()?; + Some(EventMsg::PatchApplyEnd(PatchApplyEndEvent { + call_id: self.id.clone(), + turn_id, + stdout: self.stdout.clone().unwrap_or_default(), + stderr: self.stderr.clone().unwrap_or_default(), + success: status == PatchApplyStatus::Completed, + changes: self.changes.clone(), + status, + })) + } +} + +impl McpToolCallItem { + pub fn as_legacy_begin_event(&self) -> EventMsg { + EventMsg::McpToolCallBegin(McpToolCallBeginEvent { + call_id: self.id.clone(), + invocation: McpInvocation { + server: self.server.clone(), + tool: self.tool.clone(), + arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), + }, + connector_id: self.connector_id.clone(), + mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), + link_id: self.link_id.clone(), + app_name: self.app_name.clone(), + template_id: self.template_id.clone(), + action_name: self.action_name.clone(), + plugin_id: self.plugin_id.clone(), + }) + } + + pub fn as_legacy_end_event(&self) -> Option { + let result = match (&self.result, &self.error) { + (Some(result), _) => Ok(result.clone()), + (None, Some(error)) => Err(error.message.clone()), + (None, None) => return None, + }; + + Some(EventMsg::McpToolCallEnd(McpToolCallEndEvent { + call_id: self.id.clone(), + invocation: McpInvocation { + server: self.server.clone(), + tool: self.tool.clone(), + arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), + }, + mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), + connector_id: self.connector_id.clone(), + link_id: self.link_id.clone(), + app_name: self.app_name.clone(), + template_id: self.template_id.clone(), + action_name: self.action_name.clone(), + plugin_id: self.plugin_id.clone(), + duration: self.duration?, + result, + })) + } +} + +impl TurnItem { + pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { + match self { + TurnItem::UserMessage(item) => vec![item.as_legacy_event()], + TurnItem::HookPrompt(_) => Vec::new(), + TurnItem::AgentMessage(item) => item.as_legacy_events(), + TurnItem::Plan(_) => Vec::new(), + TurnItem::CommandExecution(_) + | TurnItem::DynamicToolCall(_) + | TurnItem::CollabAgentToolCall(_) => Vec::new(), + TurnItem::SubAgentActivity(_) => Vec::new(), + TurnItem::WebSearch(item) => vec![item.as_legacy_event()], + TurnItem::ImageView(item) => { + vec![EventMsg::ViewImageToolCall(ViewImageToolCallEvent { + call_id: item.id.clone(), + path: item.path.clone(), + })] + } + TurnItem::Sleep(_) => Vec::new(), + TurnItem::ImageGeneration(item) => vec![item.as_legacy_event()], + TurnItem::FileChange(item) => item + .as_legacy_end_event(String::new()) + .into_iter() + .collect(), + TurnItem::McpToolCall(item) => item.as_legacy_end_event().into_iter().collect(), + TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning), + TurnItem::ContextCompaction(item) => vec![item.as_legacy_event()], + } + } +} + +impl HasLegacyEvent for ItemStartedEvent { + fn as_legacy_events(&self, _: bool) -> Vec { + match &self.item { + TurnItem::WebSearch(item) => vec![EventMsg::WebSearchBegin(WebSearchBeginEvent { + call_id: item.id.clone(), + })], + TurnItem::ImageView(_) => Vec::new(), + TurnItem::ImageGeneration(item) => { + vec![EventMsg::ImageGenerationBegin(ImageGenerationBeginEvent { + call_id: item.id.clone(), + })] + } + TurnItem::FileChange(item) => vec![item.as_legacy_begin_event(self.turn_id.clone())], + TurnItem::McpToolCall(item) => vec![item.as_legacy_begin_event()], + _ => Vec::new(), + } + } +} + +impl HasLegacyEvent for ItemCompletedEvent { + fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { + match &self.item { + TurnItem::FileChange(item) => item + .as_legacy_end_event(self.turn_id.clone()) + .into_iter() + .collect(), + _ => self.item.as_legacy_events(show_raw_agent_reasoning), + } + } +} + +impl HasLegacyEvent for AgentMessageContentDeltaEvent { + fn as_legacy_events(&self, _: bool) -> Vec { + Vec::new() + } +} + +impl HasLegacyEvent for ReasoningContentDeltaEvent { + fn as_legacy_events(&self, _: bool) -> Vec { + Vec::new() + } +} + +impl HasLegacyEvent for ReasoningRawContentDeltaEvent { + fn as_legacy_events(&self, _: bool) -> Vec { + Vec::new() + } +} + +impl HasLegacyEvent for EventMsg { + fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { + match self { + EventMsg::ItemStarted(event) => event.as_legacy_events(show_raw_agent_reasoning), + EventMsg::ItemCompleted(event) => event.as_legacy_events(show_raw_agent_reasoning), + EventMsg::AgentMessageContentDelta(event) => { + event.as_legacy_events(show_raw_agent_reasoning) + } + EventMsg::ReasoningContentDelta(event) => { + event.as_legacy_events(show_raw_agent_reasoning) + } + EventMsg::ReasoningRawContentDelta(event) => { + event.as_legacy_events(show_raw_agent_reasoning) + } + _ => Vec::new(), + } + } +} diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index c50e95d37f..636c64ed7b 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -16,6 +16,7 @@ pub mod dynamic_tools; pub mod error; pub mod exec_output; pub mod items; +mod legacy_events; pub mod mcp; pub mod mcp_approval_meta; pub mod memory_citation; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 0096915efb..2c97af10aa 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -84,6 +84,7 @@ pub use crate::approvals::NetworkApprovalContext; pub use crate::approvals::NetworkApprovalProtocol; pub use crate::approvals::NetworkPolicyAmendment; pub use crate::approvals::NetworkPolicyRuleAction; +pub use crate::legacy_events::HasLegacyEvent; pub use crate::permissions::FileSystemAccessMode; pub use crate::permissions::FileSystemPath; pub use crate::permissions::FileSystemSandboxEntry; @@ -1794,25 +1795,6 @@ pub struct ItemStartedEvent { pub started_at_ms: i64, } -impl HasLegacyEvent for ItemStartedEvent { - fn as_legacy_events(&self, _: bool) -> Vec { - match &self.item { - TurnItem::WebSearch(item) => vec![EventMsg::WebSearchBegin(WebSearchBeginEvent { - call_id: item.id.clone(), - })], - TurnItem::ImageView(_) => Vec::new(), - TurnItem::ImageGeneration(item) => { - vec![EventMsg::ImageGenerationBegin(ImageGenerationBeginEvent { - call_id: item.id.clone(), - })] - } - TurnItem::FileChange(item) => vec![item.as_legacy_begin_event(self.turn_id.clone())], - TurnItem::McpToolCall(item) => vec![item.as_legacy_begin_event()], - _ => Vec::new(), - } - } -} - #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ItemCompletedEvent { pub thread_id: ThreadId, @@ -1829,22 +1811,6 @@ const fn default_item_completed_at_ms() -> i64 { 0 } -pub trait HasLegacyEvent { - fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec; -} - -impl HasLegacyEvent for ItemCompletedEvent { - fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { - match &self.item { - TurnItem::FileChange(item) => item - .as_legacy_end_event(self.turn_id.clone()) - .into_iter() - .collect(), - _ => self.item.as_legacy_events(show_raw_agent_reasoning), - } - } -} - #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct AgentMessageContentDeltaEvent { pub thread_id: String, @@ -1853,12 +1819,6 @@ pub struct AgentMessageContentDeltaEvent { pub delta: String, } -impl HasLegacyEvent for AgentMessageContentDeltaEvent { - fn as_legacy_events(&self, _: bool) -> Vec { - Vec::new() - } -} - #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct PlanDeltaEvent { pub thread_id: String, @@ -1878,12 +1838,6 @@ pub struct ReasoningContentDeltaEvent { pub summary_index: i64, } -impl HasLegacyEvent for ReasoningContentDeltaEvent { - fn as_legacy_events(&self, _: bool) -> Vec { - Vec::new() - } -} - #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct ReasoningRawContentDeltaEvent { pub thread_id: String, @@ -1895,31 +1849,6 @@ pub struct ReasoningRawContentDeltaEvent { pub content_index: i64, } -impl HasLegacyEvent for ReasoningRawContentDeltaEvent { - fn as_legacy_events(&self, _: bool) -> Vec { - Vec::new() - } -} - -impl HasLegacyEvent for EventMsg { - fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec { - match self { - EventMsg::ItemStarted(event) => event.as_legacy_events(show_raw_agent_reasoning), - EventMsg::ItemCompleted(event) => event.as_legacy_events(show_raw_agent_reasoning), - EventMsg::AgentMessageContentDelta(event) => { - event.as_legacy_events(show_raw_agent_reasoning) - } - EventMsg::ReasoningContentDelta(event) => { - event.as_legacy_events(show_raw_agent_reasoning) - } - EventMsg::ReasoningRawContentDelta(event) => { - event.as_legacy_events(show_raw_agent_reasoning) - } - _ => Vec::new(), - } - } -} - #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct ExitedReviewModeEvent { pub review_output: Option, @@ -5386,6 +5315,7 @@ mod tests { let event = serde_json::from_value::(value).unwrap(); assert_eq!(event.completed_at_ms, 0); } + #[test] fn rollback_failed_error_does_not_affect_turn_status() { let event = ErrorEvent {