diff --git a/.github/scripts/install-musl-build-tools.sh b/.github/scripts/install-musl-build-tools.sh index e4c6683d0e..49035f5391 100644 --- a/.github/scripts/install-musl-build-tools.sh +++ b/.github/scripts/install-musl-build-tools.sh @@ -150,7 +150,9 @@ for arg in "\$@"; do args+=("\${arg}") done -exec "${zig_bin}" cc -target "${zig_target}" "\${args[@]}" +# Zig enables UBSan for debug C builds by default. Rust links these objects +# without Zig's sanitizer runtime, so keep native dependencies uninstrumented. +exec "${zig_bin}" cc -target "${zig_target}" "\${args[@]}" -fno-sanitize=undefined EOF cat >"${cxx}" <> "$GITHUB_ENV" pkg_config_path_var="PKG_CONFIG_PATH_${TARGET}" pkg_config_path_var="${pkg_config_path_var//-/_}" echo "${pkg_config_path_var}=${libcap_pkgconfig_dir}" >> "$GITHUB_ENV" +pkg_config_libdir_var="PKG_CONFIG_LIBDIR_${TARGET}" +pkg_config_libdir_var="${pkg_config_libdir_var//-/_}" +# Do not let musl cross-builds resolve native libraries from the host glibc +# pkg-config directories. libcap is the only target package provided here. +echo "${pkg_config_libdir_var}=${libcap_pkgconfig_dir}" >> "$GITHUB_ENV" if [[ -n "${sysroot}" && "${sysroot}" != "/" ]]; then echo "PKG_CONFIG_SYSROOT_DIR=${sysroot}" >> "$GITHUB_ENV" diff --git a/.github/workflows/bazel.yml b/.github/workflows/bazel.yml index 11c0988ceb..153ace0fc9 100644 --- a/.github/workflows/bazel.yml +++ b/.github/workflows/bazel.yml @@ -141,7 +141,9 @@ jobs: - 2 - 3 - 4 - runs-on: windows-latest + runs-on: + group: codex-runners + labels: codex-windows-x64 name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm shard ${{ matrix.shard }}/4 steps: @@ -246,7 +248,9 @@ jobs: # it a larger timeout. if: github.event_name == 'push' && github.ref == 'refs/heads/main' timeout-minutes: 40 - runs-on: windows-latest + runs-on: + group: codex-runners + labels: codex-windows-x64 name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm (native main) steps: @@ -332,7 +336,10 @@ jobs: target: aarch64-apple-darwin - os: windows-latest target: x86_64-pc-windows-gnullvm - runs-on: ${{ matrix.os }} + runs_on: + group: codex-runners + labels: codex-windows-x64 + runs-on: ${{ matrix.runs_on || matrix.os }} name: Bazel clippy on ${{ matrix.os }} for ${{ matrix.target }} steps: @@ -422,7 +429,10 @@ jobs: target: aarch64-apple-darwin - os: windows-latest target: x86_64-pc-windows-gnullvm - runs-on: ${{ matrix.os }} + runs_on: + group: codex-runners + labels: codex-windows-x64 + runs-on: ${{ matrix.runs_on || matrix.os }} name: Verify release build on ${{ matrix.os }} for ${{ matrix.target }} steps: diff --git a/.github/workflows/python-sdk-release.yml b/.github/workflows/python-sdk-release.yml new file mode 100644 index 0000000000..654dd8d822 --- /dev/null +++ b/.github/workflows/python-sdk-release.yml @@ -0,0 +1,91 @@ +name: python-sdk-release + +on: + push: + tags: + - "python-v*" + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + +jobs: + build-python-sdk: + if: github.repository == 'openai/codex' + name: build-python-sdk + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Validate tag and build Python SDK package + shell: bash + run: | + set -euo pipefail + + sdk_version="${GITHUB_REF_NAME#python-v}" + if [[ ! "${sdk_version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+b[0-9]+$ ]]; then + echo "Python SDK release tags must identify a beta release, for example python-v0.1.0b1." + exit 1 + fi + + # The pinned runtime currently publishes a musllinux Linux wheel. + # Build in Alpine so release type generation installs that wheel. + docker run --rm \ + --user "$(id -u):$(id -g)" \ + -e HOME=/tmp/codex-python-sdk-home \ + -e UV_LINK_MODE=copy \ + -e SDK_VERSION="${sdk_version}" \ + -e SDK_STAGE_DIR="${RUNNER_TEMP}/openai-codex" \ + -e SDK_DIST_DIR="${GITHUB_WORKSPACE}/dist/python-sdk" \ + -v "${GITHUB_WORKSPACE}:${GITHUB_WORKSPACE}" \ + -v "${RUNNER_TEMP}:${RUNNER_TEMP}" \ + -w "${GITHUB_WORKSPACE}/sdk/python" \ + python:3.12-alpine \ + sh -euxc ' + python -m venv /tmp/release-tools + /tmp/release-tools/bin/python -m pip install build twine uv==0.11.3 + /tmp/release-tools/bin/uv sync --extra dev --frozen + /tmp/release-tools/bin/uv run --extra dev --frozen python scripts/update_sdk_artifacts.py \ + stage-sdk "${SDK_STAGE_DIR}" \ + --sdk-version "${SDK_VERSION}" + /tmp/release-tools/bin/python -m build \ + --wheel \ + --sdist \ + --outdir "${SDK_DIST_DIR}" \ + "${SDK_STAGE_DIR}" + /tmp/release-tools/bin/python -m twine check --strict "${SDK_DIST_DIR}/"* + ' + + - name: Upload Python SDK package + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 + with: + name: python-sdk-package + path: dist/python-sdk/* + if-no-files-found: error + + publish-python-sdk: + name: publish-python-sdk + needs: build-python-sdk + runs-on: ubuntu-latest + environment: pypi + permissions: + contents: read + id-token: write # Required for PyPI trusted publishing. + + steps: + - name: Download Python SDK package + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: python-sdk-package + path: dist/python-sdk + + - name: Publish Python SDK to PyPI + uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0 + with: + packages-dir: dist/python-sdk diff --git a/.github/workflows/rust-ci-full.yml b/.github/workflows/rust-ci-full.yml index 2111ed7b0a..60d508b21d 100644 --- a/.github/workflows/rust-ci-full.yml +++ b/.github/workflows/rust-ci-full.yml @@ -260,11 +260,7 @@ jobs: set -euo pipefail if command -v apt-get >/dev/null 2>&1; then sudo apt-get update -y - packages=(pkg-config libcap-dev) - if [[ "${{ matrix.target }}" == 'x86_64-unknown-linux-musl' || "${{ matrix.target }}" == 'aarch64-unknown-linux-musl' ]]; then - packages+=(libubsan1) - fi - sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${packages[@]}" + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends pkg-config libcap-dev fi - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: @@ -348,14 +344,6 @@ jobs: sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}-${{ steps.lockhash.outputs.hash }}- sccache-${{ matrix.runner }}-${{ matrix.target }}-${{ matrix.profile }}- - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} - name: Disable sccache wrapper (musl) - shell: bash - run: | - set -euo pipefail - echo "RUSTC_WRAPPER=" >> "$GITHUB_ENV" - echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} name: Prepare APT cache directories (musl) shell: bash @@ -389,58 +377,6 @@ jobs: shell: bash run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh" - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} - name: Configure rustc UBSan wrapper (musl host) - shell: bash - run: | - set -euo pipefail - ubsan="" - if command -v ldconfig >/dev/null 2>&1; then - ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')" - fi - wrapper_root="${RUNNER_TEMP:-/tmp}" - wrapper="${wrapper_root}/rustc-ubsan-wrapper" - cat > "${wrapper}" <> "$GITHUB_ENV" - echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" - - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} - name: Clear sanitizer flags (musl) - shell: bash - run: | - set -euo pipefail - # Clear global Rust flags so host/proc-macro builds don't pull in UBSan. - echo "RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV" - # Override any runner-level Cargo config rustflags as well. - echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" - - sanitize_flags() { - local input="$1" - input="${input//-fsanitize=undefined/}" - input="${input//-fno-sanitize-recover=undefined/}" - input="${input//-fno-sanitize-trap=undefined/}" - echo "$input" - } - - cflags="$(sanitize_flags "${CFLAGS-}")" - cxxflags="$(sanitize_flags "${CXXFLAGS-}")" - echo "CFLAGS=${cflags}" >> "$GITHUB_ENV" - echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV" - - if: ${{ !contains(matrix.target, 'windows') }} name: Configure rusty_v8 artifact overrides and verify checksums uses: ./.github/actions/setup-rusty-v8 diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index eaf886cd01..07a2e87ef2 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -245,15 +245,6 @@ jobs: set -euo pipefail sudo apt-get update -y sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends pkg-config libcap-dev - - name: Install UBSan runtime (musl) - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl' }} - shell: bash - run: | - set -euo pipefail - if command -v apt-get >/dev/null 2>&1; then - sudo apt-get update -y - sudo DEBIAN_FRONTEND=noninteractive apt-get install -y libubsan1 - fi - uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0 with: targets: ${{ matrix.target }} @@ -283,30 +274,7 @@ jobs: run: bash "${GITHUB_WORKSPACE}/.github/scripts/install-musl-build-tools.sh" - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} - name: Configure rustc UBSan wrapper (musl host) - shell: bash - run: | - set -euo pipefail - ubsan="" - if command -v ldconfig >/dev/null 2>&1; then - ubsan="$(ldconfig -p | grep -m1 'libubsan\.so\.1' | sed -E 's/.*=> (.*)$/\1/')" - fi - wrapper_root="${RUNNER_TEMP:-/tmp}" - wrapper="${wrapper_root}/rustc-ubsan-wrapper" - cat > "${wrapper}" <> "$GITHUB_ENV" - echo "RUSTC_WORKSPACE_WRAPPER=" >> "$GITHUB_ENV" - - - if: ${{ matrix.target == 'x86_64-unknown-linux-musl' || matrix.target == 'aarch64-unknown-linux-musl'}} - name: Clear sanitizer flags (musl) + name: Disable aws-lc jitter entropy (musl) shell: bash run: | set -euo pipefail @@ -316,30 +284,6 @@ jobs: target_no_jitter="${target_no_jitter//-/_}" echo "${target_no_jitter}=1" >> "$GITHUB_ENV" - # Clear global Rust flags so host/proc-macro builds don't pull in UBSan. - echo "RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_ENCODED_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "RUSTDOCFLAGS=" >> "$GITHUB_ENV" - # Override any runner-level Cargo config rustflags as well. - echo "CARGO_BUILD_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" - echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=" >> "$GITHUB_ENV" - - sanitize_flags() { - local input="$1" - input="${input//-fsanitize=undefined/}" - input="${input//-fno-sanitize-recover=undefined/}" - input="${input//-fno-sanitize-trap=undefined/}" - echo "$input" - } - - cflags="$(sanitize_flags "${CFLAGS-}")" - cxxflags="$(sanitize_flags "${CXXFLAGS-}")" - echo "CFLAGS=${cflags}" >> "$GITHUB_ENV" - echo "CXXFLAGS=${cxxflags}" >> "$GITHUB_ENV" - - name: Configure rusty_v8 artifact overrides and verify checksums uses: ./.github/actions/setup-rusty-v8 with: diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index aac0d6f90c..d5434ad976 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1928,6 +1928,7 @@ dependencies = [ "codex-git-utils", "codex-guardian", "codex-hooks", + "codex-image-generation-extension", "codex-login", "codex-mcp", "codex-memories-extension", @@ -2718,18 +2719,6 @@ dependencies = [ "zip 2.4.2", ] -[[package]] -name = "codex-debug-client" -version = "0.0.0" -dependencies = [ - "anyhow", - "clap", - "codex-app-server-protocol", - "pretty_assertions", - "serde", - "serde_json", -] - [[package]] name = "codex-exec" version = "0.0.0" @@ -3039,6 +3028,27 @@ dependencies = [ "uuid", ] +[[package]] +name = "codex-image-generation-extension" +version = "0.0.0" +dependencies = [ + "async-trait", + "codex-api", + "codex-core", + "codex-extension-api", + "codex-features", + "codex-login", + "codex-model-provider", + "codex-model-provider-info", + "codex-protocol", + "codex-tools", + "http 1.4.0", + "pretty_assertions", + "schemars 0.8.22", + "serde", + "serde_json", +] + [[package]] name = "codex-install-context" version = "0.0.0" @@ -4160,6 +4170,7 @@ dependencies = [ "pretty_assertions", "schemars 0.8.22", "serde_json", + "url", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index b1f9e4c31a..a56caad775 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -14,7 +14,6 @@ members = [ "app-server-client", "app-server-protocol", "app-server-test-client", - "debug-client", "apply-patch", "arg0", "feedback", @@ -47,6 +46,7 @@ members = [ "ext/extension-api", "ext/goal", "ext/guardian", + "ext/image-generation", "ext/memories", "ext/web-search", "external-agent-migration", @@ -165,6 +165,7 @@ codex-execpolicy = { path = "execpolicy" } codex-extension-api = { path = "ext/extension-api" } codex-goal-extension = { path = "ext/goal" } codex-guardian = { path = "ext/guardian" } +codex-image-generation-extension = { path = "ext/image-generation" } codex-external-agent-migration = { path = "external-agent-migration" } codex-external-agent-sessions = { path = "external-agent-sessions" } codex-experimental-api-macros = { path = "codex-experimental-api-macros" } diff --git a/codex-rs/analytics/src/analytics_client_tests.rs b/codex-rs/analytics/src/analytics_client_tests.rs index fa64b46d7a..6a47ec78ca 100644 --- a/codex-rs/analytics/src/analytics_client_tests.rs +++ b/codex-rs/analytics/src/analytics_client_tests.rs @@ -263,6 +263,7 @@ fn sample_thread_resume_response_with_source( sandbox: AppServerSandboxPolicy::DangerFullAccess, active_permission_profile: None, reasoning_effort: None, + initial_turns_page: None, }) } @@ -271,6 +272,7 @@ fn sample_turn_start_request(thread_id: &str, request_id: i64) -> ClientRequest request_id: RequestId::Integer(request_id), params: TurnStartParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: vec![ UserInput::Text { text: "hello".to_string(), @@ -390,6 +392,7 @@ fn sample_turn_steer_request( params: TurnSteerParams { thread_id: thread_id.to_string(), expected_turn_id: expected_turn_id.to_string(), + client_user_message_id: None, input: vec![ UserInput::Text { text: "more".to_string(), diff --git a/codex-rs/analytics/src/client_tests.rs b/codex-rs/analytics/src/client_tests.rs index c6a928afa3..4a375b0639 100644 --- a/codex-rs/analytics/src/client_tests.rs +++ b/codex-rs/analytics/src/client_tests.rs @@ -89,6 +89,7 @@ fn sample_turn_start_request() -> ClientRequest { request_id: RequestId::Integer(1), params: TurnStartParams { thread_id: "thread-1".to_string(), + client_user_message_id: None, input: Vec::new(), ..Default::default() }, @@ -101,6 +102,7 @@ fn sample_turn_steer_request() -> ClientRequest { params: TurnSteerParams { thread_id: "thread-1".to_string(), expected_turn_id: "turn-1".to_string(), + client_user_message_id: None, input: Vec::new(), responsesapi_client_metadata: None, additional_context: None, @@ -172,6 +174,7 @@ fn sample_thread_resume_response() -> ClientResponsePayload { sandbox: AppServerSandboxPolicy::DangerFullAccess, active_permission_profile: None, reasoning_effort: None, + initial_turns_page: None, }) } diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 63e8fbde1a..dc5dd6ad60 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -2988,6 +2988,20 @@ ], "type": "object" }, + "SkillsExtraRootsSetParams": { + "properties": { + "extraRoots": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "extraRoots" + ], + "type": "object" + }, "SkillsListParams": { "properties": { "cwds": { @@ -3543,6 +3557,42 @@ } ] }, + "ThreadResumeInitialTurnsPageParams": { + "properties": { + "itemsView": { + "anyOf": [ + { + "$ref": "#/definitions/TurnItemsView" + }, + { + "type": "null" + } + ], + "description": "How much item detail to include for each returned turn; defaults to summary." + }, + "limit": { + "description": "Optional turn page size.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "sortDirection": { + "anyOf": [ + { + "$ref": "#/definitions/SortDirection" + }, + { + "type": "null" + } + ], + "description": "Optional turn pagination direction; defaults to descending." + } + }, + "type": "object" + }, "ThreadResumeParams": { "description": "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\n\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.", "properties": { @@ -3949,6 +3999,12 @@ ], "description": "Override where approval requests are routed for review on this turn and subsequent turns." }, + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "cwd": { "description": "Override the working directory for this turn and subsequent turns.", "type": [ @@ -4035,6 +4091,12 @@ }, "TurnSteerParams": { "properties": { + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "expectedTurnId": { "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", "type": "string" @@ -4735,6 +4797,30 @@ "title": "Skills/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/extraRoots/set" + ], + "title": "Skills/extraRoots/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsExtraRootsSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/extraRoots/setRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 2c290558da..b0501b0e9e 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -3561,6 +3561,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" 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 28dc006b5e..92549d74c8 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 @@ -709,6 +709,30 @@ "title": "Skills/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "skills/extraRoots/set" + ], + "title": "Skills/extraRoots/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/SkillsExtraRootsSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/extraRoots/setRequest", + "type": "object" + }, { "properties": { "id": { @@ -10964,6 +10988,47 @@ "title": "McpResourceReadResponse", "type": "object" }, + "McpServerInfo": { + "description": "Presentation metadata advertised by an initialized MCP server.", + "properties": { + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "version": { + "type": "string" + }, + "websiteUrl": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, "McpServerMigration": { "properties": { "name": { @@ -11074,6 +11139,16 @@ }, "type": "array" }, + "serverInfo": { + "anyOf": [ + { + "$ref": "#/definitions/v2/McpServerInfo" + }, + { + "type": "null" + } + ] + }, "tools": { "additionalProperties": { "$ref": "#/definitions/v2/Tool" @@ -11794,7 +11869,7 @@ "NetworkUnixSocketPermission": { "enum": [ "allow", - "none" + "deny" ], "type": "string" }, @@ -15070,6 +15145,27 @@ "title": "SkillsConfigWriteResponse", "type": "object" }, + "SkillsExtraRootsSetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "extraRoots": { + "items": { + "$ref": "#/definitions/v2/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "extraRoots" + ], + "title": "SkillsExtraRootsSetParams", + "type": "object" + }, + "SkillsExtraRootsSetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SkillsExtraRootsSetResponse", + "type": "object" + }, "SkillsListEntry": { "properties": { "cwd": { @@ -15945,6 +16041,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/v2/UserInput" @@ -17150,6 +17252,42 @@ "title": "ThreadRealtimeTranscriptDoneNotification", "type": "object" }, + "ThreadResumeInitialTurnsPageParams": { + "properties": { + "itemsView": { + "anyOf": [ + { + "$ref": "#/definitions/v2/TurnItemsView" + }, + { + "type": "null" + } + ], + "description": "How much item detail to include for each returned turn; defaults to summary." + }, + "limit": { + "description": "Optional turn page size.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "sortDirection": { + "anyOf": [ + { + "$ref": "#/definitions/v2/SortDirection" + }, + { + "type": "null" + } + ], + "description": "Optional turn pagination direction; defaults to descending." + } + }, + "type": "object" + }, "ThreadResumeParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\n\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.", @@ -18326,6 +18464,12 @@ ], "description": "Override where approval requests are routed for review on this turn and subsequent turns." }, + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "cwd": { "description": "Override the working directory for this turn and subsequent turns.", "type": [ @@ -18453,6 +18597,12 @@ "TurnSteerParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "expectedTurnId": { "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", "type": "string" @@ -18488,6 +18638,32 @@ "title": "TurnSteerResponse", "type": "object" }, + "TurnsPage": { + "properties": { + "backwardsCursor": { + "type": [ + "string", + "null" + ] + }, + "data": { + "items": { + "$ref": "#/definitions/v2/Turn" + }, + "type": "array" + }, + "nextCursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "type": "object" + }, "UserInput": { "oneOf": [ { 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 d1c59e9855..d266a3e977 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 @@ -1457,6 +1457,30 @@ "title": "Skills/listRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "skills/extraRoots/set" + ], + "title": "Skills/extraRoots/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/SkillsExtraRootsSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Skills/extraRoots/setRequest", + "type": "object" + }, { "properties": { "id": { @@ -7493,6 +7517,47 @@ "title": "McpResourceReadResponse", "type": "object" }, + "McpServerInfo": { + "description": "Presentation metadata advertised by an initialized MCP server.", + "properties": { + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "version": { + "type": "string" + }, + "websiteUrl": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, "McpServerMigration": { "properties": { "name": { @@ -7603,6 +7668,16 @@ }, "type": "array" }, + "serverInfo": { + "anyOf": [ + { + "$ref": "#/definitions/McpServerInfo" + }, + { + "type": "null" + } + ] + }, "tools": { "additionalProperties": { "$ref": "#/definitions/Tool" @@ -8323,7 +8398,7 @@ "NetworkUnixSocketPermission": { "enum": [ "allow", - "none" + "deny" ], "type": "string" }, @@ -12894,6 +12969,27 @@ "title": "SkillsConfigWriteResponse", "type": "object" }, + "SkillsExtraRootsSetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "extraRoots": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "extraRoots" + ], + "title": "SkillsExtraRootsSetParams", + "type": "object" + }, + "SkillsExtraRootsSetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SkillsExtraRootsSetResponse", + "type": "object" + }, "SkillsListEntry": { "properties": { "cwd": { @@ -13769,6 +13865,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" @@ -14974,6 +15076,42 @@ "title": "ThreadRealtimeTranscriptDoneNotification", "type": "object" }, + "ThreadResumeInitialTurnsPageParams": { + "properties": { + "itemsView": { + "anyOf": [ + { + "$ref": "#/definitions/TurnItemsView" + }, + { + "type": "null" + } + ], + "description": "How much item detail to include for each returned turn; defaults to summary." + }, + "limit": { + "description": "Optional turn page size.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "sortDirection": { + "anyOf": [ + { + "$ref": "#/definitions/SortDirection" + }, + { + "type": "null" + } + ], + "description": "Optional turn pagination direction; defaults to descending." + } + }, + "type": "object" + }, "ThreadResumeParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\n\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.", @@ -16150,6 +16288,12 @@ ], "description": "Override where approval requests are routed for review on this turn and subsequent turns." }, + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "cwd": { "description": "Override the working directory for this turn and subsequent turns.", "type": [ @@ -16277,6 +16421,12 @@ "TurnSteerParams": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "expectedTurnId": { "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", "type": "string" @@ -16312,6 +16462,32 @@ "title": "TurnSteerResponse", "type": "object" }, + "TurnsPage": { + "properties": { + "backwardsCursor": { + "type": [ + "string", + "null" + ] + }, + "data": { + "items": { + "$ref": "#/definitions/Turn" + }, + "type": "array" + }, + "nextCursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "type": "object" + }, "UserInput": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 63a209cc77..a82421fb01 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -460,7 +460,7 @@ "NetworkUnixSocketPermission": { "enum": [ "allow", - "none" + "deny" ], "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json index cea3dae7d2..8ba25f9a07 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json @@ -500,6 +500,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json index 529667388e..70fc43f7b8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json @@ -500,6 +500,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ListMcpServerStatusResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ListMcpServerStatusResponse.json index fc181c2702..0dc2f5e2e4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ListMcpServerStatusResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ListMcpServerStatusResponse.json @@ -10,6 +10,47 @@ ], "type": "string" }, + "McpServerInfo": { + "description": "Presentation metadata advertised by an initialized MCP server.", + "properties": { + "description": { + "type": [ + "string", + "null" + ] + }, + "icons": { + "items": true, + "type": [ + "array", + "null" + ] + }, + "name": { + "type": "string" + }, + "title": { + "type": [ + "string", + "null" + ] + }, + "version": { + "type": "string" + }, + "websiteUrl": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, "McpServerStatus": { "properties": { "authStatus": { @@ -30,6 +71,16 @@ }, "type": "array" }, + "serverInfo": { + "anyOf": [ + { + "$ref": "#/definitions/McpServerInfo" + }, + { + "type": "null" + } + ] + }, "tools": { "additionalProperties": { "$ref": "#/definitions/Tool" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json index df93fbbea5..a644ce8c4e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -644,6 +644,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetParams.json b/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetParams.json new file mode 100644 index 0000000000..9992cdf8b4 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetParams.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "AbsolutePathBuf": { + "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", + "type": "string" + } + }, + "properties": { + "extraRoots": { + "items": { + "$ref": "#/definitions/AbsolutePathBuf" + }, + "type": "array" + } + }, + "required": [ + "extraRoots" + ], + "title": "SkillsExtraRootsSetParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetResponse.json b/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetResponse.json new file mode 100644 index 0000000000..cf0792c748 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/SkillsExtraRootsSetResponse.json @@ -0,0 +1,5 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SkillsExtraRootsSetResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index a9a2529fc5..ec46130357 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -1121,6 +1121,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 8ccceaaa7c..5ace3f7af7 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index 87af03ea62..a4cc7d91ff 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index a6d86c3485..234e0867f8 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json index 58b85d41a4..364cb36617 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeParams.json @@ -983,6 +983,74 @@ "danger-full-access" ], "type": "string" + }, + "SortDirection": { + "enum": [ + "asc", + "desc" + ], + "type": "string" + }, + "ThreadResumeInitialTurnsPageParams": { + "properties": { + "itemsView": { + "anyOf": [ + { + "$ref": "#/definitions/TurnItemsView" + }, + { + "type": "null" + } + ], + "description": "How much item detail to include for each returned turn; defaults to summary." + }, + "limit": { + "description": "Optional turn page size.", + "format": "uint32", + "minimum": 0.0, + "type": [ + "integer", + "null" + ] + }, + "sortDirection": { + "anyOf": [ + { + "$ref": "#/definitions/SortDirection" + }, + { + "type": "null" + } + ], + "description": "Optional turn pagination direction; defaults to descending." + } + }, + "type": "object" + }, + "TurnItemsView": { + "oneOf": [ + { + "description": "`items` was not loaded for this turn. The field is intentionally empty.", + "enum": [ + "notLoaded" + ], + "type": "string" + }, + { + "description": "`items` contains only a display summary for this turn.", + "enum": [ + "summary" + ], + "type": "string" + }, + { + "description": "`items` contains every ThreadItem available from persisted app-server history for this turn.", + "enum": [ + "full" + ], + "type": "string" + } + ] } }, "description": "There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\n\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\n\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\n\nPrefer using thread_id whenever possible.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index b4fa181c88..59ed236c48 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -1121,6 +1121,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" @@ -1995,6 +2001,32 @@ ], "type": "string" }, + "TurnsPage": { + "properties": { + "backwardsCursor": { + "type": [ + "string", + "null" + ] + }, + "data": { + "items": { + "$ref": "#/definitions/Turn" + }, + "type": "array" + }, + "nextCursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "data" + ], + "type": "object" + }, "UserInput": { "oneOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index 4256d13ec4..7815f261c0 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 6ab655a8bc..ca52f10ca5 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -1121,6 +1121,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 91bc13a9c6..f6cb72b6b2 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index 0b68bfa957..e4e317e608 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -936,6 +936,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json index 4856f73529..6c64eb3275 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -644,6 +644,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 17b69a698e..f997976aca 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -516,6 +516,12 @@ ], "description": "Override where approval requests are routed for review on this turn and subsequent turns." }, + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "cwd": { "description": "Override the working directory for this turn and subsequent turns.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json index c5e48ae6ce..5fe9754576 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -644,6 +644,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json index 075699a34e..1db1497218 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -644,6 +644,12 @@ "oneOf": [ { "properties": { + "clientId": { + "type": [ + "string", + "null" + ] + }, "content": { "items": { "$ref": "#/definitions/UserInput" diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnSteerParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnSteerParams.json index 6f5452de66..63317f13ba 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnSteerParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnSteerParams.json @@ -218,6 +218,12 @@ } }, "properties": { + "clientUserMessageId": { + "type": [ + "string", + "null" + ] + }, "expectedTurnId": { "description": "Required active turn id precondition. The request fails when it does not match the currently active turn.", "type": "string" diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index 86ba2cd171..e19ac2dfde 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -57,6 +57,7 @@ import type { PluginUninstallParams } from "./v2/PluginUninstallParams"; import type { ReviewStartParams } from "./v2/ReviewStartParams"; import type { SendAddCreditsNudgeEmailParams } from "./v2/SendAddCreditsNudgeEmailParams"; import type { SkillsConfigWriteParams } from "./v2/SkillsConfigWriteParams"; +import type { SkillsExtraRootsSetParams } from "./v2/SkillsExtraRootsSetParams"; import type { SkillsListParams } from "./v2/SkillsListParams"; import type { ThreadApproveGuardianDeniedActionParams } from "./v2/ThreadApproveGuardianDeniedActionParams"; import type { ThreadArchiveParams } from "./v2/ThreadArchiveParams"; @@ -85,4 +86,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "skills/extraRoots/set", id: RequestId, params: SkillsExtraRootsSetParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/McpServerInfo.ts b/codex-rs/app-server-protocol/schema/typescript/McpServerInfo.ts new file mode 100644 index 0000000000..a3f6b0e142 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/McpServerInfo.ts @@ -0,0 +1,9 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { JsonValue } from "./serde_json/JsonValue"; + +/** + * Presentation metadata advertised by an initialized MCP server. + */ +export type McpServerInfo = { name: string, title: string | null, version: string, description: string | null, icons: Array | null, websiteUrl: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index 8be75af546..458d2e43b9 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -42,6 +42,7 @@ export type { InternalSessionSource } from "./InternalSessionSource"; export type { LocalShellAction } from "./LocalShellAction"; export type { LocalShellExecAction } from "./LocalShellExecAction"; export type { LocalShellStatus } from "./LocalShellStatus"; +export type { McpServerInfo } from "./McpServerInfo"; export type { MessagePhase } from "./MessagePhase"; export type { ModeKind } from "./ModeKind"; export type { NetworkPolicyAmendment } from "./NetworkPolicyAmendment"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/McpServerStatus.ts b/codex-rs/app-server-protocol/schema/typescript/v2/McpServerStatus.ts index 430494e268..d2e99ce96f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/McpServerStatus.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/McpServerStatus.ts @@ -1,9 +1,10 @@ // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { McpServerInfo } from "../McpServerInfo"; import type { Resource } from "../Resource"; import type { ResourceTemplate } from "../ResourceTemplate"; import type { Tool } from "../Tool"; import type { McpAuthStatus } from "./McpAuthStatus"; -export type McpServerStatus = { name: string, tools: { [key in string]?: Tool }, resources: Array, resourceTemplates: Array, authStatus: McpAuthStatus, }; +export type McpServerStatus = { name: string, serverInfo: McpServerInfo | null, tools: { [key in string]?: Tool }, resources: Array, resourceTemplates: Array, authStatus: McpAuthStatus, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkUnixSocketPermission.ts b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkUnixSocketPermission.ts index 466c6e5f8f..c5474cbb60 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/NetworkUnixSocketPermission.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/NetworkUnixSocketPermission.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type NetworkUnixSocketPermission = "allow" | "none"; +export type NetworkUnixSocketPermission = "allow" | "deny"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetParams.ts new file mode 100644 index 0000000000..bcddb9f6f5 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetParams.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { AbsolutePathBuf } from "../AbsolutePathBuf"; + +export type SkillsExtraRootsSetParams = { extraRoots: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetResponse.ts new file mode 100644 index 0000000000..63be08186d --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/SkillsExtraRootsSetResponse.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type SkillsExtraRootsSetResponse = Record; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts index 1b655b460e..78dff0d765 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts @@ -23,7 +23,7 @@ import type { PatchApplyStatus } from "./PatchApplyStatus"; import type { UserInput } from "./UserInput"; import type { WebSearchAction } from "./WebSearchAction"; -export type ThreadItem = { "type": "userMessage", id: string, content: Array, } | { "type": "hookPrompt", id: string, fragments: Array, } | { "type": "agentMessage", id: string, text: string, phase: MessagePhase | null, memoryCitation: MemoryCitation | null, } | { "type": "plan", id: string, text: string, } | { "type": "reasoning", id: string, summary: Array, content: Array, } | { "type": "commandExecution", id: string, +export type ThreadItem = { "type": "userMessage", id: string, clientId: string | null, content: Array, } | { "type": "hookPrompt", id: string, fragments: Array, } | { "type": "agentMessage", id: string, text: string, phase: MessagePhase | null, memoryCitation: MemoryCitation | null, } | { "type": "plan", id: string, text: string, } | { "type": "reasoning", id: string, summary: Array, content: Array, } | { "type": "commandExecution", id: string, /** * The command to be executed. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeInitialTurnsPageParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeInitialTurnsPageParams.ts new file mode 100644 index 0000000000..2dbcd97807 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadResumeInitialTurnsPageParams.ts @@ -0,0 +1,19 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SortDirection } from "./SortDirection"; +import type { TurnItemsView } from "./TurnItemsView"; + +export type ThreadResumeInitialTurnsPageParams = { +/** + * Optional turn page size. + */ +limit?: number | null, +/** + * Optional turn pagination direction; defaults to descending. + */ +sortDirection?: SortDirection | null, +/** + * How much item detail to include for each returned turn; defaults to summary. + */ +itemsView?: TurnItemsView | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts index b04919d86b..afe1ac6d94 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnStartParams.ts @@ -10,7 +10,7 @@ import type { AskForApproval } from "./AskForApproval"; import type { SandboxPolicy } from "./SandboxPolicy"; import type { UserInput } from "./UserInput"; -export type TurnStartParams = {threadId: string, input: Array, /** +export type TurnStartParams = {threadId: string, clientUserMessageId?: string | null, input: Array, /** * Override the working directory for this turn and subsequent turns. */ cwd?: string | null, /** diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnSteerParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnSteerParams.ts index dae166b401..a984f2cba8 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnSteerParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnSteerParams.ts @@ -3,7 +3,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { UserInput } from "./UserInput"; -export type TurnSteerParams = {threadId: string, input: Array, /** +export type TurnSteerParams = {threadId: string, clientUserMessageId?: string | null, input: Array, /** * Required active turn id precondition. The request fails when it does not * match the currently active turn. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnsPage.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnsPage.ts new file mode 100644 index 0000000000..e91865aeeb --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnsPage.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { Turn } from "./Turn"; + +export type TurnsPage = { data: Array, nextCursor: string | null, backwardsCursor: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 2a4220cb60..66b67fb1b4 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -344,6 +344,8 @@ export type { SkillToolDependency } from "./SkillToolDependency"; export type { SkillsChangedNotification } from "./SkillsChangedNotification"; export type { SkillsConfigWriteParams } from "./SkillsConfigWriteParams"; export type { SkillsConfigWriteResponse } from "./SkillsConfigWriteResponse"; +export type { SkillsExtraRootsSetParams } from "./SkillsExtraRootsSetParams"; +export type { SkillsExtraRootsSetResponse } from "./SkillsExtraRootsSetResponse"; export type { SkillsListEntry } from "./SkillsListEntry"; export type { SkillsListParams } from "./SkillsListParams"; export type { SkillsListResponse } from "./SkillsListResponse"; @@ -398,6 +400,7 @@ export type { ThreadRealtimeStartTransport } from "./ThreadRealtimeStartTranspor export type { ThreadRealtimeStartedNotification } from "./ThreadRealtimeStartedNotification"; export type { ThreadRealtimeTranscriptDeltaNotification } from "./ThreadRealtimeTranscriptDeltaNotification"; export type { ThreadRealtimeTranscriptDoneNotification } from "./ThreadRealtimeTranscriptDoneNotification"; +export type { ThreadResumeInitialTurnsPageParams } from "./ThreadResumeInitialTurnsPageParams"; export type { ThreadResumeParams } from "./ThreadResumeParams"; export type { ThreadResumeResponse } from "./ThreadResumeResponse"; export type { ThreadRollbackParams } from "./ThreadRollbackParams"; @@ -450,6 +453,7 @@ export type { TurnStartedNotification } from "./TurnStartedNotification"; export type { TurnStatus } from "./TurnStatus"; export type { TurnSteerParams } from "./TurnSteerParams"; export type { TurnSteerResponse } from "./TurnSteerResponse"; +export type { TurnsPage } from "./TurnsPage"; export type { UserInput } from "./UserInput"; export type { WarningNotification } from "./WarningNotification"; export type { WebSearchAction } from "./WebSearchAction"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index a8bec6b402..71c89a185c 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -610,6 +610,11 @@ client_request_definitions! { serialization: global_shared_read("config"), response: v2::SkillsListResponse, }, + SkillsExtraRootsSet => "skills/extraRoots/set" { + params: v2::SkillsExtraRootsSetParams, + serialization: global("config"), + response: v2::SkillsExtraRootsSetResponse, + }, HooksList => "hooks/list" { params: v2::HooksListParams, serialization: global("config"), @@ -1721,6 +1726,17 @@ mod tests { Some(ClientRequestSerializationScope::GlobalSharedRead("config")) ); + let skills_extra_roots_set = ClientRequest::SkillsExtraRootsSet { + request_id: request_id(), + params: v2::SkillsExtraRootsSetParams { + extra_roots: vec![absolute_path("/tmp/skills")], + }, + }; + assert_eq!( + skills_extra_roots_set.serialization_scope(), + Some(ClientRequestSerializationScope::Global("config")) + ); + let plugin_list = ClientRequest::PluginList { request_id: request_id(), params: v2::PluginListParams { diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index c0c7d55528..aa65f9ab9d 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -278,7 +278,11 @@ impl ThreadHistoryBuilder { .unwrap_or_else(|| self.new_turn(/*id*/ None)); let id = self.next_item_id(); let content = self.build_user_inputs(payload); - turn.items.push(ThreadItem::UserMessage { id, content }); + turn.items.push(ThreadItem::UserMessage { + id, + client_id: payload.client_id.clone(), + content, + }); self.current_turn = Some(turn); } @@ -1246,6 +1250,7 @@ mod tests { fn builds_multiple_turns_with_reasoning_items() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "First turn".into(), images: Some(vec!["https://example.com/one.png".into()]), text_elements: Vec::new(), @@ -1264,6 +1269,7 @@ mod tests { text: "full reasoning".into(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Second turn".into(), images: None, text_elements: Vec::new(), @@ -1292,6 +1298,7 @@ mod tests { first.items[0], ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![ UserInput::Text { text: "First turn".into(), @@ -1330,6 +1337,7 @@ mod tests { second.items[0], ThreadItem::UserMessage { id: "item-4".into(), + client_id: None, content: vec![UserInput::Text { text: "Second turn".into(), text_elements: Vec::new(), @@ -1352,6 +1360,7 @@ mod tests { let local_path = PathBuf::from("/tmp/local.png"); let events = vec![RolloutItem::EventMsg(EventMsg::UserMessage( UserMessageEvent { + client_id: None, message: "inspect these".into(), images: Some(vec!["https://example.com/image.png".into()]), image_details: vec![Some(ImageDetail::Original)], @@ -1368,6 +1377,7 @@ mod tests { turns[0].items[0], ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![ UserInput::Text { text: "inspect these".into(), @@ -1399,6 +1409,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), @@ -1410,6 +1421,7 @@ mod tests { turn_id: turn_id.to_string(), item: CoreTurnItem::UserMessage(CoreUserMessageItem { id: "user-item-id".to_string(), + client_id: None, content: Vec::new(), }), started_at_ms: 0, @@ -1434,6 +1446,7 @@ mod tests { turns[0].items[0], ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "hello".into(), text_elements: Vec::new(), @@ -1442,6 +1455,67 @@ mod tests { ); } + #[test] + fn preserves_user_message_client_id_from_legacy_event() { + let turn_id = "turn-1"; + let thread_id = ThreadId::new(); + let events = vec![ + EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + EventMsg::ItemStarted(ItemStartedEvent { + thread_id, + turn_id: turn_id.to_string(), + item: CoreTurnItem::UserMessage(CoreUserMessageItem { + id: "user-item-id".to_string(), + client_id: Some("client-message-1".to_string()), + content: vec![codex_protocol::user_input::UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + }), + started_at_ms: 0, + }), + EventMsg::UserMessage(UserMessageEvent { + client_id: Some("client-message-1".to_string()), + message: "hello".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + ..Default::default() + }), + EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: turn_id.to_string(), + last_agent_message: None, + completed_at: None, + duration_ms: None, + time_to_first_token_ms: None, + }), + ]; + + let items = events + .into_iter() + .map(RolloutItem::EventMsg) + .collect::>(); + let turns = build_turns_from_rollout_items(&items); + assert_eq!(turns.len(), 1); + assert_eq!( + turns[0].items, + vec![ThreadItem::UserMessage { + id: "item-1".into(), + client_id: Some("client-message-1".to_string()), + content: vec![UserInput::Text { + text: "hello".into(), + text_elements: Vec::new(), + }], + }] + ); + } + #[test] fn preserves_agent_message_phase_in_history() { let events = vec![EventMsg::AgentMessage(AgentMessageEvent { @@ -1478,6 +1552,7 @@ mod tests { collaboration_mode_kind: Default::default(), })), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "generate an image".into(), images: None, text_elements: Vec::new(), @@ -1515,6 +1590,7 @@ mod tests { items: vec![ ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "generate an image".into(), text_elements: Vec::new(), @@ -1536,6 +1612,7 @@ mod tests { fn splits_reasoning_when_interleaved() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Turn start".into(), images: None, text_elements: Vec::new(), @@ -1589,6 +1666,7 @@ mod tests { fn marks_turn_as_interrupted_when_aborted() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Please do the thing".into(), images: None, text_elements: Vec::new(), @@ -1607,6 +1685,7 @@ mod tests { duration_ms: None, }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Let's try again".into(), images: None, text_elements: Vec::new(), @@ -1634,6 +1713,7 @@ mod tests { first_turn.items[0], ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "Please do the thing".into(), text_elements: Vec::new(), @@ -1657,6 +1737,7 @@ mod tests { second_turn.items[0], ThreadItem::UserMessage { id: "item-3".into(), + client_id: None, content: vec![UserInput::Text { text: "Let's try again".into(), text_elements: Vec::new(), @@ -1678,6 +1759,7 @@ mod tests { fn drops_last_turns_on_thread_rollback() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "First".into(), images: None, text_elements: Vec::new(), @@ -1690,6 +1772,7 @@ mod tests { memory_citation: None, }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Second".into(), images: None, text_elements: Vec::new(), @@ -1703,6 +1786,7 @@ mod tests { }), EventMsg::ThreadRolledBack(ThreadRolledBackEvent { num_turns: 1 }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Third".into(), images: None, text_elements: Vec::new(), @@ -1732,6 +1816,7 @@ mod tests { vec![ ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "First".into(), text_elements: Vec::new(), @@ -1750,6 +1835,7 @@ mod tests { vec![ ThreadItem::UserMessage { id: "item-3".into(), + client_id: None, content: vec![UserInput::Text { text: "Third".into(), text_elements: Vec::new(), @@ -1769,6 +1855,7 @@ mod tests { fn thread_rollback_clears_all_turns_when_num_turns_exceeds_history() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "One".into(), images: None, text_elements: Vec::new(), @@ -1781,6 +1868,7 @@ mod tests { memory_citation: None, }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Two".into(), images: None, text_elements: Vec::new(), @@ -1814,6 +1902,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Start".into(), images: None, text_elements: Vec::new(), @@ -1821,6 +1910,7 @@ mod tests { ..Default::default() }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "Steer".into(), images: None, text_elements: Vec::new(), @@ -1848,6 +1938,7 @@ mod tests { vec![ ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "Start".into(), text_elements: Vec::new(), @@ -1855,6 +1946,7 @@ mod tests { }, ThreadItem::UserMessage { id: "item-2".into(), + client_id: None, content: vec![UserInput::Text { text: "Steer".into(), text_elements: Vec::new(), @@ -1875,6 +1967,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "run tools".into(), images: None, text_elements: Vec::new(), @@ -2054,6 +2147,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "run dynamic tool".into(), images: None, text_elements: Vec::new(), @@ -2121,6 +2215,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "run tools".into(), images: None, text_elements: Vec::new(), @@ -2212,6 +2307,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "review this command".into(), images: None, text_elements: Vec::new(), @@ -2297,6 +2393,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "run a subcommand".into(), images: None, text_elements: Vec::new(), @@ -2362,6 +2459,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "first".into(), images: None, text_elements: Vec::new(), @@ -2383,6 +2481,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "second".into(), images: None, text_elements: Vec::new(), @@ -2458,6 +2557,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "first".into(), images: None, text_elements: Vec::new(), @@ -2479,6 +2579,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "second".into(), images: None, text_elements: Vec::new(), @@ -2528,6 +2629,7 @@ mod tests { turns[1].items[0], ThreadItem::UserMessage { id: "item-2".into(), + client_id: None, content: vec![UserInput::Text { text: "second".into(), text_elements: Vec::new(), @@ -2549,6 +2651,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "apply patch".into(), images: None, text_elements: Vec::new(), @@ -2584,6 +2687,7 @@ mod tests { vec![ ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -2615,6 +2719,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "apply patch".into(), images: None, text_elements: Vec::new(), @@ -2652,6 +2757,7 @@ mod tests { vec![ ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -2681,6 +2787,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "first".into(), images: None, text_elements: Vec::new(), @@ -2702,6 +2809,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "second".into(), images: None, text_elements: Vec::new(), @@ -2751,6 +2859,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "first".into(), images: None, text_elements: Vec::new(), @@ -2772,6 +2881,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "second".into(), images: None, text_elements: Vec::new(), @@ -2846,6 +2956,7 @@ mod tests { fn reconstructs_collab_resume_end_item() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "resume agent".into(), images: None, text_elements: Vec::new(), @@ -2904,6 +3015,7 @@ mod tests { .expect("valid receiver thread id"); let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "spawn agent".into(), images: None, text_elements: Vec::new(), @@ -2966,6 +3078,7 @@ mod tests { .expect("valid receiver thread id"); let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "redirect".into(), images: None, text_elements: Vec::new(), @@ -3030,6 +3143,7 @@ mod tests { fn rollback_failed_error_does_not_mark_turn_failed() { let events = vec![ EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), @@ -3068,6 +3182,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), @@ -3105,6 +3220,7 @@ mod tests { items_view: TurnItemsView::Full, items: vec![ThreadItem::UserMessage { id: "item-1".into(), + client_id: None, content: vec![UserInput::Text { text: "hello".into(), text_elements: Vec::new(), @@ -3125,6 +3241,7 @@ mod tests { collaboration_mode_kind: Default::default(), }), EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), @@ -3184,6 +3301,7 @@ mod tests { collaboration_mode_kind: Default::default(), })), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index fffe213811..e30b3012ef 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -490,7 +490,7 @@ pub enum NetworkDomainPermission { #[ts(export_to = "v2/")] pub enum NetworkUnixSocketPermission { Allow, - None, + Deny, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] diff --git a/codex-rs/app-server-protocol/src/protocol/v2/item.rs b/codex-rs/app-server-protocol/src/protocol/v2/item.rs index 39e489d6aa..d68485565e 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/item.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/item.rs @@ -212,7 +212,11 @@ impl CommandAction { pub enum ThreadItem { #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] - UserMessage { id: String, content: Vec }, + UserMessage { + id: String, + client_id: Option, + content: Vec, + }, #[serde(rename_all = "camelCase")] #[ts(rename_all = "camelCase")] HookPrompt { @@ -776,6 +780,7 @@ impl From for ThreadItem { match value { CoreTurnItem::UserMessage(user) => ThreadItem::UserMessage { id: user.id, + client_id: user.client_id, content: user.content.into_iter().map(UserInput::from).collect(), }, CoreTurnItem::HookPrompt(hook_prompt) => ThreadItem::HookPrompt { diff --git a/codex-rs/app-server-protocol/src/protocol/v2/mcp.rs b/codex-rs/app-server-protocol/src/protocol/v2/mcp.rs index 31ec85a478..ae61f12b2d 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/mcp.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/mcp.rs @@ -2,6 +2,7 @@ use super::shared::v2_enum_from_core; use codex_protocol::approvals::ElicitationRequest as CoreElicitationRequest; use codex_protocol::items::McpToolCallError as CoreMcpToolCallError; use codex_protocol::mcp::CallToolResult as CoreMcpCallToolResult; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::mcp::Resource as McpResource; pub use codex_protocol::mcp::ResourceContent as McpResourceContent; use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate; @@ -53,6 +54,7 @@ pub enum McpServerStatusDetail { #[ts(export_to = "v2/")] pub struct McpServerStatus { pub name: String, + pub server_info: Option, pub tools: std::collections::HashMap, pub resources: Vec, pub resource_templates: Vec, 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 70d283994e..1b7e8ba8ff 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/plugin.rs @@ -35,6 +35,18 @@ pub struct SkillsListResponse { pub data: Vec, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct SkillsExtraRootsSetParams { + pub extra_roots: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct SkillsExtraRootsSetResponse {} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] 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 8bc01e93d9..a0be5cb15a 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -11,6 +11,7 @@ use codex_protocol::items::TurnItem; use codex_protocol::items::UserMessageItem; use codex_protocol::items::WebSearchItem; use codex_protocol::mcp::CallToolResult; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::memory_citation::MemoryCitation as CoreMemoryCitation; use codex_protocol::memory_citation::MemoryCitationEntry as CoreMemoryCitationEntry; use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile; @@ -111,6 +112,85 @@ fn thread_turns_list_params_accepts_items_view() { assert_eq!(params.items_view, Some(TurnItemsView::NotLoaded)); } +#[test] +fn thread_resume_params_accept_turns_page_bootstrap() { + let params = serde_json::from_value::(json!({ + "threadId": "thr_123", + "initialTurnsPage": { + "limit": 25, + "sortDirection": "asc", + "itemsView": "full", + }, + })) + .expect("thread resume params should deserialize"); + + assert_eq!(params.thread_id, "thr_123"); + assert_eq!( + params.initial_turns_page, + Some(ThreadResumeInitialTurnsPageParams { + limit: Some(25), + sort_direction: Some(SortDirection::Asc), + items_view: Some(TurnItemsView::Full), + }) + ); +} + +#[test] +fn thread_resume_response_round_trips_initial_turns_page() { + let response = ThreadResumeResponse { + thread: Thread { + id: "thr_123".to_string(), + session_id: "thr_123".to_string(), + forked_from_id: None, + preview: String::new(), + ephemeral: false, + model_provider: "openai".to_string(), + created_at: 1, + updated_at: 1, + status: ThreadStatus::Idle, + path: None, + cwd: absolute_path("tmp"), + cli_version: "0.0.0".to_string(), + source: SessionSource::Exec, + thread_source: None, + agent_nickname: None, + agent_role: None, + git_info: None, + name: None, + turns: Vec::new(), + }, + model: "gpt-5".to_string(), + model_provider: "openai".to_string(), + service_tier: None, + cwd: absolute_path("tmp"), + runtime_workspace_roots: Vec::new(), + instruction_sources: Vec::new(), + approval_policy: AskForApproval::OnFailure, + approvals_reviewer: ApprovalsReviewer::User, + sandbox: SandboxPolicy::DangerFullAccess, + active_permission_profile: None, + reasoning_effort: None, + initial_turns_page: Some(TurnsPage { + data: Vec::new(), + next_cursor: Some("cursor_next".to_string()), + backwards_cursor: Some("cursor_back".to_string()), + }), + }; + + let value = serde_json::to_value(&response).expect("serialize thread resume response"); + assert_eq!( + value.get("initialTurnsPage"), + Some(&json!({ + "data": [], + "nextCursor": "cursor_next", + "backwardsCursor": "cursor_back", + })) + ); + let decoded = serde_json::from_value::(value) + .expect("deserialize thread resume response"); + assert_eq!(decoded, response); +} + #[test] fn thread_turns_items_list_round_trips() { let params = ThreadTurnsItemsListParams { @@ -1676,6 +1756,7 @@ fn client_request_turn_start_granular_approval_policy_is_marked_experimental() { request_id: crate::RequestId::Integer(4), params: TurnStartParams { thread_id: "thr_123".to_string(), + client_user_message_id: None, input: Vec::new(), approval_policy: Some(AskForApproval::Granular { sandbox_approval: false, @@ -1924,6 +2005,80 @@ fn mcp_server_elicitation_response_serializes_nullable_content() { ); } +#[test] +fn mcp_server_status_serializes_absent_server_info_as_null() { + let response = ListMcpServerStatusResponse { + data: vec![McpServerStatus { + name: "not-ready".to_string(), + server_info: None, + tools: HashMap::new(), + resources: Vec::new(), + resource_templates: Vec::new(), + auth_status: McpAuthStatus::Unsupported, + }], + next_cursor: None, + }; + + assert_eq!( + serde_json::to_value(response).expect("response should serialize"), + json!({ + "data": [{ + "name": "not-ready", + "serverInfo": null, + "tools": {}, + "resources": [], + "resourceTemplates": [], + "authStatus": "unsupported", + }], + "nextCursor": null, + }) + ); +} + +#[test] +fn mcp_server_status_serializes_absent_server_info_metadata_as_null() { + let response = ListMcpServerStatusResponse { + data: vec![McpServerStatus { + name: "initialized".to_string(), + server_info: Some(McpServerInfo { + name: "lookup-server".to_string(), + title: None, + version: "1.0.0".to_string(), + description: None, + icons: None, + website_url: None, + }), + tools: HashMap::new(), + resources: Vec::new(), + resource_templates: Vec::new(), + auth_status: McpAuthStatus::Unsupported, + }], + next_cursor: None, + }; + + assert_eq!( + serde_json::to_value(response).expect("response should serialize"), + json!({ + "data": [{ + "name": "initialized", + "serverInfo": { + "name": "lookup-server", + "title": null, + "version": "1.0.0", + "description": null, + "icons": null, + "websiteUrl": null, + }, + "tools": {}, + "resources": [], + "resourceTemplates": [], + "authStatus": "unsupported", + }], + "nextCursor": null, + }) + ); +} + #[test] fn sandbox_policy_round_trips_workspace_write_access() { let v2_policy = SandboxPolicy::WorkspaceWrite { @@ -2123,7 +2278,7 @@ fn network_requirements_serializes_canonical_and_legacy_fields() { ), ( "/tmp/ignored.sock".to_string(), - NetworkUnixSocketPermission::None, + NetworkUnixSocketPermission::Deny, ), ])), allow_unix_sockets: Some(vec!["/tmp/proxy.sock".to_string()]), @@ -2147,7 +2302,7 @@ fn network_requirements_serializes_canonical_and_legacy_fields() { "allowedDomains": ["api.openai.com"], "deniedDomains": ["blocked.example.com"], "unixSockets": { - "/tmp/ignored.sock": "none", + "/tmp/ignored.sock": "deny", "/tmp/proxy.sock": "allow" }, "allowUnixSockets": ["/tmp/proxy.sock"], @@ -2160,6 +2315,7 @@ fn network_requirements_serializes_canonical_and_legacy_fields() { fn core_turn_item_into_thread_item_converts_supported_variants() { let user_item = TurnItem::UserMessage(UserMessageItem { id: "user-1".to_string(), + client_id: Some("client-message-1".to_string()), content: vec![ CoreUserInput::Text { text: "hello".to_string(), @@ -2188,6 +2344,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() { ThreadItem::from(user_item), ThreadItem::UserMessage { id: "user-1".to_string(), + client_id: Some("client-message-1".to_string()), content: vec![ UserInput::Text { text: "hello".to_string(), @@ -2469,6 +2626,27 @@ fn skills_list_params_serialization_uses_force_reload() { ); } +#[test] +fn skills_extra_roots_set_params_serialization_uses_extra_roots() { + assert_eq!( + serde_json::to_value(SkillsExtraRootsSetParams { + extra_roots: vec![absolute_path("tmp/skills")], + }) + .unwrap(), + json!({ + "extraRoots": [absolute_path_string("tmp/skills")], + }), + ); +} + +#[test] +fn skills_extra_roots_set_params_rejects_relative_roots() { + let result = serde_json::from_value::(json!({ + "extraRoots": ["relative/path"], + })); + assert!(result.is_err()); +} + #[test] fn plugin_source_serializes_local_git_and_remote_variants() { let local_path = if cfg!(windows) { @@ -3406,6 +3584,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() { assert_eq!(fork.instruction_sources, Vec::::new()); assert_eq!(start.active_permission_profile, None); assert_eq!(resume.active_permission_profile, None); + assert_eq!(resume.initial_turns_page, None); assert_eq!(fork.active_permission_profile, None); } @@ -3427,6 +3606,7 @@ fn turn_start_params_preserve_explicit_null_service_tier() { let without_override = TurnStartParams { thread_id: "thread_123".to_string(), + client_user_message_id: None, input: vec![], responsesapi_client_metadata: None, additional_context: None, 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 4971d5f4b8..8157fce69f 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/thread.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/thread.rs @@ -397,6 +397,11 @@ pub struct ThreadResumeParams { #[experimental("thread/resume.excludeTurns")] #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub exclude_turns: bool, + /// When present, include a `thread/turns/list` page in the resume response + /// so clients can bootstrap recent turns without a second request. + #[experimental("thread/resume.initialTurnsPage")] + #[ts(optional = nullable)] + pub initial_turns_page: Option, /// Deprecated and ignored by app-server. Kept only so older clients can /// continue sending the field while rollout persistence always uses the /// limited history policy. @@ -435,6 +440,44 @@ pub struct ThreadResumeResponse { #[serde(default)] pub active_permission_profile: Option, pub reasoning_effort: Option, + /// `thread/turns/list` page returned when requested by `initialTurnsPage`. + #[experimental("thread/resume.initialTurnsPage")] + #[serde(default)] + pub initial_turns_page: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ThreadResumeInitialTurnsPageParams { + /// Optional turn page size. + #[ts(optional = nullable)] + pub limit: Option, + /// Optional turn pagination direction; defaults to descending. + #[ts(optional = nullable)] + pub sort_direction: Option, + /// How much item detail to include for each returned turn; defaults to summary. + #[ts(optional = nullable)] + pub items_view: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct TurnsPage { + pub data: Vec, + pub next_cursor: Option, + pub backwards_cursor: Option, +} + +impl From for TurnsPage { + fn from(response: ThreadTurnsListResponse) -> Self { + Self { + data: response.data, + next_cursor: response.next_cursor, + backwards_cursor: response.backwards_cursor, + } + } } #[derive( diff --git a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs index ab5e59a464..f9bfe21479 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs @@ -65,6 +65,8 @@ pub struct AdditionalContextEntry { #[ts(export_to = "v2/")] pub struct TurnStartParams { pub thread_id: String, + #[ts(optional = nullable)] + pub client_user_message_id: Option, pub input: Vec, /// Optional turn-scoped Responses API client metadata. #[experimental("turn/start.responsesapiClientMetadata")] @@ -157,6 +159,8 @@ pub struct TurnStartResponse { #[ts(export_to = "v2/")] pub struct TurnSteerParams { pub thread_id: String, + #[ts(optional = nullable)] + pub client_user_message_id: Option, pub input: Vec, /// Optional turn-scoped Responses API client metadata. #[experimental("turn/steer.responsesapiClientMetadata")] diff --git a/codex-rs/app-server-test-client/src/lib.rs b/codex-rs/app-server-test-client/src/lib.rs index fd9ecc845d..e89a8dbe99 100644 --- a/codex-rs/app-server-test-client/src/lib.rs +++ b/codex-rs/app-server-test-client/src/lib.rs @@ -734,6 +734,7 @@ async fn trigger_zsh_fork_multi_cmd_approval( let mut turn_params = TurnStartParams { thread_id: thread_response.thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: message, text_elements: Vec::new(), @@ -818,6 +819,7 @@ async fn resume_message_v2( let turn_response = client.turn_start(TurnStartParams { thread_id: resume_response.thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: user_message, text_elements: Vec::new(), @@ -959,6 +961,7 @@ async fn send_message_v2_with_policies( println!("< thread/start response: {thread_response:?}"); let mut turn_params = TurnStartParams { thread_id: thread_response.thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: user_message, // Test client sends plain text without UI element ranges. @@ -999,6 +1002,7 @@ async fn send_follow_up_v2( let first_turn_params = TurnStartParams { thread_id: thread_response.thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: first_message, // Test client sends plain text without UI element ranges. @@ -1012,6 +1016,7 @@ async fn send_follow_up_v2( let follow_up_params = TurnStartParams { thread_id: thread_response.thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: follow_up_message, // Test client sends plain text without UI element ranges. @@ -1255,6 +1260,7 @@ fn live_elicitation_timeout_pause( let started_at = Instant::now(); let turn_response = client.turn_start(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: prompt, text_elements: Vec::new(), diff --git a/codex-rs/app-server-transport/src/transport/remote_control/enroll.rs b/codex-rs/app-server-transport/src/transport/remote_control/enroll.rs index 9ec6e4d004..6037caa651 100644 --- a/codex-rs/app-server-transport/src/transport/remote_control/enroll.rs +++ b/codex-rs/app-server-transport/src/transport/remote_control/enroll.rs @@ -1,18 +1,24 @@ use super::protocol::EnrollRemoteServerRequest; use super::protocol::EnrollRemoteServerResponse; +use super::protocol::RefreshRemoteServerRequest; use super::protocol::RemoteControlTarget; use axum::http::HeaderMap; use codex_api::SharedAuthProvider; use codex_login::default_client::build_reqwest_client; use codex_state::RemoteControlEnrollmentRecord; use codex_state::StateRuntime; +use serde::Serialize; +use serde::de::DeserializeOwned; use std::io; use std::io::ErrorKind; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; use tracing::info; use tracing::warn; const REMOTE_CONTROL_ENROLL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); const REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES: usize = 4096; +const REMOTE_CONTROL_SERVER_TOKEN_REFRESH_SKEW_SECS: i64 = 30; const REQUEST_ID_HEADER: &str = "x-request-id"; const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id"; @@ -26,6 +32,24 @@ pub(super) struct RemoteControlEnrollment { pub(super) environment_id: String, pub(super) server_id: String, pub(super) server_name: String, + pub(super) remote_control_token: Option, + pub(super) expires_at: Option, +} + +impl RemoteControlEnrollment { + pub(super) fn should_refresh_server_token(&self) -> bool { + self.remote_control_token.is_none() + || self.expires_at.is_none_or(|expires_at| { + expires_at.unix_timestamp() + <= OffsetDateTime::now_utc().unix_timestamp() + + REMOTE_CONTROL_SERVER_TOKEN_REFRESH_SKEW_SECS + }) + } + + pub(super) fn clear_server_token(&mut self) { + self.remote_control_token = None; + self.expires_at = None; + } } pub(super) struct RemoteControlConnectionAuth { @@ -81,6 +105,8 @@ pub(super) async fn load_persisted_remote_control_enrollment( environment_id: enrollment.environment_id, server_id: enrollment.server_id, server_name: enrollment.server_name, + remote_control_token: None, + expires_at: None, })) } None => { @@ -164,19 +190,33 @@ pub(crate) fn preview_remote_control_response_body(body: &[u8]) -> String { if trimmed.is_empty() { return "".to_string(); } - if trimmed.len() <= REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES { - return trimmed.to_string(); + let redacted = redact_remote_control_response_body(trimmed); + if redacted.len() <= REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES { + return redacted; } let mut cut = REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES; - while !trimmed.is_char_boundary(cut) { + while !redacted.is_char_boundary(cut) { cut = cut.saturating_sub(1); } - let mut truncated = trimmed[..cut].to_string(); + let mut truncated = redacted[..cut].to_string(); truncated.push_str("..."); truncated } +fn redact_remote_control_response_body(body: &str) -> String { + let Ok(mut body_json) = serde_json::from_str::(body) else { + return body.to_string(); + }; + let Some(body_object) = body_json.as_object_mut() else { + return body.to_string(); + }; + if let Some(remote_control_token) = body_object.get_mut("remote_control_token") { + *remote_control_token = serde_json::Value::String("".to_string()); + } + body_json.to_string() +} + pub(crate) fn format_headers(headers: &HeaderMap) -> String { let request_id_str = headers .get(REQUEST_ID_HEADER) @@ -204,58 +244,146 @@ pub(super) async fn enroll_remote_control_server( app_server_version: env!("CARGO_PKG_VERSION"), installation_id: installation_id.to_string(), }; + let enrollment_response = send_remote_control_server_request::<_, EnrollRemoteServerResponse>( + enroll_url, + auth, + installation_id, + &request, + "enroll", + "server enrollment", + ) + .await?; + let mut enrollment = RemoteControlEnrollment { + account_id: auth.account_id.clone(), + environment_id: enrollment_response.environment_id, + server_id: enrollment_response.server_id, + server_name: server_name.to_string(), + remote_control_token: None, + expires_at: None, + }; + update_remote_control_server_token( + &mut enrollment, + enroll_url, + enrollment_response.remote_control_token, + enrollment_response.expires_at, + )?; + Ok(enrollment) +} + +pub(super) async fn refresh_remote_control_server( + remote_control_target: &RemoteControlTarget, + auth: &RemoteControlConnectionAuth, + installation_id: &str, + enrollment: &mut RemoteControlEnrollment, +) -> io::Result<()> { + let refresh_url = &remote_control_target.refresh_url; + let request = RefreshRemoteServerRequest { + server_id: enrollment.server_id.clone(), + installation_id: installation_id.to_string(), + }; + let refreshed = send_remote_control_server_request::<_, EnrollRemoteServerResponse>( + refresh_url, + auth, + installation_id, + &request, + "refresh", + "server refresh", + ) + .await?; + if refreshed.server_id != enrollment.server_id + || refreshed.environment_id != enrollment.environment_id + { + return Err(io::Error::other(format!( + "remote control server refresh returned mismatched enrollment: expected server_id={}, environment_id={}; got server_id={}, environment_id={}", + enrollment.server_id, + enrollment.environment_id, + refreshed.server_id, + refreshed.environment_id + ))); + } + + update_remote_control_server_token( + enrollment, + refresh_url, + refreshed.remote_control_token, + refreshed.expires_at, + ) +} + +async fn send_remote_control_server_request( + url: &str, + auth: &RemoteControlConnectionAuth, + installation_id: &str, + request: &Request, + action: &str, + response_kind: &str, +) -> io::Result +where + Request: Serialize, + Response: DeserializeOwned, +{ let client = build_reqwest_client(); let mut auth_headers = HeaderMap::new(); auth.auth_provider.add_auth_headers(&mut auth_headers); - let http_request = client - .post(enroll_url) + let response = client + .post(url) .timeout(REMOTE_CONTROL_ENROLL_TIMEOUT) .headers(auth_headers) .header(REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id) .header(REMOTE_CONTROL_INSTALLATION_ID_HEADER, installation_id) - .json(&request); - - let response = http_request.send().await.map_err(|err| { - io::Error::other(format!( - "failed to enroll remote control server at `{enroll_url}`: {err}" - )) - })?; + .json(request) + .send() + .await + .map_err(|err| { + io::Error::other(format!( + "failed to {action} remote control server at `{url}`: {err}" + )) + })?; let headers = response.headers().clone(); let status = response.status(); let body = response.bytes().await.map_err(|err| { io::Error::other(format!( - "failed to read remote control enrollment response from `{enroll_url}`: {err}" + "failed to read remote control {response_kind} response from `{url}`: {err}" )) })?; let body_preview = preview_remote_control_response_body(&body); if !status.is_success() { let headers_str = format_headers(&headers); - let error_kind = if matches!(status.as_u16(), 401 | 403) { - ErrorKind::PermissionDenied - } else { - ErrorKind::Other + let error_kind = match status.as_u16() { + 401 | 403 => ErrorKind::PermissionDenied, + 404 => ErrorKind::NotFound, + _ => ErrorKind::Other, }; return Err(io::Error::new( error_kind, format!( - "remote control server enrollment failed at `{enroll_url}`: HTTP {status}, {headers_str}, body: {body_preview}" + "remote control {response_kind} failed at `{url}`: HTTP {status}, {headers_str}, body: {body_preview}" ), )); } - let enrollment = serde_json::from_slice::(&body).map_err(|err| { + serde_json::from_slice::(&body).map_err(|err| { let headers_str = format_headers(&headers); io::Error::other(format!( - "failed to parse remote control enrollment response from `{enroll_url}`: HTTP {status}, {headers_str}, body: {body_preview}, decode error: {err}" + "failed to parse remote control {response_kind} response from `{url}`: HTTP {status}, {headers_str}, body: {body_preview}, decode error: {err}" + )) + }) +} + +fn update_remote_control_server_token( + enrollment: &mut RemoteControlEnrollment, + url: &str, + token: String, + expires_at: String, +) -> io::Result<()> { + let expires_at = OffsetDateTime::parse(&expires_at, &Rfc3339).map_err(|err| { + io::Error::other(format!( + "failed to parse remote control server token expiry from `{url}`: {err}" )) })?; - - Ok(RemoteControlEnrollment { - account_id: auth.account_id.clone(), - environment_id: enrollment.environment_id, - server_id: enrollment.server_id, - server_name: server_name.to_string(), - }) + enrollment.remote_control_token = Some(token); + enrollment.expires_at = Some(expires_at); + Ok(()) } #[cfg(test)] @@ -281,6 +409,40 @@ mod tests { .expect("state runtime should initialize") } + #[test] + fn remote_control_enrollment_refreshes_server_token_before_expiry() { + let expires_soon = RemoteControlEnrollment { + account_id: "account-a".to_string(), + environment_id: "env_first".to_string(), + server_id: "srv_e_first".to_string(), + server_name: "first-server".to_string(), + remote_control_token: Some("expires-soon".to_string()), + expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(29)), + }; + let expires_later = RemoteControlEnrollment { + expires_at: Some(OffsetDateTime::now_utc() + time::Duration::seconds(31)), + remote_control_token: Some("expires-later".to_string()), + ..expires_soon.clone() + }; + + assert!(expires_soon.should_refresh_server_token()); + assert!(!expires_later.should_refresh_server_token()); + } + + #[test] + fn preview_remote_control_response_body_redacts_server_token() { + assert_eq!( + serde_json::from_str::(&preview_remote_control_response_body( + br#"{"server_id":"srv_e_test","remote_control_token":"secret"}"# + )) + .expect("redacted response preview should stay valid json"), + json!({ + "server_id": "srv_e_test", + "remote_control_token": "", + }) + ); + } + #[tokio::test] async fn persisted_remote_control_enrollment_round_trips_by_target_and_account() { let codex_home = TempDir::new().expect("temp dir should create"); @@ -295,12 +457,16 @@ mod tests { environment_id: "env_first".to_string(), server_id: "srv_e_first".to_string(), server_name: "first-server".to_string(), + remote_control_token: None, + expires_at: None, }; let second_enrollment = RemoteControlEnrollment { account_id: "account-a".to_string(), environment_id: "env_second".to_string(), server_id: "srv_e_second".to_string(), server_name: "second-server".to_string(), + remote_control_token: None, + expires_at: None, }; update_persisted_remote_control_enrollment( @@ -371,12 +537,16 @@ mod tests { environment_id: "env_first".to_string(), server_id: "srv_e_first".to_string(), server_name: "first-server".to_string(), + remote_control_token: None, + expires_at: None, }; let second_enrollment = RemoteControlEnrollment { account_id: "account-a".to_string(), environment_id: "env_second".to_string(), server_id: "srv_e_second".to_string(), server_name: "second-server".to_string(), + remote_control_token: None, + expires_at: None, }; update_persisted_remote_control_enrollment( @@ -448,7 +618,8 @@ mod tests { normalize_remote_control_url(&remote_control_url).expect("target should parse"); let enroll_url = remote_control_target.enroll_url.clone(); let response_body = json!({ - "error": "not enrolled", + "server_id": "srv_e_test", + "environment_id": "env_test", }); let expected_body = response_body.to_string(); let server_task = tokio::spawn(async move { @@ -472,7 +643,7 @@ mod tests { assert_eq!( err.to_string(), format!( - "failed to parse remote control enrollment response from `{enroll_url}`: HTTP 200 OK, request-id: , cf-ray: , body: {expected_body}, decode error: missing field `server_id` at line 1 column {}", + "failed to parse remote control server enrollment response from `{enroll_url}`: HTTP 200 OK, request-id: , cf-ray: , body: {expected_body}, decode error: missing field `remote_control_token` at line 1 column {}", expected_body.len() ) ); diff --git a/codex-rs/app-server-transport/src/transport/remote_control/protocol.rs b/codex-rs/app-server-transport/src/transport/remote_control/protocol.rs index cee646b0d9..b10af42e86 100644 --- a/codex-rs/app-server-transport/src/transport/remote_control/protocol.rs +++ b/codex-rs/app-server-transport/src/transport/remote_control/protocol.rs @@ -11,6 +11,7 @@ use url::Url; pub(super) struct RemoteControlTarget { pub(super) websocket_url: String, pub(super) enroll_url: String, + pub(super) refresh_url: String, } #[derive(Debug, Serialize)] @@ -26,6 +27,14 @@ pub(super) struct EnrollRemoteServerRequest { pub(super) struct EnrollRemoteServerResponse { pub(super) server_id: String, pub(super) environment_id: String, + pub(super) remote_control_token: String, + pub(super) expires_at: String, +} + +#[derive(Debug, Serialize)] +pub(super) struct RefreshRemoteServerRequest { + pub(super) server_id: String, + pub(super) installation_id: String, } #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -177,6 +186,9 @@ pub(super) fn normalize_remote_control_url( let enroll_url = remote_control_url .join("wham/remote/control/server/enroll") .map_err(map_url_parse_error)?; + let refresh_url = remote_control_url + .join("wham/remote/control/server/refresh") + .map_err(map_url_parse_error)?; let mut websocket_url = remote_control_url .join("wham/remote/control/server") .map_err(map_url_parse_error)?; @@ -194,6 +206,7 @@ pub(super) fn normalize_remote_control_url( Ok(RemoteControlTarget { websocket_url: websocket_url.to_string(), enroll_url: enroll_url.to_string(), + refresh_url: refresh_url.to_string(), }) } @@ -212,6 +225,8 @@ mod tests { .to_string(), enroll_url: "https://chatgpt.com/backend-api/wham/remote/control/server/enroll" .to_string(), + refresh_url: "https://chatgpt.com/backend-api/wham/remote/control/server/refresh" + .to_string(), } ); assert_eq!( @@ -224,6 +239,9 @@ mod tests { enroll_url: "https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/enroll" .to_string(), + refresh_url: + "https://api.chatgpt-staging.com/backend-api/wham/remote/control/server/refresh" + .to_string(), } ); } @@ -238,6 +256,8 @@ mod tests { .to_string(), enroll_url: "http://localhost:8080/backend-api/wham/remote/control/server/enroll" .to_string(), + refresh_url: "http://localhost:8080/backend-api/wham/remote/control/server/refresh" + .to_string(), } ); assert_eq!( @@ -248,6 +268,9 @@ mod tests { .to_string(), enroll_url: "https://localhost:8443/backend-api/wham/remote/control/server/enroll" .to_string(), + refresh_url: + "https://localhost:8443/backend-api/wham/remote/control/server/refresh" + .to_string(), } ); } diff --git a/codex-rs/app-server-transport/src/transport/remote_control/tests.rs b/codex-rs/app-server-transport/src/transport/remote_control/tests.rs index 6279072713..85bcf09222 100644 --- a/codex-rs/app-server-transport/src/transport/remote_control/tests.rs +++ b/codex-rs/app-server-transport/src/transport/remote_control/tests.rs @@ -58,6 +58,9 @@ use tokio_tungstenite::tungstenite; use tokio_util::sync::CancellationToken; const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111"; +const TEST_REMOTE_CONTROL_SERVER_TOKEN: &str = "Remote Control Token"; +const TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN: &str = "Refreshed Remote Control Token"; +const TEST_REMOTE_CONTROL_SERVER_TOKEN_EXPIRES_AT: &str = "2999-01-01T00:00:00Z"; fn remote_control_auth_manager() -> Arc { auth_manager_from_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) @@ -125,6 +128,19 @@ fn test_server_name() -> String { gethostname().to_string_lossy().trim().to_string() } +fn remote_control_server_token_response( + server_id: &str, + environment_id: &str, + remote_control_token: &str, +) -> serde_json::Value { + json!({ + "server_id": server_id, + "environment_id": environment_id, + "remote_control_token": remote_control_token, + "expires_at": TEST_REMOTE_CONTROL_SERVER_TOKEN_EXPIRES_AT, + }) +} + async fn expect_remote_control_status( status_rx: &mut watch::Receiver, expected_status: Option, @@ -203,7 +219,11 @@ async fn remote_control_transport_manages_virtual_clients_and_routes_messages() ); respond_with_json( enroll_request.stream, - json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; let mut websocket = accept_remote_control_connection(&listener).await; @@ -483,17 +503,31 @@ async fn remote_control_transport_reconnects_after_disconnect() { ); respond_with_json( enroll_request.stream, - json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; - let mut first_websocket = accept_remote_control_connection(&listener).await; + let (first_handshake_request, mut first_websocket) = + accept_remote_control_backend_connection(&listener).await; + assert_eq!( + first_handshake_request.headers.get("authorization"), + Some(&format!("Bearer {TEST_REMOTE_CONTROL_SERVER_TOKEN}")) + ); first_websocket .close(None) .await .expect("first websocket should close"); drop(first_websocket); - let mut second_websocket = accept_remote_control_connection(&listener).await; + let (second_handshake_request, mut second_websocket) = + accept_remote_control_backend_connection(&listener).await; + assert_eq!( + second_handshake_request.headers.get("authorization"), + Some(&format!("Bearer {TEST_REMOTE_CONTROL_SERVER_TOKEN}")) + ); expect_remote_control_status( &mut status_rx, /*expected_status*/ None, @@ -537,6 +571,91 @@ async fn remote_control_transport_reconnects_after_disconnect() { let _ = remote_task.await; } +#[tokio::test] +async fn remote_control_transport_refreshes_server_token_after_websocket_unauthorized() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let remote_control_url = remote_control_url_for_listener(&listener); + let codex_home = TempDir::new().expect("temp dir should create"); + let (transport_event_tx, _transport_event_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let shutdown_token = CancellationToken::new(); + let (remote_task, remote_handle) = start_remote_control( + RemoteControlStartConfig { + remote_control_url, + installation_id: TEST_INSTALLATION_ID.to_string(), + }, + Some(remote_control_state_runtime(&codex_home).await), + remote_control_auth_manager(), + transport_event_tx, + shutdown_token.clone(), + /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, + ) + .await + .expect("remote control should start"); + let mut status_rx = remote_handle.status_receiver(); + + let enroll_request = accept_http_request(&listener).await; + assert_eq!( + enroll_request.request_line, + "POST /backend-api/wham/remote/control/server/enroll HTTP/1.1" + ); + respond_with_json( + enroll_request.stream, + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; + + let websocket_request = accept_http_request(&listener).await; + assert_eq!( + websocket_request.request_line, + "GET /backend-api/wham/remote/control/server HTTP/1.1" + ); + assert_eq!( + websocket_request.headers.get("authorization"), + Some(&format!("Bearer {TEST_REMOTE_CONTROL_SERVER_TOKEN}")) + ); + respond_with_status(websocket_request.stream, "401 Unauthorized", "").await; + + let refresh_request = accept_http_request(&listener).await; + assert_eq!( + refresh_request.request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + respond_with_json( + refresh_request.stream, + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; + + let (handshake_request, _websocket) = accept_remote_control_backend_connection(&listener).await; + expect_remote_control_status( + &mut status_rx, + /*expected_status*/ None, + Some("env_test"), + ) + .await; + assert_eq!( + handshake_request.headers.get("authorization"), + Some(&format!( + "Bearer {TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN}" + )) + ); + + shutdown_token.cancel(); + let _ = remote_task.await; +} + #[tokio::test] async fn remote_control_start_allows_remote_control_invalid_url_when_disabled() { let (transport_event_tx, _transport_event_rx) = @@ -696,7 +815,11 @@ async fn remote_control_handle_enable_disable_stops_and_restarts_connections() { ); respond_with_json( enroll_request.stream, - json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; let mut first_websocket = accept_remote_control_connection(&listener).await; @@ -801,7 +924,11 @@ async fn remote_control_transport_clears_outgoing_buffer_when_backend_acks() { let enroll_request = accept_http_request(&listener).await; respond_with_json( enroll_request.stream, - json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; let mut first_websocket = accept_remote_control_connection(&listener).await; @@ -1008,7 +1135,11 @@ async fn remote_control_http_mode_enrolls_before_connecting() { ); respond_with_json( enroll_request.stream, - json!({ "server_id": "srv_e_test", "environment_id": "env_test" }), + remote_control_server_token_response( + "srv_e_test", + "env_test", + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; @@ -1026,13 +1157,13 @@ async fn remote_control_http_mode_enrolls_before_connecting() { ); assert_eq!( handshake_request.headers.get("authorization"), - Some(&"Bearer Access Token".to_string()) + Some(&format!("Bearer {TEST_REMOTE_CONTROL_SERVER_TOKEN}")) ); assert_eq!( handshake_request .headers .get(REMOTE_CONTROL_ACCOUNT_ID_HEADER), - Some(&"account_id".to_string()) + None ); assert_eq!( handshake_request @@ -1172,7 +1303,7 @@ async fn remote_control_http_mode_enrolls_before_connecting() { } #[tokio::test] -async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling() { +async fn remote_control_http_mode_refreshes_persisted_enrollment_before_connecting() { let listener = TcpListener::bind("127.0.0.1:0") .await .expect("listener should bind"); @@ -1186,6 +1317,8 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling environment_id: "env_persisted".to_string(), server_id: "srv_e_persisted".to_string(), server_name: "persisted-server".to_string(), + remote_control_token: None, + expires_at: None, }; update_persisted_remote_control_enrollment( Some(state_db.as_ref()), @@ -1215,6 +1348,33 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling .await .expect("remote control should start"); + let refresh_request = accept_http_request(&listener).await; + assert_eq!( + refresh_request.request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + assert_eq!( + refresh_request.headers.get("authorization"), + Some(&"Bearer Access Token".to_string()) + ); + assert_eq!( + serde_json::from_str::(&refresh_request.body) + .expect("refresh body should deserialize"), + json!({ + "server_id": persisted_enrollment.server_id.clone(), + "installation_id": TEST_INSTALLATION_ID, + }) + ); + respond_with_json( + refresh_request.stream, + remote_control_server_token_response( + &persisted_enrollment.server_id, + &persisted_enrollment.environment_id, + TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; + let (handshake_request, _websocket) = accept_remote_control_backend_connection(&listener).await; assert_eq!( handshake_request.path, @@ -1224,6 +1384,12 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling handshake_request.headers.get("x-codex-server-id"), Some(&persisted_enrollment.server_id) ); + assert_eq!( + handshake_request.headers.get("authorization"), + Some(&format!( + "Bearer {TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN}" + )) + ); assert_eq!( load_persisted_remote_control_enrollment( Some(state_db.as_ref()), @@ -1256,6 +1422,8 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() { environment_id: "env_persisted".to_string(), server_id: "srv_e_persisted".to_string(), server_name: "persisted-server".to_string(), + remote_control_token: None, + expires_at: None, }; update_persisted_remote_control_enrollment( Some(state_db.as_ref()), @@ -1291,6 +1459,20 @@ async fn remote_control_stdio_mode_waits_for_client_name_before_connecting() { .expect_err("remote control should wait for the stdio client name"); let _ = app_server_client_name_tx.send(app_server_client_name.to_string()); + let refresh_request = accept_http_request(&listener).await; + assert_eq!( + refresh_request.request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + respond_with_json( + refresh_request.stream, + remote_control_server_token_response( + &persisted_enrollment.server_id, + &persisted_enrollment.environment_id, + TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; let (handshake_request, _websocket) = accept_remote_control_backend_connection(&listener).await; assert_eq!( handshake_request.headers.get("x-codex-server-id"), @@ -1328,6 +1510,8 @@ async fn remote_control_waits_for_account_id_before_enrolling() { environment_id: "env_ready".to_string(), server_id: "srv_e_ready".to_string(), server_name: expected_server_name, + remote_control_token: None, + expires_at: None, }; let (transport_event_tx, _transport_event_rx) = @@ -1369,10 +1553,11 @@ async fn remote_control_waits_for_account_id_before_enrolling() { ); respond_with_json( enroll_request.stream, - json!({ - "server_id": expected_enrollment.server_id, - "environment_id": expected_enrollment.environment_id, - }), + remote_control_server_token_response( + &expected_enrollment.server_id, + &expected_enrollment.environment_id, + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; @@ -1387,7 +1572,7 @@ async fn remote_control_waits_for_account_id_before_enrolling() { } #[tokio::test] -async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() { +async fn remote_control_http_mode_reenrolls_when_refresh_reports_stale_enrollment() { let listener = TcpListener::bind("127.0.0.1:0") .await .expect("listener should bind"); @@ -1402,12 +1587,16 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() environment_id: "env_stale".to_string(), server_id: "srv_e_stale".to_string(), server_name: "stale-server".to_string(), + remote_control_token: None, + expires_at: None, }; let refreshed_enrollment = RemoteControlEnrollment { account_id: "account_id".to_string(), environment_id: "env_refreshed".to_string(), server_id: "srv_e_refreshed".to_string(), server_name: expected_server_name, + remote_control_token: None, + expires_at: None, }; update_persisted_remote_control_enrollment( Some(state_db.as_ref()), @@ -1438,6 +1627,138 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() .expect("remote control should start"); let mut status_rx = remote_handle.status_receiver(); + let refresh_request = accept_http_request(&listener).await; + assert_eq!( + refresh_request.request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + expect_remote_control_status( + &mut status_rx, + /*expected_status*/ None, + Some("env_stale"), + ) + .await; + respond_with_status(refresh_request.stream, "404 Not Found", "").await; + expect_remote_control_status( + &mut status_rx, + /*expected_status*/ None, + /*expected_environment_id*/ None, + ) + .await; + + let enroll_request = accept_http_request(&listener).await; + assert_eq!( + enroll_request.request_line, + "POST /backend-api/wham/remote/control/server/enroll HTTP/1.1" + ); + respond_with_json( + enroll_request.stream, + remote_control_server_token_response( + &refreshed_enrollment.server_id, + &refreshed_enrollment.environment_id, + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; + + let (handshake_request, _websocket) = accept_remote_control_backend_connection(&listener).await; + expect_remote_control_status( + &mut status_rx, + /*expected_status*/ None, + Some("env_refreshed"), + ) + .await; + assert_eq!( + handshake_request.headers.get("x-codex-server-id"), + Some(&refreshed_enrollment.server_id) + ); + assert_eq!( + load_persisted_remote_control_enrollment( + Some(state_db.as_ref()), + &remote_control_target, + "account_id", + /*app_server_client_name*/ None, + ) + .await + .expect("refreshed enrollment should load"), + Some(refreshed_enrollment) + ); + + shutdown_token.cancel(); + let _ = remote_task.await; +} + +#[tokio::test] +async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let remote_control_url = remote_control_url_for_listener(&listener); + let codex_home = TempDir::new().expect("temp dir should create"); + let state_db = remote_control_state_runtime(&codex_home).await; + let remote_control_target = + normalize_remote_control_url(&remote_control_url).expect("target should parse"); + let expected_server_name = gethostname().to_string_lossy().trim().to_string(); + let stale_enrollment = RemoteControlEnrollment { + account_id: "account_id".to_string(), + environment_id: "env_stale".to_string(), + server_id: "srv_e_stale".to_string(), + server_name: "stale-server".to_string(), + remote_control_token: None, + expires_at: None, + }; + let refreshed_enrollment = RemoteControlEnrollment { + account_id: "account_id".to_string(), + environment_id: "env_refreshed".to_string(), + server_id: "srv_e_refreshed".to_string(), + server_name: expected_server_name, + remote_control_token: None, + expires_at: None, + }; + update_persisted_remote_control_enrollment( + Some(state_db.as_ref()), + &remote_control_target, + "account_id", + /*app_server_client_name*/ None, + Some(&stale_enrollment), + ) + .await + .expect("stale enrollment should save"); + + let (transport_event_tx, _transport_event_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let shutdown_token = CancellationToken::new(); + let (remote_task, remote_handle) = start_remote_control( + RemoteControlStartConfig { + remote_control_url, + installation_id: TEST_INSTALLATION_ID.to_string(), + }, + Some(state_db.clone()), + remote_control_auth_manager_with_home(&codex_home), + transport_event_tx, + shutdown_token.clone(), + /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, + ) + .await + .expect("remote control should start"); + let mut status_rx = remote_handle.status_receiver(); + + let refresh_request = accept_http_request(&listener).await; + assert_eq!( + refresh_request.request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + respond_with_json( + refresh_request.stream, + remote_control_server_token_response( + &stale_enrollment.server_id, + &stale_enrollment.environment_id, + TEST_REFRESHED_REMOTE_CONTROL_SERVER_TOKEN, + ), + ) + .await; + let websocket_request = accept_http_request(&listener).await; assert_eq!( websocket_request.request_line, @@ -1468,10 +1789,11 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() ); respond_with_json( enroll_request.stream, - json!({ - "server_id": refreshed_enrollment.server_id, - "environment_id": refreshed_enrollment.environment_id, - }), + remote_control_server_token_response( + &refreshed_enrollment.server_id, + &refreshed_enrollment.environment_id, + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ), ) .await; diff --git a/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs b/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs index 95bc9d3c6f..21710b5e26 100644 --- a/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs +++ b/codex-rs/app-server-transport/src/transport/remote_control/websocket.rs @@ -7,6 +7,7 @@ use crate::transport::remote_control::enroll::enroll_remote_control_server; use crate::transport::remote_control::enroll::format_headers; use crate::transport::remote_control::enroll::load_persisted_remote_control_enrollment; use crate::transport::remote_control::enroll::preview_remote_control_response_body; +use crate::transport::remote_control::enroll::refresh_remote_control_server; use crate::transport::remote_control::enroll::update_persisted_remote_control_enrollment; use super::protocol::ClientEnvelope; @@ -55,7 +56,6 @@ use tracing::info; use tracing::warn; pub(super) const REMOTE_CONTROL_PROTOCOL_VERSION: &str = "3"; -pub(super) const REMOTE_CONTROL_ACCOUNT_ID_HEADER: &str = "chatgpt-account-id"; pub(super) const REMOTE_CONTROL_INSTALLATION_ID_HEADER: &str = "x-codex-installation-id"; const REMOTE_CONTROL_SUBSCRIBE_CURSOR_HEADER: &str = "x-codex-subscribe-cursor"; const REMOTE_CONTROL_WEBSOCKET_PING_INTERVAL: std::time::Duration = @@ -1119,7 +1119,6 @@ fn set_remote_control_header( fn build_remote_control_websocket_request( websocket_url: &str, enrollment: &RemoteControlEnrollment, - auth: &RemoteControlConnectionAuth, installation_id: &str, subscribe_cursor: Option<&str>, ) -> io::Result> { @@ -1141,10 +1140,17 @@ fn build_remote_control_websocket_request( "x-codex-protocol-version", REMOTE_CONTROL_PROTOCOL_VERSION, )?; - let mut auth_headers = tungstenite::http::HeaderMap::new(); - auth.auth_provider.add_auth_headers(&mut auth_headers); - headers.extend(auth_headers); - set_remote_control_header(headers, REMOTE_CONTROL_ACCOUNT_ID_HEADER, &auth.account_id)?; + set_remote_control_header( + headers, + "authorization", + &format!( + "Bearer {}", + enrollment + .remote_control_token + .as_deref() + .ok_or_else(|| io::Error::other("missing remote control server token"))? + ), + )?; set_remote_control_header( headers, REMOTE_CONTROL_INSTALLATION_ID_HEADER, @@ -1219,7 +1225,7 @@ fn next_reconnect_delay(reconnect_attempt: &mut u64) -> (std::time::Duration, bo pub(super) async fn connect_remote_control_websocket( remote_control_target: &RemoteControlTarget, state_db: Option<&StateRuntime>, - auth_context: RemoteControlAuthContext<'_>, + mut auth_context: RemoteControlAuthContext<'_>, enrollment: &mut Option, connect_options: RemoteControlConnectOptions<'_>, status_publisher: &RemoteControlStatusPublisher, @@ -1228,11 +1234,6 @@ pub(super) async fn connect_remote_control_websocket( tungstenite::http::Response<()>, )> { ensure_rustls_crypto_provider(); - let RemoteControlAuthContext { - auth_manager, - auth_recovery, - auth_change_rx, - } = auth_context; let Some(state_db) = state_db else { *enrollment = None; @@ -1242,7 +1243,7 @@ pub(super) async fn connect_remote_control_websocket( )); }; - let auth = match load_remote_control_auth(auth_manager).await { + let auth = match load_remote_control_auth(auth_context.auth_manager).await { Ok(auth) => auth, Err(err) => { if err.kind() == ErrorKind::PermissionDenied { @@ -1287,52 +1288,87 @@ pub(super) async fn connect_remote_control_websocket( }); } - if enrollment.is_none() { + enroll_remote_control_server_if_missing( + remote_control_target, + state_db, + &auth, + &mut auth_context, + enrollment, + connect_options, + status_publisher, + ) + .await?; + + if enrollment + .as_ref() + .ok_or_else(|| io::Error::other("missing remote control enrollment after enrollment step"))? + .should_refresh_server_token() + { + let enrollment_ref = enrollment.as_ref().ok_or_else(|| { + io::Error::other("missing remote control enrollment after enrollment step") + })?; + let server_id = enrollment_ref.server_id.clone(); + let environment_id = enrollment_ref.environment_id.clone(); + info!( - "creating new remote control enrollment: websocket_url={}, enroll_url={}, account_id={}", - remote_control_target.websocket_url, remote_control_target.enroll_url, auth.account_id + "refreshing remote control server token: websocket_url={}, refresh_url={}, account_id={}, server_id={}, environment_id={}", + remote_control_target.websocket_url, + remote_control_target.refresh_url, + auth.account_id, + server_id, + environment_id ); - let new_enrollment = match enroll_remote_control_server( + let enrollment_ref = enrollment.as_mut().ok_or_else(|| { + io::Error::other("missing remote control enrollment before server refresh") + })?; + match refresh_remote_control_server( remote_control_target, &auth, connect_options.installation_id, - connect_options.server_name, + enrollment_ref, ) .await { - Ok(new_enrollment) => new_enrollment, + Ok(()) => {} + Err(err) if err.kind() == ErrorKind::NotFound => { + info!( + "remote control server refresh returned HTTP 404; clearing stale enrollment before re-enrolling: websocket_url={}, account_id={}, server_id={}, environment_id={}", + remote_control_target.websocket_url, auth.account_id, server_id, environment_id + ); + clear_remote_control_enrollment( + state_db, + remote_control_target, + &auth.account_id, + connect_options.app_server_client_name, + enrollment, + status_publisher, + ) + .await; + enroll_remote_control_server_if_missing( + remote_control_target, + state_db, + &auth, + &mut auth_context, + enrollment, + connect_options, + status_publisher, + ) + .await?; + } Err(err) if err.kind() == ErrorKind::PermissionDenied - && recover_remote_control_auth(auth_recovery, auth_change_rx).await => + && recover_remote_control_auth( + auth_context.auth_recovery, + auth_context.auth_change_rx, + ) + .await => { return Err(io::Error::other(format!( "{err}; retrying after auth recovery" ))); } Err(err) => return Err(err), - }; - if let Err(err) = update_persisted_remote_control_enrollment( - Some(state_db), - remote_control_target, - &auth.account_id, - connect_options.app_server_client_name, - Some(&new_enrollment), - ) - .await - { - return Err(io::Error::other(format!( - "failed to persist remote control enrollment in sqlite state db: {err}" - ))); } - info!( - "created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}", - remote_control_target.websocket_url, - new_enrollment.account_id, - new_enrollment.server_id, - new_enrollment.environment_id - ); - status_publisher.publish_environment_id(Some(new_enrollment.environment_id.clone())); - *enrollment = Some(new_enrollment); } let enrollment_ref = enrollment.as_ref().ok_or_else(|| { @@ -1341,7 +1377,6 @@ pub(super) async fn connect_remote_control_websocket( let request = build_remote_control_websocket_request( &remote_control_target.websocket_url, enrollment_ref, - &auth, connect_options.installation_id, connect_options.subscribe_cursor, )?; @@ -1373,28 +1408,29 @@ pub(super) async fn connect_remote_control_websocket( enrollment_ref.server_id, enrollment_ref.environment_id ); - if let Err(clear_err) = update_persisted_remote_control_enrollment( - Some(state_db), + clear_remote_control_enrollment( + state_db, remote_control_target, &auth.account_id, connect_options.app_server_client_name, - /*enrollment*/ None, + enrollment, + status_publisher, ) - .await - { - warn!( - "failed to clear stale remote control enrollment in sqlite state db: {clear_err}" - ); - } - *enrollment = None; - status_publisher.publish_environment_id(/*environment_id*/ None); + .await; } tungstenite::Error::Http(response) - if matches!(response.status().as_u16(), 401 | 403) - && recover_remote_control_auth(auth_recovery, auth_change_rx).await => + if matches!(response.status().as_u16(), 401 | 403) => { + enrollment + .as_mut() + .ok_or_else(|| { + io::Error::other( + "missing remote control enrollment after websocket auth failure", + ) + })? + .clear_server_token(); return Err(io::Error::other(format!( - "remote control websocket auth failed with HTTP {}; retrying after auth recovery", + "remote control websocket auth failed with HTTP {}; refreshing server token before reconnect", response.status() ))); } @@ -1410,6 +1446,94 @@ pub(super) async fn connect_remote_control_websocket( } } +async fn clear_remote_control_enrollment( + state_db: &StateRuntime, + remote_control_target: &RemoteControlTarget, + account_id: &str, + app_server_client_name: Option<&str>, + enrollment: &mut Option, + status_publisher: &RemoteControlStatusPublisher, +) { + if let Err(clear_err) = update_persisted_remote_control_enrollment( + Some(state_db), + remote_control_target, + account_id, + app_server_client_name, + /*enrollment*/ None, + ) + .await + { + warn!("failed to clear stale remote control enrollment in sqlite state db: {clear_err}"); + } + *enrollment = None; + status_publisher.publish_environment_id(/*environment_id*/ None); +} + +async fn enroll_remote_control_server_if_missing( + remote_control_target: &RemoteControlTarget, + state_db: &StateRuntime, + auth: &RemoteControlConnectionAuth, + auth_context: &mut RemoteControlAuthContext<'_>, + enrollment: &mut Option, + connect_options: RemoteControlConnectOptions<'_>, + status_publisher: &RemoteControlStatusPublisher, +) -> io::Result<()> { + if enrollment.is_some() { + return Ok(()); + } + + info!( + "creating new remote control enrollment: websocket_url={}, enroll_url={}, account_id={}", + remote_control_target.websocket_url, remote_control_target.enroll_url, auth.account_id + ); + let new_enrollment = match enroll_remote_control_server( + remote_control_target, + auth, + connect_options.installation_id, + connect_options.server_name, + ) + .await + { + Ok(new_enrollment) => new_enrollment, + Err(err) + if err.kind() == ErrorKind::PermissionDenied + && recover_remote_control_auth( + auth_context.auth_recovery, + auth_context.auth_change_rx, + ) + .await => + { + return Err(io::Error::other(format!( + "{err}; retrying after auth recovery" + ))); + } + Err(err) => return Err(err), + }; + if let Err(err) = update_persisted_remote_control_enrollment( + Some(state_db), + remote_control_target, + &auth.account_id, + connect_options.app_server_client_name, + Some(&new_enrollment), + ) + .await + { + return Err(io::Error::other(format!( + "failed to persist remote control enrollment in sqlite state db: {err}" + ))); + } + info!( + "created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}", + remote_control_target.websocket_url, + new_enrollment.account_id, + new_enrollment.server_id, + new_enrollment.environment_id + ); + status_publisher.publish_environment_id(Some(new_enrollment.environment_id.clone())); + *enrollment = Some(new_enrollment); + Ok(()) +} + async fn recover_remote_control_auth( auth_recovery: &mut UnauthorizedRecovery, auth_change_rx: &mut watch::Receiver, @@ -1519,6 +1643,19 @@ mod tests { #[cfg(not(windows))] const TEST_HTTP_ACCEPT_TIMEOUT: Duration = Duration::from_secs(5); const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111"; + const TEST_REMOTE_CONTROL_SERVER_TOKEN: &str = "Remote Control Token"; + + fn remote_control_enrollment(remote_control_token: Option<&str>) -> RemoteControlEnrollment { + RemoteControlEnrollment { + account_id: "account_id".to_string(), + environment_id: "env_test".to_string(), + server_id: "srv_e_test".to_string(), + server_name: "test-server".to_string(), + remote_control_token: remote_control_token.map(str::to_string), + expires_at: remote_control_token + .map(|_| time::OffsetDateTime::now_utc() + time::Duration::hours(1)), + } + } #[test] fn next_reconnect_delay_resets_after_cap() { @@ -1670,12 +1807,9 @@ mod tests { let auth_manager = remote_control_auth_manager(); let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut auth_change_rx = auth_manager.auth_change_receiver(); - let mut enrollment = Some(RemoteControlEnrollment { - account_id: "account_id".to_string(), - environment_id: "env_test".to_string(), - server_id: "srv_e_test".to_string(), - server_name: "test-server".to_string(), - }); + let mut enrollment = Some(remote_control_enrollment(Some( + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ))); let (status_publisher, status_rx) = remote_control_status_channel(); let err = match connect_remote_control_websocket( @@ -1715,7 +1849,7 @@ mod tests { } #[tokio::test] - async fn connect_remote_control_websocket_recovers_after_unauthorized_reload() { + async fn connect_remote_control_websocket_invalidates_unauthorized_server_token() { let listener = TcpListener::bind("127.0.0.1:0") .await .expect("listener should bind"); @@ -1723,35 +1857,14 @@ mod tests { let remote_control_target = normalize_remote_control_url(&remote_control_url).expect("target should parse"); let codex_home = TempDir::new().expect("temp dir should create"); - save_auth( - codex_home.path(), - &remote_control_auth_dot_json("stale-token"), - AuthCredentialsStoreMode::File, - ) - .expect("stale auth should save"); let state_db = remote_control_state_runtime(&codex_home).await; - let auth_manager = AuthManager::shared( - codex_home.path().to_path_buf(), - /*enable_codex_api_key_env*/ false, - AuthCredentialsStoreMode::File, - /*chatgpt_base_url*/ None, - ) - .await; + let auth_manager = remote_control_auth_manager(); let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut auth_change_rx = auth_manager.auth_change_receiver(); - let mut enrollment = Some(RemoteControlEnrollment { - account_id: "account_id".to_string(), - environment_id: "env_test".to_string(), - server_id: "srv_e_test".to_string(), - server_name: "test-server".to_string(), - }); + let mut enrollment = Some(remote_control_enrollment(Some( + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ))); let (status_publisher, status_rx) = remote_control_status_channel(); - save_auth( - codex_home.path(), - &remote_control_auth_dot_json("fresh-token"), - AuthCredentialsStoreMode::File, - ) - .expect("fresh auth should save"); let server_task = tokio::spawn(async move { let (stream, request_line) = accept_http_request(&listener).await; @@ -1794,22 +1907,13 @@ mod tests { ); assert_eq!( err.to_string(), - "remote control websocket auth failed with HTTP 401 Unauthorized; retrying after auth recovery" + "remote control websocket auth failed with HTTP 401 Unauthorized; refreshing server token before reconnect" ); assert_eq!( - auth_manager - .auth() - .await - .expect("auth should remain available") - .get_token() - .expect("token should be readable"), - "fresh-token" - ); - assert!( - !auth_change_rx - .has_changed() - .expect("auth change watch should remain open"), - "recovery's own auth reload should not wake the reconnect loop" + enrollment, + Some(remote_control_enrollment( + /*remote_control_token*/ None + )) ); } @@ -1905,6 +2009,104 @@ mod tests { ); } + #[tokio::test] + async fn connect_remote_control_websocket_recovers_after_unauthorized_refresh() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let remote_control_url = remote_control_url_for_listener(&listener); + let remote_control_target = + normalize_remote_control_url(&remote_control_url).expect("target should parse"); + let refresh_url = remote_control_target.refresh_url.clone(); + let server_task = tokio::spawn(async move { + let (stream, request_line) = accept_http_request(&listener).await; + assert_eq!( + request_line, + "POST /backend-api/wham/remote/control/server/refresh HTTP/1.1" + ); + respond_with_status_and_headers(stream, "401 Unauthorized", &[], "unauthorized").await; + }); + let codex_home = TempDir::new().expect("temp dir should create"); + save_auth( + codex_home.path(), + &remote_control_auth_dot_json("stale-token"), + AuthCredentialsStoreMode::File, + ) + .expect("stale auth should save"); + let state_db = remote_control_state_runtime(&codex_home).await; + let auth_manager = AuthManager::shared( + codex_home.path().to_path_buf(), + /*enable_codex_api_key_env*/ false, + AuthCredentialsStoreMode::File, + /*chatgpt_base_url*/ None, + ) + .await; + let mut auth_recovery = auth_manager.unauthorized_recovery(); + let mut auth_change_rx = auth_manager.auth_change_receiver(); + let mut enrollment = Some(remote_control_enrollment( + /*remote_control_token*/ None, + )); + let (status_publisher, status_rx) = remote_control_status_channel(); + save_auth( + codex_home.path(), + &remote_control_auth_dot_json("fresh-token"), + AuthCredentialsStoreMode::File, + ) + .expect("fresh auth should save"); + + let err = connect_remote_control_websocket( + &remote_control_target, + Some(state_db.as_ref()), + RemoteControlAuthContext { + auth_manager: &auth_manager, + auth_recovery: &mut auth_recovery, + auth_change_rx: &mut auth_change_rx, + }, + &mut enrollment, + RemoteControlConnectOptions { + installation_id: TEST_INSTALLATION_ID, + server_name: "test-server", + subscribe_cursor: None, + app_server_client_name: None, + }, + &status_publisher, + ) + .await + .expect_err("unauthorized refresh should fail the websocket connect"); + + server_task.await.expect("server task should succeed"); + assert_eq!( + status_rx.borrow().clone(), + RemoteControlStatusChangedNotification { + status: RemoteControlConnectionStatus::Connecting, + server_name: "test-server".to_string(), + installation_id: TEST_INSTALLATION_ID.to_string(), + environment_id: Some("env_test".to_string()), + } + ); + assert_eq!( + err.to_string(), + format!( + "remote control server refresh failed at `{refresh_url}`: HTTP 401 Unauthorized, request-id: , cf-ray: , body: unauthorized; retrying after auth recovery" + ) + ); + assert_eq!( + auth_manager + .auth() + .await + .expect("auth should remain available") + .get_token() + .expect("token should be readable"), + "fresh-token" + ); + assert!( + !auth_change_rx + .has_changed() + .expect("auth change watch should remain open"), + "recovery's own auth reload should not wake the reconnect loop" + ); + } + #[tokio::test] async fn connect_remote_control_websocket_requires_sqlite_state_db() { let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/") @@ -1912,12 +2114,9 @@ mod tests { let auth_manager = remote_control_auth_manager(); let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut auth_change_rx = auth_manager.auth_change_receiver(); - let mut enrollment = Some(RemoteControlEnrollment { - account_id: "account_id".to_string(), - environment_id: "env_test".to_string(), - server_id: "srv_e_test".to_string(), - server_name: "test-server".to_string(), - }); + let mut enrollment = Some(remote_control_enrollment(Some( + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ))); let (status_publisher, _status_rx) = remote_control_status_channel(); let err = connect_remote_control_websocket( @@ -1960,12 +2159,9 @@ mod tests { .await; let mut auth_recovery = auth_manager.unauthorized_recovery(); let mut auth_change_rx = auth_manager.auth_change_receiver(); - let mut enrollment = Some(RemoteControlEnrollment { - account_id: "account_id".to_string(), - environment_id: "env_test".to_string(), - server_id: "srv_e_test".to_string(), - server_name: "test-server".to_string(), - }); + let mut enrollment = Some(remote_control_enrollment(Some( + TEST_REMOTE_CONTROL_SERVER_TOKEN, + ))); let (status_publisher, mut status_rx) = remote_control_status_channel(); status_publisher.publish_environment_id(Some("env_test".to_string())); status_rx diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 09e3197b77..d1a69783ad 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -54,6 +54,7 @@ codex-backend-client = { workspace = true } codex-file-search = { workspace = true } codex-chatgpt = { workspace = true } codex-login = { workspace = true } +codex-image-generation-extension = { workspace = true } codex-memories-extension = { workspace = true } codex-web-search-extension = { workspace = true } codex-memories-write = { workspace = true } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 88edc22f9e..2bf6035b27 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -23,7 +23,7 @@ Similar to [MCP](https://modelcontextprotocol.io/), `codex app-server` supports Supported transports: -- stdio (`--listen stdio://`, default): newline-delimited JSON (JSONL) +- stdio (`--stdio` or `--listen stdio://`, default): newline-delimited JSON (JSONL) - websocket (`--listen ws://IP:PORT`): one JSON-RPC message per websocket text frame (**experimental / unsupported**) - unix socket (`--listen unix://` or `--listen unix://PATH`): websocket connections over `$CODEX_HOME/app-server-control/app-server-control.sock` or a custom socket path, using the standard HTTP Upgrade handshake - off (`--listen off`): do not expose a local transport @@ -158,9 +158,9 @@ Example with notification opt-out: - `thread/shellCommand` — run a user-initiated `!` shell command against a thread; this runs unsandboxed with full access rather than inheriting the thread sandbox policy. Returns `{}` immediately while progress streams through standard turn/item notifications and any active turn receives the formatted output in its message stream. - `thread/backgroundTerminals/clean` — terminate all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`); returns `{}` when the cleanup request is accepted. - `thread/rollback` — drop the last N turns from the agent’s in-memory context and persist a rollback marker in the rollout so future resumes see the pruned history; returns the updated `thread` (with `turns` populated) on success. -- `turn/start` — add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. Experimental `runtimeWorkspaceRoots` replaces the thread-scoped runtime workspace roots used to materialize `:workspace_roots`; relative paths resolve against the effective turn cwd. Prefer experimental `permissions` profile selection by id for permission overrides; the legacy `sandboxPolicy` field is still accepted but cannot be combined with `permissions`. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". +- `turn/start` — add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. `clientUserMessageId` is optional; when supplied, the corresponding `userMessage` item echoes it as `clientId`. Experimental `runtimeWorkspaceRoots` replaces the thread-scoped runtime workspace roots used to materialize `:workspace_roots`; relative paths resolve against the effective turn cwd. Prefer experimental `permissions` profile selection by id for permission overrides; the legacy `sandboxPolicy` field is still accepted but cannot be combined with `permissions`. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode". - `thread/inject_items` — append raw Responses API items to a loaded thread’s model-visible history without starting a user turn; returns `{}` on success. -- `turn/steer` — add user input to an already in-flight regular turn without starting a new turn; returns the active `turnId` that accepted the input. Review and manual compaction turns reject `turn/steer`. +- `turn/steer` — add user input to an already in-flight regular turn without starting a new turn; returns the active `turnId` that accepted the input. `clientUserMessageId` is optional; when supplied, the corresponding `userMessage` item echoes it as `clientId`. Review and manual compaction turns reject `turn/steer`. - `turn/interrupt` — request cancellation of an in-flight turn by `(thread_id, turn_id)`; success is an empty `{}` response and the turn finishes with `status: "interrupted"`. - `thread/realtime/start` — start a thread-scoped realtime session (experimental); pass `outputModality: "text"` or `outputModality: "audio"` to choose model output, returns `{}` and streams `thread/realtime/*` notifications. Omit `transport` for the websocket transport, or pass `{ "type": "webrtc", "sdp": "..." }` to create a WebRTC session from a browser-generated SDP offer; the remote answer SDP is emitted as `thread/realtime/sdp`. - `thread/realtime/appendAudio` — append an input audio chunk to the active realtime session (experimental); returns `{}`. @@ -196,6 +196,7 @@ Example with notification opt-out: - `environment/add` — experimental; add or replace a named remote environment by `environmentId` and `execServerUrl` for later selection by `thread/start` or `turn/start`; returns `{}` and does not change the default environment. - `collaborationMode/list` — list available collaboration mode presets (experimental, no pagination). Built-in presets do not select a model; the Plan preset selects medium reasoning effort. This response omits built-in developer instructions; clients should either pass `settings.developer_instructions: null` when setting a mode to use Codex's built-in instructions, or provide their own instructions explicitly. - `skills/list` — list skills for one or more `cwd` values (optional `forceReload`). +- `skills/extraRoots/set` — replace the app-server process runtime extra standalone skill roots. The roots are not persisted; missing directories are accepted and simply load no skills. - `hooks/list` — list discovered hooks for one or more `cwd` values. - `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. @@ -216,7 +217,7 @@ Example with notification opt-out: - `mcpServer/oauth/login` — start an OAuth login for a configured MCP server; returns an `authorization_url` and later emits `mcpServer/oauthLogin/completed` once the browser flow finishes. - `tool/requestUserInput` — prompt the user with 1–3 short questions for a tool call and return their answers (experimental). - `config/mcpServer/reload` — reload MCP server config from disk and queue a refresh for loaded threads (applied on each thread's next active turn); returns `{}`. Use this after editing `config.toml` without restarting the server. -- `mcpServerStatus/list` — enumerate configured MCP servers with their tools and auth status, plus resources/resource templates for `full` detail; supports optional `threadId` and cursor+limit pagination. If `threadId` is omitted, the server reads from the latest global config directly. If `detail` is omitted, the server defaults to `full`. +- `mcpServerStatus/list` — enumerate configured MCP servers with their tools, auth status, server info, plus resources/resource templates for `full` detail; supports optional `threadId` and cursor+limit pagination. If `threadId` is omitted, the server reads from the latest global config directly. If `detail` is omitted, the server defaults to `full`. - `mcpServer/resource/read` — read a resource from a configured MCP server by optional `threadId`, `server`, and `uri`, returning text/blob resource `contents`. If `threadId` is omitted, the server reads from the latest MCP config directly. - `mcpServer/tool/call` — call a tool on a thread's configured MCP server by `threadId`, `server`, `tool`, optional `arguments`, and optional `_meta`, returning the MCP tool result. - `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); accepts an optional absolute `cwd` to target setup for a specific workspace, returns `{ started: true }` immediately, and later emits `windowsSandbox/setupCompleted`. @@ -281,6 +282,8 @@ To continue a stored session, call `thread/resume` with the `thread.id` you prev By default, `thread/resume` includes the reconstructed turn history in `thread.turns`. Experimental clients can pass `excludeTurns: true` to return only thread metadata and live resume state, then call `thread/turns/list` separately if they want to page the turn history over the network. In that mode the server also skips replaying restored `thread/tokenUsage/updated`, which avoids rebuilding turns just to attribute historical usage. +Experimental clients that want the live resume subscription plus a turns page in one round trip can pass `initialTurnsPage`. It accepts the same `limit`, `sortDirection`, and `itemsView` controls as `thread/turns/list`; omitted controls use its defaults. The response includes `initialTurnsPage` with `nextCursor` and `backwardsCursor` for follow-up pagination. + By default, resume uses the latest persisted `model` and `reasoningEffort` values associated with the thread. Supplying any of `model`, `modelProvider`, `config.model`, or `config.model_reasoning_effort` disables that persisted fallback and uses the explicit overrides plus normal config resolution instead. Example: @@ -297,6 +300,24 @@ Example: "excludeTurns": true } } { "id": 12, "result": { "thread": { "id": "thr_123", "turns": [], … } } } + +{ "method": "thread/resume", "id": 13, "params": { + "threadId": "thr_123", + "excludeTurns": true, + "initialTurnsPage": { + "limit": 20, + "sortDirection": "desc", + "itemsView": "summary" + } +} } +{ "id": 13, "result": { + "thread": { "id": "thr_123", "turns": [], … }, + "initialTurnsPage": { + "data": [ ... ], + "nextCursor": "older-turns-cursor-or-null", + "backwardsCursor": "newer-turns-cursor-or-null" + } +} } ``` To branch from a stored session, call `thread/fork` with the `thread.id`. This creates a new thread id and emits a `thread/started` notification for it. The returned `thread.sessionId` identifies the current live session tree root. Root threads use their own `thread.id` as `thread.sessionId`; stored threads that are not loaded also report their own `thread.id`, because resuming one makes it the root of a new live session tree. When the source history includes persisted token usage, the server also emits `thread/tokenUsage/updated` for the new thread immediately after the response. If the source thread is actively running, the fork snapshots it as if the current turn had been interrupted first. Pass `ephemeral: true` when the fork should stay in-memory only: @@ -642,6 +663,7 @@ You can optionally specify config overrides on the new turn. If specified, these ```json { "method": "turn/start", "id": 30, "params": { "threadId": "thr_123", + "clientUserMessageId": "client_msg_123", "input": [ { "type": "text", "text": "Run tests" } ], // Below are optional config overrides "cwd": "/Users/me/project", @@ -840,6 +862,7 @@ not emit `turn/started` and does not accept thread settings overrides. ```json { "method": "turn/steer", "id": 32, "params": { "threadId": "thr_123", + "clientUserMessageId": "client_msg_124", "input": [ { "type": "text", "text": "Actually focus on failing tests first." } ], "expectedTurnId": "turn_456" } } @@ -1225,7 +1248,7 @@ Today both notifications carry an empty `items` array even when item events were `ThreadItem` is the tagged union carried in turn responses and `item/*` notifications. Currently we support events for the following items: -- `userMessage` — `{id, content}` where `content` is a list of user inputs (`text`, `image`, or `localImage`). +- `userMessage` — `{id, clientId, content}` where `clientId` is the optional `clientUserMessageId` supplied to `turn/start` or `turn/steer`, and `content` is a list of user inputs (`text`, `image`, or `localImage`). - `agentMessage` — `{id, text}` containing the accumulated agent reply. - `plan` — `{id, text}` emitted for plan-mode turns; plan text can stream via `item/plan/delta` (experimental). - `reasoning` — `{id, summary, content}` where `summary` holds streamed reasoning summaries (applicable for most OpenAI models) and `content` holds raw reasoning blocks (applicable for e.g. open source models). @@ -1484,6 +1507,7 @@ $skill-creator Add a new skill for triaging flaky CI and include step-by-step us Use `skills/list` to fetch the available skills (optionally scoped by `cwds`, with `forceReload`). `skills/list` might reuse a cached skills result per `cwd`; setting `forceReload` to `true` refreshes the result from disk. The server also emits `skills/changed` notifications when watched local skill files change. Treat this as an invalidation signal and re-run `skills/list` with your current params when needed. +Use `skills/extraRoots/set` to replace additional standalone skill roots for the current app-server process. These roots use the same layout as other standalone skill roots: each root contains skill directories, and each skill directory contains `SKILL.md`. Missing roots are accepted and load no skills until they exist. This setting is lost when app-server exits. ```json { "method": "skills/list", "id": 25, "params": { @@ -1520,12 +1544,23 @@ The server also emits `skills/changed` notifications when watched local skill fi } ``` +```json +{ + "method": "skills/extraRoots/set", + "id": 26, + "params": { + "extraRoots": ["/Users/me/generated-skills"] + } +} +{ "id": 26, "result": {} } +``` + To enable or disable a skill by absolute path: ```json { "method": "skills/config/write", - "id": 26, + "id": 27, "params": { "path": "/Users/alice/.codex/skills/skill-creator/SKILL.md", "name": null, @@ -1539,7 +1574,7 @@ To enable or disable a skill by name: ```json { "method": "skills/config/write", - "id": 27, + "id": 28, "params": { "path": null, "name": "github:yeet", diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 5f784ea23a..fd220ae86d 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -2153,6 +2153,7 @@ mod tests { let created_at = Utc::now(); let history_items = vec![ RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "before rollback".to_string(), images: None, local_images: Vec::new(), @@ -3228,6 +3229,7 @@ mod tests { state.track_current_turn_event( "turn-1", &EventMsg::UserMessage(codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "already tracked".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/app-server/src/command_exec.rs b/codex-rs/app-server/src/command_exec.rs index 443117e592..2f62f099e9 100644 --- a/codex-rs/app-server/src/command_exec.rs +++ b/codex-rs/app-server/src/command_exec.rs @@ -697,12 +697,13 @@ mod tests { let cwd = AbsolutePathBuf::current_dir().expect("current dir"); ExecRequest::new( vec!["cmd".to_string()], - cwd, + cwd.clone(), HashMap::new(), /*network*/ None, ExecExpiration::DefaultTimeout, codex_core::exec::ExecCapturePolicy::ShellTool, SandboxType::WindowsRestrictedToken, + vec![cwd], WindowsSandboxLevel::Disabled, /*windows_sandbox_private_desktop*/ false, PermissionProfile::read_only(), @@ -819,6 +820,7 @@ mod tests { ExecExpiration::Cancellation(CancellationToken::new()), codex_core::exec::ExecCapturePolicy::ShellTool, SandboxType::None, + vec![cwd.clone()], WindowsSandboxLevel::Disabled, /*windows_sandbox_private_desktop*/ false, PermissionProfile::read_only(), @@ -887,6 +889,7 @@ mod tests { }; let cancellation = CancellationToken::new(); let cancel = cancellation.clone(); + let cwd = AbsolutePathBuf::current_dir().expect("current dir"); manager .start(StartCommandExecParams { @@ -898,7 +901,7 @@ mod tests { process_id: Some("proc-101".to_string()), exec_request: ExecRequest::new( vec!["sh".to_string(), "-lc".to_string(), "sleep 30".to_string()], - AbsolutePathBuf::current_dir().expect("current dir"), + cwd.clone(), HashMap::new(), /*network*/ None, ExecExpiration::TimeoutOrCancellation { @@ -907,6 +910,7 @@ mod tests { }, codex_core::exec::ExecCapturePolicy::ShellTool, SandboxType::None, + vec![cwd], WindowsSandboxLevel::Disabled, /*windows_sandbox_private_desktop*/ false, PermissionProfile::read_only(), diff --git a/codex-rs/app-server/src/extensions.rs b/codex-rs/app-server/src/extensions.rs index 1246da7b37..7b2673ca06 100644 --- a/codex-rs/app-server/src/extensions.rs +++ b/codex-rs/app-server/src/extensions.rs @@ -31,7 +31,8 @@ where let mut builder = ExtensionRegistryBuilder::::with_event_sink(event_sink); codex_guardian::install(&mut builder, guardian_agent_spawner); codex_memories_extension::install(&mut builder, codex_otel::global()); - codex_web_search_extension::install(&mut builder, auth_manager); + codex_web_search_extension::install(&mut builder, auth_manager.clone()); + codex_image_generation_extension::install(&mut builder, auth_manager); Arc::new(builder.build()) } diff --git a/codex-rs/app-server/src/fs_watch.rs b/codex-rs/app-server/src/fs_watch.rs index 09c6dc5533..405b0560a3 100644 --- a/codex-rs/app-server/src/fs_watch.rs +++ b/codex-rs/app-server/src/fs_watch.rs @@ -8,66 +8,24 @@ use codex_app_server_protocol::FsWatchParams; use codex_app_server_protocol::FsWatchResponse; use codex_app_server_protocol::JSONRPCErrorError; use codex_app_server_protocol::ServerNotification; +use codex_file_watcher::DebouncedWatchReceiver; use codex_file_watcher::FileWatcher; -use codex_file_watcher::FileWatcherEvent; use codex_file_watcher::FileWatcherSubscriber; -use codex_file_watcher::Receiver; use codex_file_watcher::WatchPath; use codex_file_watcher::WatchRegistration; use std::collections::HashMap; -use std::collections::HashSet; use std::collections::hash_map::Entry; use std::hash::Hash; -use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use tokio::sync::Mutex as AsyncMutex; #[cfg(test)] use tokio::sync::mpsc; use tokio::sync::oneshot; -use tokio::time::Instant; use tracing::warn; const FS_CHANGED_NOTIFICATION_DEBOUNCE: Duration = Duration::from_millis(200); -struct DebouncedReceiver { - rx: Receiver, - interval: Duration, - changed_paths: HashSet, - next_allowance: Option, -} - -impl DebouncedReceiver { - fn new(rx: Receiver, interval: Duration) -> Self { - Self { - rx, - interval, - changed_paths: HashSet::new(), - next_allowance: None, - } - } - - async fn recv(&mut self) -> Option { - while self.changed_paths.is_empty() { - self.changed_paths.extend(self.rx.recv().await?.paths); - } - let next_allowance = *self - .next_allowance - .get_or_insert_with(|| Instant::now() + self.interval); - - loop { - tokio::select! { - event = self.rx.recv() => self.changed_paths.extend(event?.paths), - _ = tokio::time::sleep_until(next_allowance) => break, - } - } - - Some(FileWatcherEvent { - paths: self.changed_paths.drain().collect(), - }) - } -} - #[derive(Clone)] pub(crate) struct FsWatchManager { outgoing: Arc, @@ -151,7 +109,7 @@ impl FsWatchManager { let task_watch_id = watch_id.clone(); tokio::spawn(async move { - let mut rx = DebouncedReceiver::new(rx, FS_CHANGED_NOTIFICATION_DEBOUNCE); + let mut rx = DebouncedWatchReceiver::new(rx, FS_CHANGED_NOTIFICATION_DEBOUNCE); tokio::pin!(terminate_rx); loop { let event = tokio::select! { @@ -219,6 +177,8 @@ mod tests { use super::*; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; + use std::collections::HashSet; + use std::path::PathBuf; use tempfile::TempDir; fn absolute_path(path: PathBuf) -> AbsolutePathBuf { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 33b9c56d4a..2dbd17a3d7 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -354,6 +354,8 @@ impl MessageProcessor { app_list_shutdown_token, ); let catalog_processor = CatalogRequestProcessor::new( + outgoing.clone(), + Arc::clone(&skills_watcher), auth_manager.clone(), Arc::clone(&thread_manager), Arc::clone(&config), @@ -1108,6 +1110,9 @@ impl MessageProcessor { ClientRequest::SkillsList { params, .. } => { self.catalog_processor.skills_list(params).await } + ClientRequest::SkillsExtraRootsSet { params, .. } => { + self.catalog_processor.skills_extra_roots_set(params).await + } ClientRequest::HooksList { params, .. } => { self.catalog_processor.hooks_list(params).await } diff --git a/codex-rs/app-server/src/message_processor_tracing_tests.rs b/codex-rs/app-server/src/message_processor_tracing_tests.rs index 97c497b877..94b5a1af27 100644 --- a/codex-rs/app-server/src/message_processor_tracing_tests.rs +++ b/codex-rs/app-server/src/message_processor_tracing_tests.rs @@ -653,6 +653,7 @@ async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> { params: TurnStartParams { environments: None, thread_id, + client_user_message_id: None, input: vec![UserInput::Text { text: "hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index 66ab8e3a1d..a110b73191 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -156,6 +156,8 @@ use codex_app_server_protocol::ServerRequestResolvedNotification; use codex_app_server_protocol::SkillSummary; use codex_app_server_protocol::SkillsConfigWriteParams; use codex_app_server_protocol::SkillsConfigWriteResponse; +use codex_app_server_protocol::SkillsExtraRootsSetParams; +use codex_app_server_protocol::SkillsExtraRootsSetResponse; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::SortDirection; @@ -213,6 +215,7 @@ use codex_app_server_protocol::ThreadRealtimeStartResponse; use codex_app_server_protocol::ThreadRealtimeStartTransport; use codex_app_server_protocol::ThreadRealtimeStopParams; use codex_app_server_protocol::ThreadRealtimeStopResponse; +use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams; use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadRollbackParams; diff --git a/codex-rs/app-server/src/request_processors/catalog_processor.rs b/codex-rs/app-server/src/request_processors/catalog_processor.rs index ba6c535665..6f17e4614f 100644 --- a/codex-rs/app-server/src/request_processors/catalog_processor.rs +++ b/codex-rs/app-server/src/request_processors/catalog_processor.rs @@ -4,6 +4,8 @@ use futures::StreamExt; #[derive(Clone)] pub(crate) struct CatalogRequestProcessor { + pub(super) outgoing: Arc, + pub(super) skills_watcher: Arc, pub(super) auth_manager: Arc, pub(super) thread_manager: Arc, pub(super) config: Arc, @@ -96,6 +98,8 @@ fn errors_to_info( impl CatalogRequestProcessor { pub(crate) fn new( + outgoing: Arc, + skills_watcher: Arc, auth_manager: Arc, thread_manager: Arc, config: Arc, @@ -103,6 +107,8 @@ impl CatalogRequestProcessor { workspace_settings_cache: Arc, ) -> Self { Self { + outgoing, + skills_watcher, auth_manager, thread_manager, config, @@ -138,6 +144,15 @@ impl CatalogRequestProcessor { .map(|response| Some(response.into())) } + pub(crate) async fn skills_extra_roots_set( + &self, + params: SkillsExtraRootsSetParams, + ) -> Result, JSONRPCErrorError> { + self.skills_extra_roots_set_response(params) + .await + .map(|response| Some(response.into())) + } + pub(crate) async fn model_list( &self, params: ModelListParams, @@ -567,6 +582,24 @@ impl CatalogRequestProcessor { Ok(SkillsListResponse { data }) } + async fn skills_extra_roots_set_response( + &self, + params: SkillsExtraRootsSetParams, + ) -> Result { + let SkillsExtraRootsSetParams { extra_roots } = params; + self.skills_watcher + .register_runtime_extra_roots(&extra_roots); + self.thread_manager + .skills_manager() + .set_extra_roots(extra_roots); + self.outgoing + .send_server_notification(ServerNotification::SkillsChanged( + codex_app_server_protocol::SkillsChangedNotification {}, + )) + .await; + Ok(SkillsExtraRootsSetResponse {}) + } + /// Handle `hooks/list` by resolving hooks for each requested cwd. async fn hooks_list_response( &self, diff --git a/codex-rs/app-server/src/request_processors/command_exec_processor.rs b/codex-rs/app-server/src/request_processors/command_exec_processor.rs index 930cc6d18f..5b14f0b0c0 100644 --- a/codex-rs/app-server/src/request_processors/command_exec_processor.rs +++ b/codex-rs/app-server/src/request_processors/command_exec_processor.rs @@ -203,6 +203,7 @@ impl CommandExecRequestProcessor { network_proxy_spec, network_proxy_permission_profile, managed_network_requirements_enabled, + windows_sandbox_workspace_roots, ) = if let Some(permission_profile) = permission_profile { let overrides = ConfigOverrides { cwd: Some(cwd.to_path_buf()), @@ -230,6 +231,7 @@ impl CommandExecRequestProcessor { config.permissions.network.clone(), config.permissions.permission_profile().clone(), config.managed_network_requirements_enabled(), + config.effective_workspace_roots(), ) } else if let Some(policy) = sandbox_policy.map(|policy| policy.to_core()) { self.config @@ -255,6 +257,7 @@ impl CommandExecRequestProcessor { self.config.permissions.network.clone(), self.config.permissions.permission_profile().clone(), self.config.managed_network_requirements_enabled(), + self.config.effective_workspace_roots(), ) } else { ( @@ -262,6 +265,7 @@ impl CommandExecRequestProcessor { self.config.permissions.network.clone(), self.config.permissions.permission_profile().clone(), self.config.managed_network_requirements_enabled(), + self.config.effective_workspace_roots(), ) }; let started_network_proxy = match network_proxy_spec.as_ref() { @@ -318,6 +322,7 @@ impl CommandExecRequestProcessor { exec_params, &effective_permission_profile, &sandbox_cwd, + windows_sandbox_workspace_roots.as_slice(), &codex_linux_sandbox_exe, use_legacy_landlock, ) diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index 39dbd17fe6..5ba6d02ecb 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -611,7 +611,7 @@ fn map_network_unix_socket_permission_to_api( ) -> NetworkUnixSocketPermission { match permission { codex_config::NetworkUnixSocketPermissionToml::Allow => NetworkUnixSocketPermission::Allow, - codex_config::NetworkUnixSocketPermissionToml::None => NetworkUnixSocketPermission::None, + codex_config::NetworkUnixSocketPermissionToml::Deny => NetworkUnixSocketPermission::Deny, } } diff --git a/codex-rs/app-server/src/request_processors/mcp_processor.rs b/codex-rs/app-server/src/request_processors/mcp_processor.rs index 22d5a4326a..ae62e2e785 100644 --- a/codex-rs/app-server/src/request_processors/mcp_processor.rs +++ b/codex-rs/app-server/src/request_processors/mcp_processor.rs @@ -276,6 +276,7 @@ impl McpRequestProcessor { .await; let McpServerStatusSnapshot { + server_infos, tools_by_server, resources, resource_templates, @@ -315,6 +316,7 @@ impl McpRequestProcessor { .iter() .map(|name| McpServerStatus { name: name.clone(), + server_info: server_infos.get(name).cloned(), tools: tools_by_server.get(name).cloned().unwrap_or_default(), resources: resources.get(name).cloned().unwrap_or_default(), resource_templates: resource_templates.get(name).cloned().unwrap_or_default(), diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs index 985baac91a..f72cfb5a62 100644 --- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs +++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs @@ -565,8 +565,28 @@ pub(super) async fn handle_pending_thread_resume_request( has_live_in_progress_turn, ); let token_usage_thread = pending.include_turns.then(|| thread.clone()); + let mut initial_turns_page = if let Some(params) = pending.initial_turns_page.as_ref() { + match super::thread_processor::build_thread_resume_initial_turns_page( + &pending.history_items, + thread.status.clone(), + has_live_in_progress_turn, + active_turn, + params, + ) { + Ok(page) => Some(page), + Err(error) => { + outgoing.send_error(request_id, error).await; + return; + } + } + } else { + None + }; if pending.redact_resume_payloads { - redact_thread_resume_payloads(&mut thread); + redact_thread_resume_payloads(&mut thread.turns); + if let Some(initial_turns_page) = initial_turns_page.as_mut() { + redact_thread_resume_payloads(&mut initial_turns_page.data); + } } { @@ -635,6 +655,7 @@ pub(super) async fn handle_pending_thread_resume_request( sandbox, active_permission_profile, reasoning_effort, + initial_turns_page, }; outgoing.send_response(request_id, response).await; // Match cold resume: metadata-only resume should attach the listener without 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 5a2e1a4de8..939c3df519 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -2241,8 +2241,6 @@ impl ThreadRequestProcessor { sort_direction, items_view, } = params; - let items_view = items_view.unwrap_or(TurnItemsView::Summary); - let thread_uuid = ThreadId::from_string(&thread_id) .map_err(|err| invalid_request(format!("invalid thread id: {err}")))?; @@ -2270,60 +2268,20 @@ impl ThreadRequestProcessor { } else { None }; - let mut turns = reconstruct_thread_turns_for_turns_list( + build_thread_turns_page_response( &items, self.thread_watch_manager .loaded_status_for_thread(&thread_uuid.to_string()) .await, has_live_running_thread, active_turn, - ); - for turn in &mut turns { - match items_view { - TurnItemsView::NotLoaded => { - turn.items.clear(); - turn.items_view = TurnItemsView::NotLoaded; - } - TurnItemsView::Summary => { - let first_user_message = turn - .items - .iter() - .find(|item| matches!(item, ThreadItem::UserMessage { .. })) - .cloned(); - let final_agent_message = turn - .items - .iter() - .rev() - .find(|item| matches!(item, ThreadItem::AgentMessage { .. })) - .cloned(); - turn.items = match (first_user_message, final_agent_message) { - (Some(user_message), Some(agent_message)) - if user_message.id() != agent_message.id() => - { - vec![user_message, agent_message] - } - (Some(user_message), _) => vec![user_message], - (None, Some(agent_message)) => vec![agent_message], - (None, None) => Vec::new(), - }; - turn.items_view = TurnItemsView::Summary; - } - TurnItemsView::Full => { - turn.items_view = TurnItemsView::Full; - } - } - } - let page = paginate_thread_turns( - turns, - cursor.as_deref(), - limit, - sort_direction.unwrap_or(SortDirection::Desc), - )?; - Ok(ThreadTurnsListResponse { - data: page.turns, - next_cursor: page.next_cursor, - backwards_cursor: page.backwards_cursor, - }) + ThreadTurnsPageOptions { + cursor: cursor.as_deref(), + limit, + sort_direction: sort_direction.unwrap_or(SortDirection::Desc), + items_view: items_view.unwrap_or(TurnItemsView::Summary), + }, + ) } async fn load_thread_turns_list_history( @@ -2531,6 +2489,7 @@ impl ThreadRequestProcessor { developer_instructions, personality, exclude_turns, + initial_turns_page, persist_extended_history: _persist_extended_history, } = params; let include_turns = !exclude_turns; @@ -2685,8 +2644,28 @@ impl ThreadRequestProcessor { config_snapshot.active_permission_profile, ); let token_usage_thread = include_turns.then(|| thread.clone()); + let mut initial_turns_page = if let Some(params) = initial_turns_page.as_ref() { + match build_thread_resume_initial_turns_page( + &response_history.get_rollout_items(), + thread.status.clone(), + /*has_live_running_thread*/ false, + /*active_turn*/ None, + params, + ) { + Ok(page) => Some(page), + Err(error) => { + self.outgoing.send_error(request_id, error).await; + return Ok(()); + } + } + } else { + None + }; if redact_resume_payloads { - redact_thread_resume_payloads(&mut thread); + redact_thread_resume_payloads(&mut thread.turns); + if let Some(initial_turns_page) = initial_turns_page.as_mut() { + redact_thread_resume_payloads(&mut initial_turns_page.data); + } } let response = ThreadResumeResponse { @@ -2702,6 +2681,7 @@ impl ThreadRequestProcessor { sandbox, active_permission_profile, reasoning_effort: session_configured.reasoning_effort, + initial_turns_page, }; let connection_id = request_id.connection_id; @@ -2926,6 +2906,7 @@ impl ThreadRequestProcessor { emit_thread_goal_update, thread_goal_state_db, include_turns: !params.exclude_turns, + initial_turns_page: params.initial_turns_page.clone(), redact_resume_payloads, }), ); @@ -3706,6 +3687,95 @@ fn parse_thread_turns_cursor(cursor: &str) -> Result { + cursor: Option<&'a str>, + limit: Option, + sort_direction: SortDirection, + items_view: TurnItemsView, +} + +fn build_thread_turns_page_response( + items: &[RolloutItem], + loaded_status: ThreadStatus, + has_live_running_thread: bool, + active_turn: Option, + options: ThreadTurnsPageOptions<'_>, +) -> Result { + let mut turns = reconstruct_thread_turns_for_turns_list( + items, + loaded_status, + has_live_running_thread, + active_turn, + ); + apply_thread_turns_items_view(&mut turns, options.items_view); + let page = paginate_thread_turns(turns, options.cursor, options.limit, options.sort_direction)?; + Ok(ThreadTurnsListResponse { + data: page.turns, + next_cursor: page.next_cursor, + backwards_cursor: page.backwards_cursor, + }) +} + +pub(super) fn build_thread_resume_initial_turns_page( + items: &[RolloutItem], + loaded_status: ThreadStatus, + has_live_running_thread: bool, + active_turn: Option, + params: &ThreadResumeInitialTurnsPageParams, +) -> Result { + build_thread_turns_page_response( + items, + loaded_status, + has_live_running_thread, + active_turn, + ThreadTurnsPageOptions { + cursor: None, + limit: params.limit, + sort_direction: params.sort_direction.unwrap_or(SortDirection::Desc), + items_view: params.items_view.unwrap_or(TurnItemsView::Summary), + }, + ) + .map(Into::into) +} + +fn apply_thread_turns_items_view(turns: &mut [Turn], items_view: TurnItemsView) { + for turn in turns { + match items_view { + TurnItemsView::NotLoaded => { + turn.items.clear(); + turn.items_view = TurnItemsView::NotLoaded; + } + TurnItemsView::Summary => { + let first_user_message = turn + .items + .iter() + .find(|item| matches!(item, ThreadItem::UserMessage { .. })) + .cloned(); + let final_agent_message = turn + .items + .iter() + .rev() + .find(|item| matches!(item, ThreadItem::AgentMessage { .. })) + .cloned(); + turn.items = match (first_user_message, final_agent_message) { + (Some(user_message), Some(agent_message)) + if user_message.id() != agent_message.id() => + { + vec![user_message, agent_message] + } + (Some(user_message), _) => vec![user_message], + (None, Some(agent_message)) => vec![agent_message], + (None, None) => Vec::new(), + }; + turn.items_view = TurnItemsView::Summary; + } + TurnItemsView::Full => { + turn.items_view = TurnItemsView::Full; + } + } + } +} + fn reconstruct_thread_turns_for_turns_list( items: &[RolloutItem], loaded_status: ThreadStatus, diff --git a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs index ab8f52ffc0..b5d49cf7fb 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor_tests.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor_tests.rs @@ -213,6 +213,7 @@ mod thread_processor_behavior_tests { fn thread_turns_list_merges_in_progress_active_turn_before_agent_status_running() { let persisted_items = vec![RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "persisted".to_string(), images: None, local_images: Vec::new(), @@ -224,6 +225,7 @@ mod thread_processor_behavior_tests { id: "live-turn".to_string(), items: vec![ThreadItem::UserMessage { id: "live-user-message".to_string(), + client_id: None, content: vec![V2UserInput::Text { text: "live".to_string(), text_elements: Vec::new(), @@ -652,6 +654,7 @@ mod thread_processor_behavior_tests { developer_instructions: None, personality: None, exclude_turns: false, + initial_turns_page: None, persist_extended_history: false, }; let config_snapshot = ThreadConfigSnapshot { diff --git a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs index b1e8608842..b265e3a632 100644 --- a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs +++ b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs @@ -1,6 +1,6 @@ use codex_app_server_protocol::McpToolCallResult; -use codex_app_server_protocol::Thread; use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::Turn; use serde_json::Value as JsonValue; // Temporary bandaid for remote clients: thread/resume can include large MCP and @@ -14,8 +14,8 @@ pub(super) fn should_redact_thread_resume_payloads(client_name: Option<&str>) -> client_name.is_some_and(|client_name| CHATGPT_REMOTE_CLIENT_NAMES.contains(&client_name)) } -pub(super) fn redact_thread_resume_payloads(thread: &mut Thread) { - for turn in &mut thread.turns { +pub(super) fn redact_thread_resume_payloads(turns: &mut [Turn]) { + for turn in turns { turn.items.retain_mut(|item| match item { ThreadItem::McpToolCall { arguments, @@ -55,8 +55,8 @@ mod tests { use codex_app_server_protocol::McpToolCallError; use codex_app_server_protocol::McpToolCallStatus; use codex_app_server_protocol::SessionSource; + use codex_app_server_protocol::Thread; use codex_app_server_protocol::ThreadStatus; - use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnItemsView; use codex_app_server_protocol::TurnStatus; use codex_utils_absolute_path::test_support::PathBufExt; @@ -100,7 +100,7 @@ mod tests { }, ]); - redact_thread_resume_payloads(&mut thread); + redact_thread_resume_payloads(&mut thread.turns); assert_eq!(thread.turns[0].items.len(), 2); assert_eq!( @@ -146,7 +146,7 @@ mod tests { duration_ms: Some(8), }]); - redact_thread_resume_payloads(&mut thread); + redact_thread_resume_payloads(&mut thread.turns); assert_eq!( thread.turns[0].items[0], diff --git a/codex-rs/app-server/src/request_processors/token_usage_replay.rs b/codex-rs/app-server/src/request_processors/token_usage_replay.rs index b8c65645fc..d4d2228d4b 100644 --- a/codex-rs/app-server/src/request_processors/token_usage_replay.rs +++ b/codex-rs/app-server/src/request_processors/token_usage_replay.rs @@ -148,6 +148,7 @@ mod tests { fn token_usage_history() -> Vec { vec![ RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "first turn".to_string(), images: None, local_images: Vec::new(), @@ -164,6 +165,7 @@ mod tests { rate_limits: None, })), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "second turn".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/app-server/src/request_processors/turn_processor.rs b/codex-rs/app-server/src/request_processors/turn_processor.rs index 975ff22d07..2fbc64c398 100644 --- a/codex-rs/app-server/src/request_processors/turn_processor.rs +++ b/codex-rs/app-server/src/request_processors/turn_processor.rs @@ -416,6 +416,7 @@ impl TurnRequestProcessor { .into_iter() .map(V2UserInput::into_core) .collect(); + let client_user_message_id = params.client_user_message_id; let additional_context = map_additional_context(params.additional_context); let turn_has_input = !mapped_items.is_empty(); let thread_settings = self @@ -448,8 +449,12 @@ impl TurnRequestProcessor { additional_context, thread_settings, }; - let turn_id = self - .submit_core_op(&request_id, thread.as_ref(), turn_op) + let turn_id = thread + .submit_user_input_with_client_user_message_id( + turn_op, + self.request_trace_context(&request_id).await, + client_user_message_id, + ) .await .map_err(|err| { let error = internal_error(format!("failed to start turn: {err}")); @@ -780,6 +785,7 @@ impl TurnRequestProcessor { mapped_items, additional_context, Some(¶ms.expected_turn_id), + params.client_user_message_id, params.responsesapi_client_metadata, ) .await @@ -989,6 +995,7 @@ impl TurnRequestProcessor { } else { vec![ThreadItem::UserMessage { id: turn_id.clone(), + client_id: None, content: vec![V2UserInput::Text { text: display_text.to_string(), // Review prompt display text is synthesized; no UI element ranges to preserve. diff --git a/codex-rs/app-server/src/request_processors/windows_sandbox_processor.rs b/codex-rs/app-server/src/request_processors/windows_sandbox_processor.rs index c507bf8ddf..aa82ea9513 100644 --- a/codex-rs/app-server/src/request_processors/windows_sandbox_processor.rs +++ b/codex-rs/app-server/src/request_processors/windows_sandbox_processor.rs @@ -77,7 +77,7 @@ impl WindowsSandboxRequestProcessor { let setup_request = WindowsSandboxSetupRequest { mode, permission_profile: config.permissions.effective_permission_profile(), - permission_profile_cwd: config.cwd.to_path_buf(), + workspace_roots: config.effective_workspace_roots(), command_cwd, env_map: std::env::vars().collect(), codex_home: config.codex_home.to_path_buf(), diff --git a/codex-rs/app-server/src/skills_watcher.rs b/codex-rs/app-server/src/skills_watcher.rs index 9e34cdac8e..57edb89c7f 100644 --- a/codex-rs/app-server/src/skills_watcher.rs +++ b/codex-rs/app-server/src/skills_watcher.rs @@ -1,4 +1,5 @@ use std::sync::Arc; +use std::sync::Mutex; use std::time::Duration; use crate::outgoing_message::OutgoingMessageSender; @@ -15,6 +16,7 @@ use codex_file_watcher::ThrottledWatchReceiver; use codex_file_watcher::WatchPath; use codex_file_watcher::WatchRegistration; use codex_protocol::protocol::TurnEnvironmentSelection; +use codex_utils_absolute_path::AbsolutePathBuf; use tokio_util::sync::CancellationToken; use tokio_util::sync::DropGuard; use tracing::warn; @@ -26,6 +28,7 @@ const WATCHER_THROTTLE_INTERVAL: Duration = Duration::from_millis(50); pub(crate) struct SkillsWatcher { subscriber: FileWatcherSubscriber, + runtime_extra_roots_registration: Mutex, shutdown_token: CancellationToken, _shutdown_drop_guard: DropGuard, } @@ -48,6 +51,7 @@ impl SkillsWatcher { Self::spawn_event_loop(rx, skills_manager, outgoing, shutdown_token.child_token()); Arc::new(Self { subscriber, + runtime_extra_roots_registration: Mutex::new(WatchRegistration::default()), shutdown_token, _shutdown_drop_guard: shutdown_drop_guard, }) @@ -57,6 +61,22 @@ impl SkillsWatcher { self.shutdown_token.cancel(); } + pub(crate) fn register_runtime_extra_roots(&self, extra_roots: &[AbsolutePathBuf]) { + let roots = extra_roots + .iter() + .map(|root| WatchPath { + path: root.clone().into_path_buf(), + recursive: true, + }) + .collect(); + let registration = self.subscriber.register_paths(roots); + let mut guard = self + .runtime_extra_roots_registration + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *guard = registration; + } + pub(crate) async fn register_thread_config( &self, config: &Config, diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs index 7f864265b2..2d932f0326 100644 --- a/codex-rs/app-server/src/thread_state.rs +++ b/codex-rs/app-server/src/thread_state.rs @@ -35,6 +35,8 @@ pub(crate) struct PendingThreadResumeRequest { pub(crate) emit_thread_goal_update: bool, pub(crate) thread_goal_state_db: Option, pub(crate) include_turns: bool, + pub(crate) initial_turns_page: + Option, pub(crate) redact_resume_payloads: bool, } diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index 2d2c26b5a6..d3bbfbf180 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -71,6 +71,7 @@ use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewStartParams; use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; use codex_app_server_protocol::ServerRequest; +use codex_app_server_protocol::SkillsExtraRootsSetParams; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::ThreadArchiveParams; use codex_app_server_protocol::ThreadCompactStartParams; @@ -675,6 +676,15 @@ impl McpProcess { self.send_request("skills/list", params).await } + /// Send a `skills/extraRoots/set` JSON-RPC request. + pub async fn send_skills_extra_roots_set_request( + &mut self, + params: SkillsExtraRootsSetParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("skills/extraRoots/set", params).await + } + /// Send a `hooks/list` JSON-RPC request. pub async fn send_hooks_list_request( &mut self, diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index 0a41daa7c6..aaf9f69477 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -52,6 +52,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, } } diff --git a/codex-rs/app-server/tests/suite/v2/account.rs b/codex-rs/app-server/tests/suite/v2/account.rs index a15b46abd9..8eb55e8715 100644 --- a/codex-rs/app-server/tests/suite/v2/account.rs +++ b/codex-rs/app-server/tests/suite/v2/account.rs @@ -506,6 +506,7 @@ async fn external_auth_refreshes_on_unauthorized() -> Result<()> { let turn_req = mcp .send_turn_start_request(codex_app_server_protocol::TurnStartParams { thread_id: thread.thread.id, + client_user_message_id: None, input: vec![codex_app_server_protocol::UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -612,6 +613,7 @@ async fn external_auth_refresh_error_fails_turn() -> Result<()> { let turn_req = mcp .send_turn_start_request(codex_app_server_protocol::TurnStartParams { thread_id: thread.thread.id.clone(), + client_user_message_id: None, input: vec![codex_app_server_protocol::UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -734,6 +736,7 @@ async fn external_auth_refresh_mismatched_workspace_fails_turn() -> Result<()> { let turn_req = mcp .send_turn_start_request(codex_app_server_protocol::TurnStartParams { thread_id: thread.thread.id.clone(), + client_user_message_id: None, input: vec![codex_app_server_protocol::UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -849,6 +852,7 @@ async fn external_auth_refresh_invalid_access_token_fails_turn() -> Result<()> { let turn_req = mcp .send_turn_start_request(codex_app_server_protocol::TurnStartParams { thread_id: thread.thread.id.clone(), + client_user_message_id: None, input: vec![codex_app_server_protocol::UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs index aa7b67a574..039fffe5cd 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -316,6 +316,73 @@ connectors = false Ok(()) } +#[tokio::test] +async fn list_apps_keeps_apps_with_app_only_tools_accessible() -> Result<()> { + let connectors = vec![AppInfo { + id: "beta".to_string(), + name: "Beta".to_string(), + description: Some("Beta connector".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + branding: None, + app_metadata: None, + labels: None, + install_url: None, + is_accessible: false, + is_enabled: true, + plugin_display_names: Vec::new(), + }]; + let mut app_only_tool = connector_tool("beta", "Beta App")?; + app_only_tool + .meta + .as_mut() + .expect("connector tool should include metadata") + .0 + .insert("ui".to_string(), json!({ "visibility": ["app"] })); + let tools = vec![app_only_tool]; + let (server_url, server_handle) = + start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; + + let codex_home = TempDir::new()?; + write_connectors_config(codex_home.path(), &server_url)?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-app-only") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_apps_list_request(AppsListParams { + limit: None, + cursor: None, + thread_id: None, + force_refetch: true, + }) + .await?; + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let AppsListResponse { data, next_cursor } = to_response(response)?; + + assert_eq!(data.len(), 1); + assert_eq!(data[0].id, "beta"); + assert!(data[0].is_accessible); + assert!(next_cursor.is_none()); + + server_handle.abort(); + let _ = server_handle.await; + Ok(()) +} + #[tokio::test] async fn list_apps_reports_is_enabled_from_config() -> Result<()> { let connectors = vec![AppInfo { diff --git a/codex-rs/app-server/tests/suite/v2/attestation.rs b/codex-rs/app-server/tests/suite/v2/attestation.rs index d0565e2571..a662755be9 100644 --- a/codex-rs/app-server/tests/suite/v2/attestation.rs +++ b/codex-rs/app-server/tests/suite/v2/attestation.rs @@ -110,6 +110,7 @@ async fn attestation_generate_round_trip_adds_header_to_responses_websocket_hand let turn_request_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/client_metadata.rs b/codex-rs/app-server/tests/suite/v2/client_metadata.rs index 9daa8d34f1..687efefbdf 100644 --- a/codex-rs/app-server/tests/suite/v2/client_metadata.rs +++ b/codex-rs/app-server/tests/suite/v2/client_metadata.rs @@ -73,6 +73,7 @@ async fn turn_start_forwards_client_metadata_to_responses_request_v2() -> Result let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -153,6 +154,7 @@ async fn turn_start_sends_fork_lineage_in_turn_metadata_for_thread_fork_v2() -> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Continue".to_string(), text_elements: Vec::new(), @@ -333,6 +335,7 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2() let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Run sleep".to_string(), text_elements: Vec::new(), @@ -363,6 +366,7 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2() let steer_req = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Focus on the failure".to_string(), text_elements: Vec::new(), @@ -458,6 +462,7 @@ async fn turn_start_forwards_client_metadata_to_responses_websocket_request_body let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/compaction.rs b/codex-rs/app-server/tests/suite/v2/compaction.rs index 2cf9f6b36c..ca46c88a28 100644 --- a/codex-rs/app-server/tests/suite/v2/compaction.rs +++ b/codex-rs/app-server/tests/suite/v2/compaction.rs @@ -394,6 +394,7 @@ async fn send_turn_and_wait(mcp: &mut McpProcess, thread_id: &str, text: &str) - let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: text.to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket_unix.rs b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket_unix.rs index 4b708d4ab3..0c8a59a9c8 100644 --- a/codex-rs/app-server/tests/suite/v2/connection_handling_websocket_unix.rs +++ b/codex-rs/app-server/tests/suite/v2/connection_handling_websocket_unix.rs @@ -226,6 +226,7 @@ async fn send_turn_start_request(stream: &mut WsClient, id: i64, thread_id: &str id, Some(serde_json::to_value(TurnStartParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs index b357e139db..333086c722 100644 --- a/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs +++ b/codex-rs/app-server/tests/suite/v2/dynamic_tools.rs @@ -89,6 +89,7 @@ async fn thread_start_injects_dynamic_tools_into_model_requests() -> Result<()> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -168,6 +169,7 @@ async fn thread_start_keeps_hidden_dynamic_tools_out_of_model_requests() -> Resu let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -347,6 +349,7 @@ async fn dynamic_tool_call_round_trip_sends_text_content_items_to_model() -> Res let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Run the tool".to_string(), text_elements: Vec::new(), @@ -521,6 +524,7 @@ async fn dynamic_tool_call_round_trip_sends_content_items_to_model() -> Result<( let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Run the tool".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/external_agent_config.rs b/codex-rs/app-server/tests/suite/v2/external_agent_config.rs index f5f74c0231..22790f94f7 100644 --- a/codex-rs/app-server/tests/suite/v2/external_agent_config.rs +++ b/codex-rs/app-server/tests/suite/v2/external_agent_config.rs @@ -391,6 +391,7 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> { let request_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "follow up".to_string(), text_elements: Vec::new(), @@ -964,6 +965,7 @@ async fn external_agent_config_import_compacts_huge_session_before_first_follow_ let request_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "follow up".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/hooks_list.rs b/codex-rs/app-server/tests/suite/v2/hooks_list.rs index 1c8f76fe51..7e0b39f0c6 100644 --- a/codex-rs/app-server/tests/suite/v2/hooks_list.rs +++ b/codex-rs/app-server/tests/suite/v2/hooks_list.rs @@ -662,6 +662,7 @@ command = "python3 {hook_script_path}" let first_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "first turn".to_string(), text_elements: Vec::new(), @@ -723,6 +724,7 @@ command = "python3 {hook_script_path}" let second_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "second turn".to_string(), text_elements: Vec::new(), @@ -792,6 +794,7 @@ command = "python3 {hook_script_path}" let third_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "third turn".to_string(), text_elements: Vec::new(), @@ -932,6 +935,7 @@ command = "python3 {hook_script_path}" let first_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "first turn".to_string(), text_elements: Vec::new(), @@ -983,6 +987,7 @@ command = "python3 {hook_script_path}" let second_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "second turn".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/initialize.rs b/codex-rs/app-server/tests/suite/v2/initialize.rs index 47cacdb20e..3a9b22cf16 100644 --- a/codex-rs/app-server/tests/suite/v2/initialize.rs +++ b/codex-rs/app-server/tests/suite/v2/initialize.rs @@ -306,6 +306,7 @@ async fn turn_start_notify_payload_includes_initialize_client_name() -> Result<( let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs index 9c415a4c9e..7357e3f178 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs @@ -135,6 +135,7 @@ async fn mcp_server_elicitation_round_trip() -> Result<()> { let warmup_turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Warm up connectors.".to_string(), text_elements: Vec::new(), @@ -167,6 +168,7 @@ async fn mcp_server_elicitation_round_trip() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Use [$calendar](app://calendar) to run the calendar tool.".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs index 7af89d887b..32f98a1738 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_status.rs @@ -20,6 +20,7 @@ use codex_core::config::set_project_trust_level; use codex_protocol::config_types::TrustLevel; use pretty_assertions::assert_eq; use rmcp::handler::server::ServerHandler; +use rmcp::model::Implementation; use rmcp::model::JsonObject; use rmcp::model::ListResourceTemplatesResult; use rmcp::model::ListResourcesResult; @@ -99,6 +100,13 @@ url = "{mcp_server_url}/mcp" .map(|tool| tool.name.as_str()), Some("look-up.raw") ); + assert_eq!( + status + .server_info + .as_ref() + .and_then(|info| info.title.as_deref()), + Some("Lookup Server") + ); mcp_server_handle.abort(); let _ = mcp_server_handle.await; @@ -205,7 +213,9 @@ struct McpStatusServer { impl ServerHandler for McpStatusServer { fn get_info(&self) -> ServerInfo { - ServerInfo::new(ServerCapabilities::builder().enable_tools().build()) + ServerInfo::new(ServerCapabilities::builder().enable_tools().build()).with_server_info( + Implementation::new("lookup-server", "1.0.0").with_title("Lookup Server"), + ) } async fn list_tools( diff --git a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs index eff9ec9603..9ba09b078f 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs @@ -461,6 +461,7 @@ url = "{mcp_server_url}/mcp" let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Call the large MCP tool".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/output_schema.rs b/codex-rs/app-server/tests/suite/v2/output_schema.rs index 149e098b68..86d12edcfc 100644 --- a/codex-rs/app-server/tests/suite/v2/output_schema.rs +++ b/codex-rs/app-server/tests/suite/v2/output_schema.rs @@ -59,6 +59,7 @@ async fn turn_start_accepts_output_schema_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -141,6 +142,7 @@ async fn turn_start_output_schema_is_per_turn_v2() -> Result<()> { let turn_req_1 = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -183,6 +185,7 @@ async fn turn_start_output_schema_is_per_turn_v2() -> Result<()> { let turn_req_2 = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello again".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/plan_item.rs b/codex-rs/app-server/tests/suite/v2/plan_item.rs index 97e67fa090..63f7d9fba2 100644 --- a/codex-rs/app-server/tests/suite/v2/plan_item.rs +++ b/codex-rs/app-server/tests/suite/v2/plan_item.rs @@ -152,6 +152,7 @@ async fn start_plan_mode_turn(mcp: &mut McpProcess) -> Result Result<()> { BTreeSet::from([ "config.toml".to_string(), "installation_id".to_string(), - "memories".to_string(), "skills".to_string(), ]), "non-local thread persistence should not create unexpected files in codex_home" diff --git a/codex-rs/app-server/tests/suite/v2/request_permissions.rs b/codex-rs/app-server/tests/suite/v2/request_permissions.rs index 7acdc1b12f..8fd44d26f0 100644 --- a/codex-rs/app-server/tests/suite/v2/request_permissions.rs +++ b/codex-rs/app-server/tests/suite/v2/request_permissions.rs @@ -49,6 +49,7 @@ async fn request_permissions_round_trip() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "pick a directory".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/request_user_input.rs b/codex-rs/app-server/tests/suite/v2/request_user_input.rs index f77ddfb4f7..a80b5527a7 100644 --- a/codex-rs/app-server/tests/suite/v2/request_user_input.rs +++ b/codex-rs/app-server/tests/suite/v2/request_user_input.rs @@ -51,6 +51,7 @@ async fn request_user_input_round_trip() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "ask something".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/review.rs b/codex-rs/app-server/tests/suite/v2/review.rs index bf0271f821..bb89a68077 100644 --- a/codex-rs/app-server/tests/suite/v2/review.rs +++ b/codex-rs/app-server/tests/suite/v2/review.rs @@ -91,6 +91,7 @@ async fn review_start_runs_review_turn_and_emits_code_review_item() -> Result<() turn.items, vec![ThreadItem::UserMessage { id: turn_id.clone(), + client_id: None, content: vec![V2UserInput::Text { text: "commit 1234567: Tidy UI colors".to_string(), text_elements: Vec::new(), @@ -199,6 +200,7 @@ async fn review_start_exec_approval_item_id_matches_command_execution_item() -> turn.items, vec![ThreadItem::UserMessage { id: turn_id.clone(), + client_id: None, content: vec![V2UserInput::Text { text: "commit 1234567: Check review approvals".to_string(), text_elements: Vec::new(), @@ -328,6 +330,7 @@ async fn review_start_with_detached_delivery_returns_new_thread_id() -> Result<( turn.items, vec![ThreadItem::UserMessage { id: turn.id.clone(), + client_id: None, content: vec![V2UserInput::Text { text: "detached review".to_string(), text_elements: Vec::new(), @@ -465,6 +468,7 @@ async fn materialize_thread_rollout(mcp: &mut McpProcess, thread_id: &str) -> Re let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "materialize rollout".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/safety_check_downgrade.rs b/codex-rs/app-server/tests/suite/v2/safety_check_downgrade.rs index 7c1619e38a..a7f1bf3729 100644 --- a/codex-rs/app-server/tests/suite/v2/safety_check_downgrade.rs +++ b/codex-rs/app-server/tests/suite/v2/safety_check_downgrade.rs @@ -67,6 +67,7 @@ async fn openai_model_header_mismatch_emits_model_rerouted_notification_v2() -> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "trigger safeguard".to_string(), text_elements: Vec::new(), @@ -133,6 +134,7 @@ async fn cyber_policy_response_emits_typed_error_notification_v2() -> Result<()> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "trigger cyber policy error".to_string(), text_elements: Vec::new(), @@ -209,6 +211,7 @@ async fn response_model_field_mismatch_emits_model_rerouted_notification_v2_when let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "trigger response model check".to_string(), text_elements: Vec::new(), @@ -277,6 +280,7 @@ async fn model_verification_emits_typed_notification_and_warning_v2() -> Result< let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "trigger model verification".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs index 74100bc19f..2ad0b2006a 100644 --- a/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs @@ -13,11 +13,14 @@ use codex_app_server_protocol::PluginListParams; use codex_app_server_protocol::PluginListResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SkillsChangedNotification; +use codex_app_server_protocol::SkillsExtraRootsSetParams; +use codex_app_server_protocol::SkillsExtraRootsSetResponse; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::ThreadStartParams; use codex_config::types::AuthCredentialsStoreMode; use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR; +use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; @@ -40,6 +43,23 @@ fn write_skill(root: &TempDir, name: &str) -> Result<()> { Ok(()) } +async fn expect_skills_changed_notification( + mcp: &mut McpProcess, + timeout_duration: Duration, +) -> Result<()> { + let notification = timeout( + timeout_duration, + mcp.read_stream_until_notification_message("skills/changed"), + ) + .await??; + let params = notification + .params + .context("skills/changed params must be present")?; + let notification: SkillsChangedNotification = serde_json::from_value(params)?; + assert_eq!(notification, SkillsChangedNotification {}); + Ok(()) +} + fn write_plugins_enabled_config_with_base_url( codex_home: &std::path::Path, base_url: &str, @@ -573,6 +593,150 @@ async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { Ok(()) } +#[tokio::test] +async fn skills_extra_roots_set_updates_process_runtime_roots() -> Result<()> { + let codex_home = TempDir::new()?; + let cwd = TempDir::new()?; + let extra_root = TempDir::new()?; + let extra_skills_root = extra_root.path().join("skills"); + let skill_dir = extra_skills_root.join("runtime-skill"); + std::fs::create_dir_all(&skill_dir)?; + std::fs::write( + skill_dir.join("SKILL.md"), + "---\nname: runtime-skill\ndescription: runtime skill\n---\n\n# Body\n", + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let set_request_id = mcp + .send_skills_extra_roots_set_request(SkillsExtraRootsSetParams { + extra_roots: vec![AbsolutePathBuf::from_absolute_path(&extra_skills_root)?], + }) + .await?; + let set_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(set_request_id)), + ) + .await??; + let _: SkillsExtraRootsSetResponse = to_response(set_response)?; + expect_skills_changed_notification(&mut mcp, DEFAULT_TIMEOUT).await?; + + let skills_request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![cwd.path().to_path_buf()], + force_reload: false, + }) + .await?; + let skills_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(skills_request_id)), + ) + .await??; + let SkillsListResponse { data } = to_response(skills_response)?; + assert_eq!(data.len(), 1); + assert_eq!(data[0].errors, Vec::new()); + assert!( + data[0] + .skills + .iter() + .any(|skill| skill.name == "runtime-skill") + ); + + let missing_root = extra_root.path().join("missing-skills"); + let reset_request_id = mcp + .send_skills_extra_roots_set_request(SkillsExtraRootsSetParams { + extra_roots: vec![AbsolutePathBuf::from_absolute_path(&missing_root)?], + }) + .await?; + let reset_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(reset_request_id)), + ) + .await??; + let _: SkillsExtraRootsSetResponse = to_response(reset_response)?; + expect_skills_changed_notification(&mut mcp, DEFAULT_TIMEOUT).await?; + + let skills_request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![cwd.path().to_path_buf()], + force_reload: false, + }) + .await?; + let skills_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(skills_request_id)), + ) + .await??; + let SkillsListResponse { data } = to_response(skills_response)?; + assert_eq!(data.len(), 1); + assert_eq!(data[0].errors, Vec::new()); + assert!( + data[0] + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); + + let clear_request_id = mcp + .send_skills_extra_roots_set_request(SkillsExtraRootsSetParams { + extra_roots: Vec::new(), + }) + .await?; + let clear_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(clear_request_id)), + ) + .await??; + let _: SkillsExtraRootsSetResponse = to_response(clear_response)?; + expect_skills_changed_notification(&mut mcp, DEFAULT_TIMEOUT).await?; + let skills_request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![cwd.path().to_path_buf()], + force_reload: false, + }) + .await?; + let skills_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(skills_request_id)), + ) + .await??; + let SkillsListResponse { data } = to_response(skills_response)?; + assert_eq!(data.len(), 1); + assert_eq!(data[0].errors, Vec::new()); + assert!( + data[0] + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); + + drop(mcp); + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + let skills_request_id = mcp + .send_skills_list_request(SkillsListParams { + cwds: vec![cwd.path().to_path_buf()], + force_reload: false, + }) + .await?; + let skills_response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(skills_request_id)), + ) + .await??; + let SkillsListResponse { data } = to_response(skills_response)?; + assert_eq!(data.len(), 1); + assert_eq!(data[0].errors, Vec::new()); + assert!( + data[0] + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); + Ok(()) +} + #[tokio::test] async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/app-server/tests/suite/v2/thread_archive.rs b/codex-rs/app-server/tests/suite/v2/thread_archive.rs index b441a23cb6..6eadb1131b 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_archive.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_archive.rs @@ -93,6 +93,7 @@ async fn thread_archive_requires_materialized_rollout() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize".to_string(), text_elements: Vec::new(), @@ -517,6 +518,7 @@ async fn thread_archive_clears_stale_subscriptions_before_resume() -> Result<()> let turn_start_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize".to_string(), text_elements: Vec::new(), @@ -594,6 +596,7 @@ async fn thread_archive_clears_stale_subscriptions_before_resume() -> Result<()> let resumed_turn_id = secondary .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![UserInput::Text { text: "secondary turn".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_fork.rs b/codex-rs/app-server/tests/suite/v2/thread_fork.rs index 287afe1016..5c4c637f4b 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_fork.rs @@ -747,6 +747,7 @@ async fn thread_fork_ephemeral_remains_pathless_and_omits_listing() -> Result<() let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: fork_thread_id, + client_user_message_id: None, input: vec![UserInput::Text { text: "continue".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs b/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs index 5a45e81e1d..c543b50498 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_inject_items.rs @@ -92,6 +92,7 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history() -> Resu let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -170,6 +171,7 @@ async fn thread_inject_items_adds_raw_response_items_after_a_turn() -> Result<() let first_turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "First turn".to_string(), text_elements: Vec::new(), @@ -215,6 +217,7 @@ async fn thread_inject_items_adds_raw_response_items_after_a_turn() -> Result<() let second_turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Second turn".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index e064ff6e25..8808092361 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -227,6 +227,7 @@ async fn thread_list_reports_system_error_idle_flag_after_failed_turn() -> Resul let seed_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -249,6 +250,7 @@ async fn thread_list_reports_system_error_idle_flag_after_failed_turn() -> Resul let failed_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "fail turn".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_read.rs b/codex-rs/app-server/tests/suite/v2/thread_read.rs index c8e3e179fb..ee430f1593 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -24,6 +24,7 @@ use codex_app_server_protocol::ThreadListResponse; use codex_app_server_protocol::ThreadNameUpdatedNotification; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; +use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams; use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadSetNameParams; @@ -631,6 +632,77 @@ async fn thread_read_can_return_archived_threads_by_id() -> Result<()> { Ok(()) } +#[tokio::test] +async fn thread_resume_initial_turns_page_matches_requested_turns_list_page() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + let codex_home = TempDir::new()?; + create_config_toml(codex_home.path(), &server.uri())?; + + let filename_ts = "2025-01-05T12-00-00"; + let conversation_id = create_fake_rollout_with_text_elements( + codex_home.path(), + filename_ts, + "2025-01-05T12:00:00Z", + "first", + vec![], + Some("mock_provider"), + /*git_info*/ None, + )?; + let rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id); + append_user_message(rollout_path.as_path(), "2025-01-05T12:01:00Z", "second")?; + append_user_message(rollout_path.as_path(), "2025-01-05T12:02:00Z", "third")?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let turns_list_id = mcp + .send_thread_turns_list_request(ThreadTurnsListParams { + thread_id: conversation_id.clone(), + cursor: None, + limit: Some(2), + sort_direction: Some(SortDirection::Asc), + items_view: Some(TurnItemsView::NotLoaded), + }) + .await?; + let turns_list_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turns_list_id)), + ) + .await??; + let expected_page = to_response::(turns_list_resp)?; + + let resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id: conversation_id, + exclude_turns: true, + initial_turns_page: Some(ThreadResumeInitialTurnsPageParams { + limit: Some(2), + sort_direction: Some(SortDirection::Asc), + items_view: Some(TurnItemsView::NotLoaded), + }), + ..Default::default() + }) + .await?; + let resume_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), + ) + .await??; + let ThreadResumeResponse { + thread, + initial_turns_page, + .. + } = to_response::(resume_resp)?; + + assert!(thread.turns.is_empty()); + assert_eq!( + initial_turns_page, + Some(codex_app_server_protocol::TurnsPage::from(expected_page)) + ); + + Ok(()) +} + #[tokio::test] async fn thread_turns_list_rejects_cursor_when_anchor_turn_is_rolled_back() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; @@ -1126,6 +1198,7 @@ async fn thread_read_reports_system_error_idle_flag_after_failed_turn() -> Resul let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "fail this turn".to_string(), text_elements: Vec::new(), @@ -1319,6 +1392,7 @@ async fn seed_pathless_store_thread( fn store_history_items() -> Vec { vec![RolloutItem::EventMsg(EventMsg::UserMessage( UserMessageEvent { + client_id: None, message: "history from store".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index bb2de2cfbb..36dac0d45c 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -37,6 +37,7 @@ use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams; use codex_app_server_protocol::ThreadMetadataUpdateParams; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; +use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams; use codex_app_server_protocol::ThreadResumeParams; use codex_app_server_protocol::ThreadResumeResponse; use codex_app_server_protocol::ThreadSource; @@ -210,6 +211,7 @@ async fn thread_resume_with_empty_path_uses_running_thread_id() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize rollout".to_string(), text_elements: Vec::new(), @@ -278,6 +280,7 @@ async fn turn_start_updates_runtime_workspace_roots_for_loaded_thread() -> Resul let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -530,48 +533,59 @@ async fn thread_resume_returns_rollout_history() -> Result<()> { #[tokio::test] async fn thread_resume_redacts_payloads_for_chatgpt_remote_clients() -> Result<()> { for client_name in ["codex_chatgpt_android_remote", "codex_chatgpt_ios_remote"] { - let remote_thread = resume_redaction_fixture(Some(client_name)).await?; - let remote_turn = remote_thread + let remote_resume = resume_redaction_fixture(Some(client_name)).await?; + let remote_turn = remote_resume + .thread .turns .first() .expect("remote resume should include a turn"); - let remote_mcp_item = remote_turn - .items - .iter() - .find(|item| matches!(item, ThreadItem::McpToolCall { .. })) - .expect("remote resume should include redacted MCP item"); - let ThreadItem::McpToolCall { - arguments, - result, - error, - .. - } = remote_mcp_item - else { - unreachable!("matched MCP item"); - }; - assert_eq!(arguments, &json!("[redacted]")); - let result = result.as_ref().expect("redacted MCP result"); - assert_eq!( - result.content, - vec![json!({ - "type": "text", - "text": "[redacted]", - })] - ); - assert_eq!(result.structured_content, None); - assert_eq!(result.meta, None); - assert_eq!(error, &None); - assert!( - !remote_turn + let remote_page_turn = remote_resume + .initial_turns_page + .as_ref() + .expect("remote resume should include the requested initial turns page") + .data + .first() + .expect("remote initial turns page should include a turn"); + for remote_turn in [remote_turn, remote_page_turn] { + let remote_mcp_item = remote_turn .items .iter() - .any(|item| matches!(item, ThreadItem::ImageGeneration { .. })), - "remote resume should drop image generation items for {client_name}" - ); + .find(|item| matches!(item, ThreadItem::McpToolCall { .. })) + .expect("remote resume should include redacted MCP item"); + let ThreadItem::McpToolCall { + arguments, + result, + error, + .. + } = remote_mcp_item + else { + unreachable!("matched MCP item"); + }; + assert_eq!(arguments, &json!("[redacted]")); + let result = result.as_ref().expect("redacted MCP result"); + assert_eq!( + result.content, + vec![json!({ + "type": "text", + "text": "[redacted]", + })] + ); + assert_eq!(result.structured_content, None); + assert_eq!(result.meta, None); + assert_eq!(error, &None); + assert!( + !remote_turn + .items + .iter() + .any(|item| matches!(item, ThreadItem::ImageGeneration { .. })), + "remote resume should drop image generation items for {client_name}" + ); + } } - let normal_thread = resume_redaction_fixture(Some("some_other_client")).await?; - let normal_turn = normal_thread + let normal_resume = resume_redaction_fixture(Some("some_other_client")).await?; + let normal_turn = normal_resume + .thread .turns .first() .expect("normal resume should include a turn"); @@ -616,9 +630,7 @@ async fn thread_resume_redacts_payloads_for_chatgpt_remote_clients() -> Result<( Ok(()) } -async fn resume_redaction_fixture( - client_name: Option<&str>, -) -> Result { +async fn resume_redaction_fixture(client_name: Option<&str>) -> Result { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; create_config_toml(codex_home.path(), &server.uri())?; @@ -658,6 +670,11 @@ async fn resume_redaction_fixture( let resume_id = mcp .send_thread_resume_request(ThreadResumeParams { thread_id: conversation_id, + initial_turns_page: Some(ThreadResumeInitialTurnsPageParams { + limit: None, + sort_direction: None, + items_view: Some(TurnItemsView::Full), + }), ..Default::default() }) .await?; @@ -666,8 +683,7 @@ async fn resume_redaction_fixture( mcp.read_stream_until_response_message(RequestId::Integer(resume_id)), ) .await??; - let ThreadResumeResponse { thread, .. } = to_response::(resume_resp)?; - Ok(thread) + to_response::(resume_resp) } fn append_resume_redaction_history( @@ -795,6 +811,7 @@ async fn thread_resume_keeps_paused_goal_paused() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize this thread".to_string(), text_elements: Vec::new(), @@ -899,6 +916,7 @@ async fn thread_goal_set_preserves_budget_limited_same_objective() -> Result<()> let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize this thread".to_string(), text_elements: Vec::new(), @@ -997,6 +1015,7 @@ async fn thread_goal_set_persists_resumable_stopped_statuses() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize this thread".to_string(), text_elements: Vec::new(), @@ -1192,6 +1211,7 @@ async fn thread_goal_clear_deletes_goal_and_notifies() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize this thread".to_string(), text_elements: Vec::new(), @@ -2060,6 +2080,7 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> { let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2085,6 +2106,7 @@ async fn thread_resume_keeps_in_flight_turn_streaming() -> Result<()> { let turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "respond with docs".to_string(), text_elements: Vec::new(), @@ -2167,6 +2189,7 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> { let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2190,6 +2213,7 @@ async fn thread_resume_rejects_history_when_thread_is_running() -> Result<()> { let running_turn_request_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "keep running".to_string(), text_elements: Vec::new(), @@ -2283,6 +2307,7 @@ async fn thread_resume_rejects_mismatched_path_for_running_thread_id() -> Result let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2306,6 +2331,7 @@ async fn thread_resume_rejects_mismatched_path_for_running_thread_id() -> Result let running_turn_request_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "keep running".to_string(), text_elements: Vec::new(), @@ -2419,6 +2445,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2441,6 +2468,7 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R let running_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "keep running".to_string(), text_elements: Vec::new(), @@ -2448,11 +2476,13 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R ..Default::default() }) .await?; - timeout( + let running_turn_resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, primary.read_stream_until_response_message(RequestId::Integer(running_turn_id)), ) .await??; + let TurnStartResponse { turn: running_turn } = + to_response::(running_turn_resp)?; timeout( DEFAULT_READ_TIMEOUT, primary.read_stream_until_notification_message("turn/started"), @@ -2464,6 +2494,11 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R thread_id: thread.id.clone(), model: Some("not-the-running-model".to_string()), cwd: Some("/tmp".to_string()), + initial_turns_page: Some(ThreadResumeInitialTurnsPageParams { + limit: None, + sort_direction: None, + items_view: None, + }), ..Default::default() }) .await?; @@ -2472,9 +2507,23 @@ async fn thread_resume_rejoins_running_thread_even_with_override_mismatch() -> R primary.read_stream_until_response_message(RequestId::Integer(resume_id)), ) .await??; - let ThreadResumeResponse { thread, model, .. } = - to_response::(resume_resp)?; + let ThreadResumeResponse { + thread, + model, + initial_turns_page, + .. + } = to_response::(resume_resp)?; assert_eq!(model, "gpt-5.4"); + let initial_turns_page = initial_turns_page.expect("resume should include initial turns page"); + let resumed_running_turn = initial_turns_page + .data + .first() + .expect("resume page should include the running turn"); + assert_eq!(resumed_running_turn.id, running_turn.id); + assert_eq!(resumed_running_turn.items_view, TurnItemsView::Summary); + assert_eq!(resumed_running_turn.status, TurnStatus::InProgress); + assert!(initial_turns_page.backwards_cursor.is_some()); + assert_eq!(initial_turns_page.next_cursor, None); // The running-thread resume response is queued onto the thread listener task. // If the in-flight turn completes before that queued command runs, the response // can legitimately observe the thread as idle. @@ -2527,6 +2576,7 @@ async fn thread_resume_can_skip_turns_when_thread_is_running() -> Result<()> { let turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2610,6 +2660,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2632,6 +2683,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R let running_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "run command".to_string(), text_elements: Vec::new(), @@ -2748,6 +2800,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result< let seed_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -2771,6 +2824,7 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result< let running_turn_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "apply patch".to_string(), text_elements: Vec::new(), @@ -2915,6 +2969,7 @@ async fn thread_resume_with_overrides_defers_updated_at_until_turn_start() -> Re let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: resumed_thread.id, + client_user_message_id: None, input: vec![UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -3227,6 +3282,7 @@ async fn start_materialized_thread_and_restart( let materialize_turn_id = first_mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: seed_text.to_string(), text_elements: Vec::new(), @@ -3316,6 +3372,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> { let materialize_id = primary .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "seed history".to_string(), text_elements: Vec::new(), @@ -3356,6 +3413,7 @@ async fn thread_resume_accepts_personality_override() -> Result<()> { let turn_id = secondary .send_turn_start_request(TurnStartParams { thread_id: resume.thread.id, + client_user_message_id: None, input: vec![UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_rollback.rs b/codex-rs/app-server/tests/suite/v2/thread_rollback.rs index 5f79db0e26..80feacb4fe 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_rollback.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_rollback.rs @@ -57,6 +57,7 @@ async fn thread_rollback_drops_last_turns_and_persists_to_rollout() -> Result<() let turn1_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: first_text.to_string(), text_elements: Vec::new(), @@ -78,6 +79,7 @@ async fn thread_rollback_drops_last_turns_and_persists_to_rollout() -> Result<() let turn2_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Second".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs index aef2e961c0..5f7b8dbf21 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs @@ -259,6 +259,7 @@ async fn turn_start_settings_override_emits_thread_settings_updated() -> Result< let turn_request_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "hello".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs index 4ab677aca1..368368badc 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_shell_command.rs @@ -275,6 +275,7 @@ async fn thread_shell_command_uses_existing_active_turn() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_status.rs b/codex-rs/app-server/tests/suite/v2/thread_status.rs index 957969c3ea..51dda1bde7 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_status.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_status.rs @@ -48,6 +48,7 @@ async fn thread_status_changed_emits_runtime_updates() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "collect status updates".to_string(), text_elements: Vec::new(), @@ -171,6 +172,7 @@ async fn thread_status_changed_can_be_opted_out() -> Result<()> { let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run once".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs b/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs index d2f8f268a2..dea8433d44 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_unarchive.rs @@ -81,6 +81,7 @@ async fn thread_unarchive_moves_rollout_back_into_sessions_directory() -> Result let turn_start_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![UserInput::Text { text: "materialize".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs index 45437b7ee1..ebd3c9b95d 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_unsubscribe.rs @@ -151,6 +151,7 @@ async fn thread_unsubscribe_during_turn_keeps_turn_running() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run deterministic tool".to_string(), text_elements: Vec::new(), @@ -260,6 +261,7 @@ async fn thread_unsubscribe_preserves_cached_status_before_idle_unload() -> Resu let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "fail this turn".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs index aedc54e016..78079ea148 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_interrupt.rs @@ -78,6 +78,7 @@ async fn turn_interrupt_aborts_running_turn() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run sleep".to_string(), text_elements: Vec::new(), @@ -159,6 +160,7 @@ async fn turn_interrupt_rejects_completed_turn() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "say done".to_string(), text_elements: Vec::new(), @@ -253,6 +255,7 @@ async fn turn_interrupt_resolves_pending_command_approval_request() -> Result<() let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index d0f1c13246..2ae4561d86 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -141,6 +141,7 @@ async fn run_local_image_turn(detail: Option) -> Result> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::LocalImage { path: image_path, detail, @@ -235,6 +236,7 @@ async fn turn_start_with_empty_input_runs_model_request() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: Vec::new(), ..Default::default() }) @@ -335,6 +337,7 @@ async fn turn_start_additional_context_flows_to_model_input() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "inspect tab".to_string(), text_elements: Vec::new(), @@ -420,6 +423,7 @@ async fn turn_start_sends_originator_header() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -492,6 +496,7 @@ async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: Some("client-message-1".to_string()), input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: text_elements.clone(), @@ -521,7 +526,10 @@ async fn turn_start_emits_user_message_item_with_text_elements() -> Result<()> { .await??; match user_message_item { - ThreadItem::UserMessage { content, .. } => { + ThreadItem::UserMessage { + client_id, content, .. + } => { + assert_eq!(client_id, Some("client-message-1".to_string())); assert_eq!( content, vec![V2UserInput::Text { @@ -595,6 +603,7 @@ async fn turn_start_emits_thread_scoped_warning_notification_for_trimmed_skills( let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -761,6 +770,7 @@ async fn thread_start_omits_empty_instruction_overrides_from_model_request() -> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -840,6 +850,7 @@ async fn turn_start_tracks_turn_event_analytics() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Image { url: "https://example.com/a.png".to_string(), detail: None, @@ -928,6 +939,7 @@ async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![ V2UserInput::Text { text: "x".repeat(MAX_USER_INPUT_TEXT_CHARS), @@ -991,6 +1003,7 @@ async fn turn_start_rejects_combined_oversized_text_input() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![ V2UserInput::Text { text: first, @@ -1065,6 +1078,7 @@ async fn turn_start_rejects_invalid_permission_selection_before_starting_turn() let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1137,6 +1151,7 @@ async fn turn_start_rejects_unknown_environment_before_starting_turn() -> Result let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1210,6 +1225,7 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<( let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1262,6 +1278,7 @@ async fn turn_start_emits_notifications_and_accepts_model_override() -> Result<( let turn_req2 = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Second".to_string(), text_elements: Vec::new(), @@ -1360,6 +1377,7 @@ async fn turn_start_accepts_collaboration_mode_override_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1449,6 +1467,7 @@ async fn turn_start_uses_thread_feature_overrides_for_request_user_input_tool_de let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1520,6 +1539,7 @@ async fn turn_start_accepts_personality_override_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1601,6 +1621,7 @@ async fn turn_start_change_personality_mid_thread_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1625,6 +1646,7 @@ async fn turn_start_change_personality_mid_thread_v2() -> Result<()> { let turn_req2 = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello again".to_string(), text_elements: Vec::new(), @@ -1727,6 +1749,7 @@ async fn turn_start_uses_migrated_pragmatic_personality_without_override_v2() -> let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Hello".to_string(), text_elements: Vec::new(), @@ -1847,6 +1870,7 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { let first_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), @@ -1911,6 +1935,7 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> { let second_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python again".to_string(), text_elements: Vec::new(), @@ -1988,6 +2013,7 @@ async fn turn_start_exec_approval_decline_v2() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), @@ -2143,6 +2169,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { .send_turn_start_request(TurnStartParams { environments: None, thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "first turn".to_string(), text_elements: Vec::new(), @@ -2186,6 +2213,7 @@ async fn turn_start_updates_sandbox_and_cwd_between_turns_v2() -> Result<()> { .send_turn_start_request(TurnStartParams { environments: None, thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "second turn".to_string(), text_elements: Vec::new(), @@ -2328,6 +2356,7 @@ stream_max_retries = 0 let first_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "select dev profile".to_string(), text_elements: Vec::new(), @@ -2351,6 +2380,7 @@ stream_max_retries = 0 let second_turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "write in new root".to_string(), text_elements: Vec::new(), @@ -2483,6 +2513,7 @@ async fn run_environment_selection_case( let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: format!("run {}", case.name), text_elements: Vec::new(), @@ -2598,6 +2629,7 @@ async fn turn_start_file_change_approval_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -2788,6 +2820,7 @@ async fn turn_start_does_not_stream_apply_patch_change_updates_without_feature_v let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id, + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -2925,6 +2958,7 @@ async fn turn_start_streams_apply_patch_change_updates_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -3055,6 +3089,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<() let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: PARENT_PROMPT.to_string(), text_elements: Vec::new(), @@ -3274,6 +3309,7 @@ config_file = "./custom-role.toml" let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: PARENT_PROMPT.to_string(), text_elements: Vec::new(), @@ -3419,6 +3455,7 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res let turn_1_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch 1".into(), text_elements: Vec::new(), @@ -3491,6 +3528,7 @@ async fn turn_start_file_change_approval_accept_for_session_persists_v2() -> Res let turn_2_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch 2".into(), text_elements: Vec::new(), @@ -3589,6 +3627,7 @@ async fn turn_start_file_change_approval_decline_v2() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "apply patch".into(), text_elements: Vec::new(), @@ -3734,6 +3773,7 @@ async fn command_execution_notifications_include_process_id() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run a command".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs index 7b7a6c2563..ec77af88dd 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start_zsh_fork.rs @@ -117,6 +117,7 @@ async fn turn_start_shell_zsh_fork_executes_command_v2() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run echo hi".to_string(), text_elements: Vec::new(), @@ -235,6 +236,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), @@ -367,6 +369,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> { let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run python".to_string(), text_elements: Vec::new(), @@ -525,6 +528,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2() let turn_id = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "remove both files".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/app-server/tests/suite/v2/turn_steer.rs b/codex-rs/app-server/tests/suite/v2/turn_steer.rs index 0c4dcabe77..3d4b46b91d 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_steer.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_steer.rs @@ -12,10 +12,12 @@ use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE; use codex_app_server::INVALID_PARAMS_ERROR_CODE; use codex_app_server_protocol::AdditionalContextEntry; use codex_app_server_protocol::AdditionalContextKind; +use codex_app_server_protocol::ItemStartedNotification; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadItem; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnStartParams; @@ -67,6 +69,7 @@ async fn turn_steer_requires_active_turn() -> Result<()> { let steer_req = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id.clone(), + client_user_message_id: Some("client-steer-message-1".to_string()), input: vec![V2UserInput::Text { text: "steer".to_string(), text_elements: Vec::new(), @@ -152,6 +155,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run sleep".to_string(), text_elements: Vec::new(), @@ -177,6 +181,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> { let steer_req = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: oversized_input.clone(), text_elements: Vec::new(), @@ -217,10 +222,10 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { let shell_command = vec![ "powershell".to_string(), "-Command".to_string(), - "Start-Sleep -Seconds 10".to_string(), + "Start-Sleep -Seconds 2".to_string(), ]; #[cfg(not(target_os = "windows"))] - let shell_command = vec!["sleep".to_string(), "10".to_string()]; + let shell_command = vec!["sleep".to_string(), "2".to_string()]; let tmp = TempDir::new()?; let codex_home = tmp.path().join("codex_home"); @@ -228,14 +233,16 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { let working_directory = tmp.path().join("workdir"); std::fs::create_dir(&working_directory)?; - let server = - create_mock_responses_server_sequence_unchecked(vec![create_shell_command_sse_response( + let server = create_mock_responses_server_sequence_unchecked(vec![ + create_shell_command_sse_response( shell_command.clone(), Some(&working_directory), Some(10_000), "call_sleep", - )?]) - .await; + )?, + app_test_support::create_final_assistant_message_sse_response("Done")?, + ]) + .await; write_mock_responses_config_toml_with_chatgpt_base_url( &codex_home, &server.uri(), @@ -262,6 +269,7 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run sleep".to_string(), text_elements: Vec::new(), @@ -286,6 +294,7 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { let steer_req = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id.clone(), + client_user_message_id: Some("client-steer-message-1".to_string()), input: vec![V2UserInput::Text { text: "steer".to_string(), text_elements: Vec::new(), @@ -303,6 +312,34 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { let steer: TurnSteerResponse = to_response::(steer_resp)?; assert_eq!(steer.turn_id, turn.id); + timeout(DEFAULT_READ_TIMEOUT, async { + loop { + let notification = mcp + .read_stream_until_notification_message("item/started") + .await?; + let params = notification.params.expect("item/started params"); + let item_started: ItemStartedNotification = + serde_json::from_value(params).expect("deserialize item/started notification"); + let ThreadItem::UserMessage { + client_id, content, .. + } = item_started.item + else { + continue; + }; + if client_id == Some("client-steer-message-1".to_string()) { + assert_eq!( + content, + vec![V2UserInput::Text { + text: "steer".to_string(), + text_elements: Vec::new(), + }] + ); + return Ok::<(), anyhow::Error>(()); + } + } + }) + .await??; + let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_steer_event").await?; assert_eq!(event["event_params"]["thread_id"], thread.id); @@ -316,8 +353,11 @@ async fn turn_steer_returns_active_turn_id() -> Result<()> { serde_json::Value::Null ); - mcp.interrupt_turn_and_wait_for_aborted(thread.id, steer.turn_id, DEFAULT_READ_TIMEOUT) - .await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; Ok(()) } @@ -366,6 +406,7 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu let turn_req = mcp .send_turn_start_request(TurnStartParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "run sleep".to_string(), text_elements: Vec::new(), @@ -396,6 +437,7 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu let steer_req = mcp .send_turn_steer_request(TurnSteerParams { thread_id: thread.id.clone(), + client_user_message_id: None, input: Vec::new(), responsesapi_client_metadata: None, additional_context, diff --git a/codex-rs/app-server/tests/suite/v2/web_search.rs b/codex-rs/app-server/tests/suite/v2/web_search.rs index 927f14ca9d..ef8d562703 100644 --- a/codex-rs/app-server/tests/suite/v2/web_search.rs +++ b/codex-rs/app-server/tests/suite/v2/web_search.rs @@ -7,13 +7,19 @@ use app_test_support::ChatGptAuthFixture; use app_test_support::McpProcess; use app_test_support::to_response; use app_test_support::write_chatgpt_auth; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::ItemStartedNotification; use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadReadParams; +use codex_app_server_protocol::ThreadReadResponse; use codex_app_server_protocol::ThreadStartParams; use codex_app_server_protocol::ThreadStartResponse; use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput as V2UserInput; +use codex_app_server_protocol::WebSearchAction; use codex_config::types::AuthCredentialsStoreMode; use core_test_support::responses; use pretty_assertions::assert_eq; @@ -84,10 +90,12 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> { ) .await??; let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + let thread_id = thread.id.clone(); let turn_req = mcp .send_turn_start_request(TurnStartParams { - thread_id: thread.id, + thread_id: thread_id.clone(), + client_user_message_id: None, input: vec![V2UserInput::Text { text: "Search the web".to_string(), text_elements: Vec::new(), @@ -102,6 +110,13 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> { .await??; let _turn: TurnStartResponse = to_response::(turn_resp)?; + let started = timeout(DEFAULT_READ_TIMEOUT, wait_for_web_search_started(&mut mcp)).await??; + let completed = timeout( + DEFAULT_READ_TIMEOUT, + wait_for_web_search_completed(&mut mcp), + ) + .await??; + timeout( DEFAULT_READ_TIMEOUT, mcp.read_stream_until_notification_message("turn/completed"), @@ -158,10 +173,83 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> { }], }) ); + assert_eq!( + started.item, + ThreadItem::WebSearch { + id: call_id.to_string(), + query: String::new(), + action: Some(WebSearchAction::Other), + } + ); + let expected_completed_item = ThreadItem::WebSearch { + id: call_id.to_string(), + query: "standalone web search".to_string(), + action: Some(WebSearchAction::Search { + query: Some("standalone web search".to_string()), + queries: None, + }), + }; + assert_eq!(completed.item, expected_completed_item); + + drop(mcp); + let mut reloaded_mcp = + McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?; + timeout(DEFAULT_READ_TIMEOUT, reloaded_mcp.initialize()).await??; + let read_req = reloaded_mcp + .send_thread_read_request(ThreadReadParams { + thread_id, + include_turns: true, + }) + .await?; + let read_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + reloaded_mcp.read_stream_until_response_message(RequestId::Integer(read_req)), + ) + .await??; + let ThreadReadResponse { thread, .. } = to_response::(read_resp)?; + let persisted_web_searches: Vec<&ThreadItem> = thread + .turns + .iter() + .flat_map(|turn| &turn.items) + .filter(|item| matches!(item, ThreadItem::WebSearch { .. })) + .collect(); + assert_eq!(persisted_web_searches, vec![&expected_completed_item]); Ok(()) } +async fn wait_for_web_search_started(mcp: &mut McpProcess) -> Result { + loop { + let notification = mcp + .read_stream_until_notification_message("item/started") + .await?; + let started: ItemStartedNotification = serde_json::from_value( + notification + .params + .context("item/started notification should include params")?, + )?; + if matches!(&started.item, ThreadItem::WebSearch { .. }) { + return Ok(started); + } + } +} + +async fn wait_for_web_search_completed(mcp: &mut McpProcess) -> Result { + loop { + let notification = mcp + .read_stream_until_notification_message("item/completed") + .await?; + let completed: ItemCompletedNotification = serde_json::from_value( + notification + .params + .context("item/completed notification should include params")?, + )?; + if matches!(&completed.item, ThreadItem::WebSearch { .. }) { + return Ok(completed); + } + } +} + async fn mount_search_response(server: &MockServer) { Mock::given(method("POST")) .and(path("/api/codex/alpha/search")) diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 36c5e683b2..5a4944f50d 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -208,10 +208,12 @@ async fn run_command_under_sandbox( // In practice, this should be `std::env::current_dir()` because this CLI // does not support `--cwd`, but let's use the config value for consistency. let cwd = config.cwd.clone(); - // For now, we always use the same cwd for both the command and the - // permission profile. In the future, we could add a CLI option to set them - // separately. - let permission_profile_cwd = cwd.clone(); + // Non-Windows sandbox launchers still use `sandbox_policy_cwd` for any + // remaining cwd-dependent policy resolution. `:workspace_roots` entries in + // the effective profile have already been materialized from config roots. + let sandbox_policy_cwd = cwd.clone(); + #[cfg(target_os = "windows")] + let workspace_roots = config.effective_workspace_roots(); let env = create_env( &config.permissions.shell_environment_policy, @@ -222,8 +224,7 @@ async fn run_command_under_sandbox( if let SandboxType::Windows = sandbox_type { #[cfg(target_os = "windows")] { - run_command_under_windows_session(&config, command, cwd, permission_profile_cwd, env) - .await; + run_command_under_windows_session(&config, command, cwd, workspace_roots, env).await; } #[cfg(not(target_os = "windows"))] { @@ -266,7 +267,7 @@ async fn run_command_under_sandbox( command, file_system_sandbox_policy: &file_system_sandbox_policy, network_sandbox_policy, - sandbox_policy_cwd: permission_profile_cwd.as_path(), + sandbox_policy_cwd: sandbox_policy_cwd.as_path(), enforce_managed_network: false, network: network.as_ref(), extra_allow_unix_sockets: allow_unix_sockets, @@ -298,7 +299,7 @@ async fn run_command_under_sandbox( command, cwd.as_path(), &config.permissions.effective_permission_profile(), - permission_profile_cwd.as_path(), + sandbox_policy_cwd.as_path(), use_legacy_landlock, allow_network_for_proxy(managed_network_requirements_enabled), ); @@ -350,7 +351,7 @@ async fn run_command_under_windows_session( config: &Config, command: Vec, cwd: AbsolutePathBuf, - permission_profile_cwd: AbsolutePathBuf, + workspace_roots: Vec, env: std::collections::HashMap, ) -> ! { use codex_core::windows_sandbox::WindowsSandboxLevelExt; @@ -368,7 +369,7 @@ async fn run_command_under_windows_session( let spawned = if use_elevated { spawn_windows_sandbox_session_elevated_for_permission_profile( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), config.codex_home.as_path(), command, cwd.as_path(), @@ -387,7 +388,7 @@ async fn run_command_under_windows_session( } else { spawn_windows_sandbox_session_legacy( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), config.codex_home.as_path(), command, cwd.as_path(), @@ -1125,7 +1126,7 @@ mod tests { } #[tokio::test] - async fn debug_sandbox_uses_explicit_profile_cwd() -> anyhow::Result<()> { + async fn debug_sandbox_uses_explicit_cwd() -> anyhow::Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index e0812e3fdc..e5660301b5 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -50,6 +50,8 @@ mod marketplace_cmd; mod mcp_cmd; mod plugin_cmd; mod remote_control_cmd; +#[cfg(target_os = "windows")] +mod sandbox_setup; mod state_db_recovery; #[cfg(not(windows))] mod wsl_paths; @@ -452,6 +454,10 @@ struct AppServerCommand { )] listen: codex_app_server::AppServerTransport, + /// Use stdio as the transport (equivalent to `--listen stdio://`). + #[arg(long = "stdio", conflicts_with = "listen")] + stdio: bool, + /// Enable remote control for this app-server process. #[arg(long = "remote-control", hide = true)] remote_control: bool, @@ -965,6 +971,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { subcommand, strict_config: app_server_strict_config, listen, + stdio, remote_control, analytics_default_enabled, auth, @@ -978,7 +985,11 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { )?; match subcommand { None => { - let transport = listen; + let transport = if stdio { + codex_app_server::AppServerTransport::Stdio + } else { + listen + }; let auth = auth.try_into_settings()?; let runtime_options = codex_app_server::AppServerRuntimeOptions { remote_control_enabled: remote_control, @@ -1241,6 +1252,16 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { .await?; } Some(Subcommand::Sandbox(mut sandbox_cli)) => { + #[cfg(target_os = "windows")] + if let Some(setup_cli) = sandbox_setup::parse_setup_command(&sandbox_cli.command)? { + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "sandbox setup", + )?; + sandbox_setup::run(setup_cli).await?; + return Ok(()); + } reject_remote_mode_for_subcommand( root_remote.as_deref(), root_remote_auth_token_env.as_deref(), @@ -3197,6 +3218,25 @@ mod tests { ); } + #[test] + fn app_server_stdio_flag_parses() { + let app_server = app_server_from_args(["codex", "app-server", "--stdio"].as_ref()); + assert!(app_server.stdio); + } + + #[test] + fn app_server_stdio_flag_conflicts_with_listen() { + let err = MultitoolCli::try_parse_from([ + "codex", + "app-server", + "--stdio", + "--listen", + "stdio://", + ]) + .expect_err("--stdio and --listen should be rejected together"); + assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict); + } + #[test] fn app_server_listen_unix_socket_url_parses() { let app_server = diff --git a/codex-rs/cli/src/sandbox_setup.rs b/codex-rs/cli/src/sandbox_setup.rs new file mode 100644 index 0000000000..958411c428 --- /dev/null +++ b/codex-rs/cli/src/sandbox_setup.rs @@ -0,0 +1,206 @@ +use std::path::PathBuf; + +use clap::ArgAction; +use clap::ArgGroup; +use clap::Parser; +use codex_core::config::edit::ConfigEditsBuilder; +use codex_core::config::find_codex_home; + +#[derive(Debug, Parser)] +#[command(group( + ArgGroup::new("sandbox_user") + .required(true) + .args(["user", "current_user"]) +))] +pub(crate) struct SandboxSetupCommand { + /// Set up the elevated Windows sandbox. + #[arg(long = "elevated", action = ArgAction::SetTrue)] + elevated_sandbox_level: bool, + + /// Windows user that will run Codex after managed deployment. + #[arg( + long = "user", + value_name = "USER", + conflicts_with = "current_user", + requires = "codex_home" + )] + user: Option, + + /// Use the current Windows user as the Codex user. + #[arg( + long = "current-user", + default_value_t = false, + conflicts_with = "user" + )] + current_user: bool, + + /// CODEX_HOME for the Codex user. Required with --user. + #[arg(long = "codex-home", value_name = "DIR")] + codex_home: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SandboxSetupLevel { + Elevated, +} + +impl SandboxSetupCommand { + fn setup_level(&self) -> anyhow::Result { + if self.elevated_sandbox_level { + Ok(SandboxSetupLevel::Elevated) + } else { + anyhow::bail!("`codex sandbox setup` currently requires --elevated"); + } + } +} + +pub(crate) async fn run(cmd: SandboxSetupCommand) -> anyhow::Result<()> { + match cmd.setup_level()? { + SandboxSetupLevel::Elevated => run_elevated(cmd).await, + } +} + +pub(crate) fn parse_setup_command( + sandbox_command: &[String], +) -> anyhow::Result> { + if sandbox_command + .first() + .is_none_or(|command| command != "setup") + { + return Ok(None); + } + + SandboxSetupCommand::try_parse_from(sandbox_command.iter().map(String::as_str)) + .map(Some) + .map_err(anyhow::Error::from) +} + +async fn run_elevated(cmd: SandboxSetupCommand) -> anyhow::Result<()> { + let identity = resolve_sandbox_setup_identity(&cmd)?; + + codex_core::windows_sandbox::run_elevated_provisioning_setup( + identity.codex_home.as_path(), + identity.real_user.as_str(), + )?; + ConfigEditsBuilder::new(identity.codex_home.as_path()) + .set_windows_sandbox_mode("elevated") + .apply() + .await + .map_err(|err| { + anyhow::anyhow!( + "sandbox provisioning succeeded, but failed to persist elevated sandbox config: {err}" + ) + })?; + + println!( + "Windows elevated sandbox setup completed for {} at {}.", + identity.real_user, + identity.codex_home.display() + ); + Ok(()) +} + +struct SandboxSetupIdentity { + real_user: String, + codex_home: PathBuf, +} + +fn resolve_sandbox_setup_identity( + cmd: &SandboxSetupCommand, +) -> anyhow::Result { + if cmd.current_user { + let real_user = std::env::var("USERNAME") + .or_else(|_| std::env::var("USER")) + .map_err(|err| { + anyhow::anyhow!("failed to determine current user from environment: {err}") + })?; + let codex_home = match cmd.codex_home.clone() { + Some(codex_home) => codex_home, + None => find_codex_home()?.to_path_buf(), + }; + return Ok(SandboxSetupIdentity { + real_user, + codex_home, + }); + } + + let real_user = cmd + .user + .clone() + .ok_or_else(|| anyhow::anyhow!("--user or --current-user is required"))?; + let codex_home = cmd + .codex_home + .clone() + .ok_or_else(|| anyhow::anyhow!("--codex-home is required with --user"))?; + Ok(SandboxSetupIdentity { + real_user, + codex_home, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_managed_user_identity() { + let command = SandboxSetupCommand::try_parse_from([ + "setup", + "--elevated", + "--user", + "DOMAIN\\alice", + "--codex-home", + r"C:\Users\alice\.codex", + ]) + .expect("parse"); + + assert!(command.elevated_sandbox_level); + assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice")); + assert!(!command.current_user); + assert_eq!( + command.codex_home.as_deref(), + Some(std::path::Path::new(r"C:\Users\alice\.codex")) + ); + } + + #[test] + fn requires_explicit_user_identity() { + let err = SandboxSetupCommand::try_parse_from(["setup", "--elevated"]) + .expect_err("parse should fail"); + + assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument); + } + + #[test] + fn requires_codex_home_for_managed_user() { + let err = + SandboxSetupCommand::try_parse_from(["setup", "--elevated", "--user", "DOMAIN\\alice"]) + .expect_err("parse should fail"); + + assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument); + } + + #[test] + fn parses_setup_from_sandbox_command_args() { + let command = parse_setup_command(&[ + "setup".to_string(), + "--elevated".to_string(), + "--user".to_string(), + r"DOMAIN\alice".to_string(), + "--codex-home".to_string(), + r"C:\Users\alice\.codex".to_string(), + ]) + .expect("parse") + .expect("setup command"); + + assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice")); + } + + #[test] + fn ignores_non_setup_sandbox_command_args() { + let command = + parse_setup_command(&["echo".to_string(), "hello".to_string()]).expect("parse"); + + assert!(command.is_none()); + } +} diff --git a/codex-rs/code-mode/src/description.rs b/codex-rs/code-mode/src/description.rs index 1362b51a4c..ca606cc100 100644 --- a/codex-rs/code-mode/src/description.rs +++ b/codex-rs/code-mode/src/description.rs @@ -17,8 +17,8 @@ const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/co - Runs raw JavaScript -- no Node, no file system, no network access, no console. - Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences. - You may optionally start the tool input with a first-line pragma like `// @exec: {"yield_time_ms": 10000, "max_output_tokens": 1000}`. -- `yield_time_ms` asks `exec` to yield early after that many milliseconds if the script is still running. -- `max_output_tokens` sets the token budget for direct `exec` results. By default the result is truncated to 10000 tokens. +- `yield_time_ms` asks `exec` to yield early if the script is still running. Defaults to 10000 ms. +- `max_output_tokens` sets the token budget for direct `exec` results. Defaults to 10000 tokens. - When the JS code is fully evaluated, the isolate's lifetime ends and unawaited promises are silently discarded. - Global helpers: @@ -34,9 +34,9 @@ const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/co - `yield_control()`: yields the accumulated output to the model immediately while the script keeps running."#; const WAIT_DESCRIPTION_TEMPLATE: &str = r#"- Use `wait` only after `exec` returns `Script running with cell ID ...`. - `cell_id` identifies the running `exec` cell to resume. -- `yield_time_ms` controls how long to wait for more output before yielding again. If omitted, `wait` uses its default wait timeout. -- `max_tokens` limits how much new output this wait call returns. -- `terminate: true` stops the running cell instead of waiting for more output. +- `yield_time_ms` controls how long to wait for more output before yielding again. Defaults to 10000 ms. +- `max_tokens` limits how much new output this wait call returns. Defaults to 10000 tokens. +- `terminate: true` stops the running cell; false or omitted waits for output. - `wait` returns only the new output since the last yield, or the final completion or termination result for that cell. - If the cell is still running, `wait` may yield again with the same `cell_id`. - If the cell has already finished, `wait` returns the completed result and closes the cell."#; diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index b1f6f6d4bb..38d8dc9862 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -98,6 +98,7 @@ async fn models_client_hits_models_endpoint() { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, }], }; diff --git a/codex-rs/codex-mcp/src/codex_apps.rs b/codex-rs/codex-mcp/src/codex_apps.rs index eb88ffa6b1..3196a143e8 100644 --- a/codex-rs/codex-mcp/src/codex_apps.rs +++ b/codex-rs/codex-mcp/src/codex_apps.rs @@ -12,7 +12,9 @@ use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::runtime::emit_duration; use crate::tools::MCP_TOOLS_CACHE_WRITE_DURATION_METRIC; use crate::tools::ToolInfo; +use anyhow::Context; use codex_login::CodexAuth; +use codex_protocol::mcp::McpServerInfo; use codex_utils_plugins::mcp_connector::is_connector_id_allowed; use codex_utils_plugins::mcp_connector::sanitize_name; use serde::Deserialize; @@ -20,8 +22,6 @@ use serde::Serialize; use sha1::Digest; use sha1::Sha1; -pub(crate) const CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION: u8 = 3; - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CodexAppsToolsCacheKey { pub(crate) account_id: Option, @@ -44,11 +44,19 @@ pub(crate) struct CodexAppsToolsCacheContext { } impl CodexAppsToolsCacheContext { - pub(crate) fn cache_path(&self) -> PathBuf { + pub(crate) fn tools_cache_path(&self) -> PathBuf { + self.cache_path_in(CODEX_APPS_TOOLS_CACHE_DIR) + } + + pub(crate) fn server_info_cache_path(&self) -> PathBuf { + self.cache_path_in(CODEX_APPS_SERVER_INFO_CACHE_DIR) + } + + fn cache_path_in(&self, cache_dir: &str) -> PathBuf { let user_key_json = serde_json::to_string(&self.user_key).unwrap_or_default(); let user_key_hash = sha1_hex(&user_key_json); self.codex_home - .join(CODEX_APPS_TOOLS_CACHE_DIR) + .join(cache_dir) .join(format!("{user_key_hash}.json")) } } @@ -136,6 +144,7 @@ pub(crate) fn normalize_codex_apps_callable_namespace( pub(crate) fn write_cached_codex_apps_tools_if_needed( server_name: &str, cache_context: Option<&CodexAppsToolsCacheContext>, + server_info: &McpServerInfo, tools: &[ToolInfo], ) { if server_name != CODEX_APPS_MCP_SERVER_NAME { @@ -145,6 +154,9 @@ pub(crate) fn write_cached_codex_apps_tools_if_needed( if let Some(cache_context) = cache_context { let cache_write_start = Instant::now(); write_cached_codex_apps_tools(cache_context, tools); + if let Err(err) = write_cached_codex_apps_server_info(cache_context, server_info) { + tracing::warn!("failed to write Codex Apps server info cache: {err:#}"); + } emit_duration( MCP_TOOLS_CACHE_WRITE_DURATION_METRIC, cache_write_start.elapsed(), @@ -169,6 +181,17 @@ pub(crate) fn load_startup_cached_codex_apps_tools_snapshot( } } +pub(crate) fn load_startup_cached_codex_apps_server_info( + server_name: &str, + cache_context: Option<&CodexAppsToolsCacheContext>, +) -> Option { + if server_name != CODEX_APPS_MCP_SERVER_NAME { + return None; + } + + load_cached_codex_apps_server_info(cache_context?) +} + #[cfg(test)] pub(crate) fn read_cached_codex_apps_tools( cache_context: &CodexAppsToolsCacheContext, @@ -182,7 +205,7 @@ pub(crate) fn read_cached_codex_apps_tools( pub(crate) fn load_cached_codex_apps_tools( cache_context: &CodexAppsToolsCacheContext, ) -> CachedCodexAppsToolsLoad { - let cache_path = cache_context.cache_path(); + let cache_path = cache_context.tools_cache_path(); let bytes = match std::fs::read(cache_path) { Ok(bytes) => bytes, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { @@ -204,7 +227,7 @@ pub(crate) fn write_cached_codex_apps_tools( cache_context: &CodexAppsToolsCacheContext, tools: &[ToolInfo], ) { - let cache_path = cache_context.cache_path(); + let cache_path = cache_context.tools_cache_path(); if let Some(parent) = cache_path.parent() && std::fs::create_dir_all(parent).is_err() { @@ -220,6 +243,42 @@ pub(crate) fn write_cached_codex_apps_tools( let _ = std::fs::write(cache_path, bytes); } +pub(crate) fn load_cached_codex_apps_server_info( + cache_context: &CodexAppsToolsCacheContext, +) -> Option { + let bytes = std::fs::read(cache_context.server_info_cache_path()).ok()?; + let cache: CodexAppsServerInfoDiskCache = serde_json::from_slice(&bytes).ok()?; + (cache.schema_version == CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION) + .then_some(cache.server_info) +} + +fn write_cached_codex_apps_server_info( + cache_context: &CodexAppsToolsCacheContext, + server_info: &McpServerInfo, +) -> anyhow::Result<()> { + let cache_path = cache_context.server_info_cache_path(); + if let Some(parent) = cache_path.parent() { + std::fs::create_dir_all(parent).with_context(|| { + format!( + "failed to create Codex Apps server info cache directory `{}`", + parent.display() + ) + })?; + } + let bytes = serde_json::to_vec_pretty(&CodexAppsServerInfoDiskCache { + schema_version: CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION, + server_info: server_info.clone(), + }) + .context("failed to serialize Codex Apps server info cache")?; + std::fs::write(&cache_path, bytes).with_context(|| { + format!( + "failed to write Codex Apps server info cache `{}`", + cache_path.display() + ) + })?; + Ok(()) +} + pub(crate) fn filter_disallowed_codex_apps_tools(tools: Vec) -> Vec { tools .into_iter() @@ -237,7 +296,17 @@ struct CodexAppsToolsDiskCache { tools: Vec, } +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CodexAppsServerInfoDiskCache { + schema_version: u8, + server_info: McpServerInfo, +} + const CODEX_APPS_TOOLS_CACHE_DIR: &str = "cache/codex_apps_tools"; +pub(crate) const CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION: u8 = 3; + +const CODEX_APPS_SERVER_INFO_CACHE_DIR: &str = "cache/codex_apps_server_info"; +const CODEX_APPS_SERVER_INFO_CACHE_SCHEMA_VERSION: u8 = 1; fn sha1_hex(s: &str) -> String { let mut hasher = Sha1::new(); diff --git a/codex-rs/codex-mcp/src/connection_manager.rs b/codex-rs/codex-mcp/src/connection_manager.rs index da7c9963ac..d15a2e1500 100644 --- a/codex-rs/codex-mcp/src/connection_manager.rs +++ b/codex-rs/codex-mcp/src/connection_manager.rs @@ -9,6 +9,7 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; @@ -44,6 +45,7 @@ use codex_config::McpServerTransportConfig; use codex_config::types::OAuthCredentialsStoreMode; use codex_login::CodexAuth; use codex_protocol::mcp::CallToolResult; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::Event; @@ -62,6 +64,7 @@ use rmcp::model::ReadResourceResult; use rmcp::model::RequestId; use rmcp::model::Resource; use rmcp::model::ResourceTemplate; +use serde_json::Value as JsonValue; use tokio::task::JoinSet; use tokio_util::sync::CancellationToken; use tracing::Instrument; @@ -70,6 +73,34 @@ use tracing::trace; use tracing::trace_span; use tracing::warn; +const MCP_UI_META_KEY: &str = "ui"; +const MCP_UI_VISIBILITY_META_KEY: &str = "visibility"; +const MCP_UI_MODEL_VISIBILITY: &str = "model"; + +/// Returns whether a tool may be included in model-facing tool declarations. +/// +/// Tools without visibility metadata remain visible. +/// Tools with visibility metadata are hidden unless they explicitly include `model`. +/// +/// +pub fn tool_is_model_visible(tool: &ToolInfo) -> bool { + let Some(visibility) = tool + .tool + .meta + .as_deref() + .and_then(|meta| meta.get(MCP_UI_META_KEY)) + .and_then(JsonValue::as_object) + .and_then(|ui| ui.get(MCP_UI_VISIBILITY_META_KEY)) + .and_then(JsonValue::as_array) + else { + return true; + }; + + visibility + .iter() + .any(|target| target.as_str() == Some(MCP_UI_MODEL_VISIBILITY)) +} + /// A thin wrapper around a set of running [`RmcpClient`] instances. pub struct McpConnectionManager { clients: HashMap, @@ -385,13 +416,13 @@ impl McpConnectionManager { pub async fn list_all_tools(&self) -> Vec { let mut tools = Vec::new(); for (server_name, managed_client) in &self.clients { - let has_startup_snapshot = managed_client.startup_snapshot.is_some(); + let has_cached_tool_info_snapshot = managed_client.cached_tool_info_snapshot.is_some(); let startup_complete = managed_client .startup_complete .load(std::sync::atomic::Ordering::Acquire); trace!( server_name = %server_name, - has_startup_snapshot, + has_cached_tool_info_snapshot, startup_complete, "waiting for MCP server tools while building tool list" ); @@ -400,7 +431,7 @@ impl McpConnectionManager { .instrument(trace_span!( "list_tools_for_server", server_name = %server_name, - has_startup_snapshot, + has_cached_tool_info_snapshot, startup_complete )) .await @@ -421,6 +452,31 @@ impl McpConnectionManager { normalize_tools_for_model_with_prefix(tools, self.prefix_mcp_tool_names) } + /// Returns presentation metadata without waiting for uncached clients still initializing. + /// Cached values will be used if available and the server is still starting up. + pub async fn list_available_server_infos(&self) -> HashMap { + let mut server_infos = HashMap::new(); + for (server_name, client) in &self.clients { + if !client.startup_complete.load(Ordering::Acquire) { + if let Some(server_info) = client.cached_server_info.clone() { + server_infos.insert(server_name.clone(), server_info); + } + continue; + } + match client.client().await { + Ok(managed_client) => { + server_infos.insert(server_name.clone(), managed_client.server_info); + } + Err(_) => { + if let Some(server_info) = client.cached_server_info.clone() { + server_infos.insert(server_name.clone(), server_info); + } + } + } + } + server_infos + } + /// Force-refresh codex apps tools by bypassing the in-process cache. /// /// On success, the refreshed tools replace the cache contents and the @@ -456,6 +512,7 @@ impl McpConnectionManager { write_cached_codex_apps_tools_if_needed( CODEX_APPS_MCP_SERVER_NAME, managed_client.codex_apps_tools_cache_context.as_ref(), + &managed_client.server_info, &tools, ); emit_duration( diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index a1e312d543..60a0026eeb 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -1,9 +1,11 @@ use super::*; use crate::codex_apps::CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION; use crate::codex_apps::CodexAppsToolsCacheContext; +use crate::codex_apps::load_startup_cached_codex_apps_server_info; use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot; use crate::codex_apps::read_cached_codex_apps_tools; use crate::codex_apps::write_cached_codex_apps_tools; +use crate::codex_apps::write_cached_codex_apps_tools_if_needed; use crate::declared_openai_file_input_param_names; use crate::elicitation::ElicitationRequestManager; use crate::elicitation::elicitation_is_rejected_by_policy; @@ -20,6 +22,7 @@ use codex_config::Constrained; use codex_config::McpServerConfig; use codex_exec_server::EnvironmentManager; use codex_protocol::ToolName; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::GranularApprovalConfig; use codex_protocol::protocol::McpAuthStatus; @@ -82,6 +85,17 @@ fn create_codex_apps_tools_cache_context( } } +fn create_test_server_info(title: &str) -> McpServerInfo { + McpServerInfo { + name: "codex-apps".to_string(), + title: Some(title.to_string()), + version: "1.0.0".to_string(), + description: None, + icons: None, + website_url: None, + } +} + fn model_tool_names(tools: &[ToolInfo]) -> HashSet { tools .iter() @@ -582,8 +596,8 @@ fn codex_apps_tools_cache_is_scoped_per_user() { assert_eq!(read_user_1[0].callable_name, "one"); assert_eq!(read_user_2[0].callable_name, "two"); assert_ne!( - cache_context_user_1.cache_path(), - cache_context_user_2.cache_path(), + cache_context_user_1.tools_cache_path(), + cache_context_user_2.tools_cache_path(), "each user should get an isolated cache file" ); } @@ -627,7 +641,7 @@ fn codex_apps_tools_cache_is_ignored_when_schema_version_mismatches() { Some("account-one"), Some("user-one"), ); - let cache_path = cache_context.cache_path(); + let cache_path = cache_context.tools_cache_path(); if let Some(parent) = cache_path.parent() { std::fs::create_dir_all(parent).expect("create parent"); } @@ -649,7 +663,7 @@ fn codex_apps_tools_cache_is_ignored_when_json_is_invalid() { Some("account-one"), Some("user-one"), ); - let cache_path = cache_context.cache_path(); + let cache_path = cache_context.tools_cache_path(); if let Some(parent) = cache_path.parent() { std::fs::create_dir_all(parent).expect("create parent"); } @@ -670,21 +684,112 @@ fn startup_cached_codex_apps_tools_loads_from_disk_cache() { CODEX_APPS_MCP_SERVER_NAME, "calendar_search", )]; - write_cached_codex_apps_tools(&cache_context, &cached_tools); + let server_info = create_test_server_info("Codex Apps"); + write_cached_codex_apps_tools_if_needed( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + &server_info, + &cached_tools, + ); - let startup_snapshot = load_startup_cached_codex_apps_tools_snapshot( + let startup_tools = load_startup_cached_codex_apps_tools_snapshot( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ) + .expect("expected startup snapshot to load from cache"); + let cached_server_info = load_startup_cached_codex_apps_server_info( CODEX_APPS_MCP_SERVER_NAME, Some(&cache_context), ); - let startup_tools = startup_snapshot.expect("expected startup snapshot to load from cache"); assert_eq!(startup_tools.len(), 1); assert_eq!(startup_tools[0].server_name, CODEX_APPS_MCP_SERVER_NAME); assert_eq!(startup_tools[0].callable_name, "calendar_search"); + assert_eq!(cached_server_info, Some(server_info)); +} + +#[test] +fn startup_cached_codex_apps_tools_loads_without_server_info_cache() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let cache_path = cache_context.tools_cache_path(); + if let Some(parent) = cache_path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + let bytes = serde_json::to_vec_pretty(&serde_json::json!({ + "schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION, + "tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "calendar_search")], + })) + .expect("serialize"); + std::fs::write(cache_path, bytes).expect("write"); + + let startup_tools = load_startup_cached_codex_apps_tools_snapshot( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ) + .expect("legacy startup snapshot should remain available"); + let cached_server_info = load_startup_cached_codex_apps_server_info( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ); + + assert_eq!(startup_tools.len(), 1); + assert_eq!(startup_tools[0].callable_name, "calendar_search"); + assert_eq!(cached_server_info, None); +} + +#[test] +fn codex_apps_server_info_cache_survives_legacy_tools_cache_write() { + let codex_home = tempdir().expect("tempdir"); + let cache_context = create_codex_apps_tools_cache_context( + codex_home.path().to_path_buf(), + Some("account-one"), + Some("user-one"), + ); + let server_info = create_test_server_info("Codex Apps"); + write_cached_codex_apps_tools_if_needed( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + &server_info, + &[create_test_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_search", + )], + ); + + let cache_path = cache_context.tools_cache_path(); + if let Some(parent) = cache_path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + let bytes = serde_json::to_vec_pretty(&serde_json::json!({ + "schema_version": CODEX_APPS_TOOLS_CACHE_SCHEMA_VERSION - 1, + "tools": [create_test_tool(CODEX_APPS_MCP_SERVER_NAME, "calendar_search")], + })) + .expect("serialize"); + std::fs::write(cache_path, bytes).expect("write legacy tools cache"); + + assert_eq!( + load_startup_cached_codex_apps_server_info( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ), + Some(server_info) + ); + assert!( + load_startup_cached_codex_apps_tools_snapshot( + CODEX_APPS_MCP_SERVER_NAME, + Some(&cache_context), + ) + .is_none() + ); } #[tokio::test] -async fn list_all_tools_uses_startup_snapshot_while_client_is_pending() { +async fn list_all_tools_uses_cached_tool_info_snapshot_while_client_is_pending() { let startup_tools = vec![create_test_tool( CODEX_APPS_MCP_SERVER_NAME, "calendar_create_event", @@ -703,7 +808,8 @@ async fn list_all_tools_uses_startup_snapshot_while_client_is_pending() { CODEX_APPS_MCP_SERVER_NAME.to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: Some(startup_tools), + cached_tool_info_snapshot: Some(startup_tools), + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -722,6 +828,43 @@ async fn list_all_tools_uses_startup_snapshot_while_client_is_pending() { assert_eq!(tool.callable_name, "calendar_create_event"); } +#[tokio::test] +async fn list_available_server_infos_uses_cache_while_client_is_pending() { + let pending_client = futures::future::pending::>() + .boxed() + .shared(); + let approval_policy = Constrained::allow_any(AskForApproval::OnFailure); + let permission_profile = Constrained::allow_any(PermissionProfile::default()); + let mut manager = McpConnectionManager::new_uninitialized( + &approval_policy, + &permission_profile, + /*prefix_mcp_tool_names*/ true, + ); + let server_info = create_test_server_info("Codex Apps"); + manager.clients.insert( + CODEX_APPS_MCP_SERVER_NAME.to_string(), + AsyncManagedClient { + client: pending_client, + cached_tool_info_snapshot: Some(Vec::new()), + cached_server_info: Some(server_info.clone()), + startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), + tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), + cancel_token: CancellationToken::new(), + }, + ); + + let timeout_result = tokio::time::timeout( + Duration::from_millis(10), + manager.list_available_server_infos(), + ) + .await; + let server_infos = timeout_result.expect("server info lookup should not block on startup"); + assert_eq!( + server_infos.get(CODEX_APPS_MCP_SERVER_NAME), + Some(&server_info) + ); +} + #[tokio::test] async fn list_all_tools_accepts_canonical_namespaced_tool_names() { let startup_tools = vec![create_test_tool("rmcp", "echo")]; @@ -739,7 +882,8 @@ async fn list_all_tools_accepts_canonical_namespaced_tool_names() { "rmcp".to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: Some(startup_tools), + cached_tool_info_snapshot: Some(startup_tools), + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -781,7 +925,8 @@ async fn list_all_tools_applies_legacy_mcp_prefix_by_default() { "rmcp".to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: Some(startup_tools), + cached_tool_info_snapshot: Some(startup_tools), + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -807,7 +952,7 @@ async fn list_all_tools_applies_legacy_mcp_prefix_by_default() { } #[tokio::test] -async fn list_all_tools_blocks_while_client_is_pending_without_startup_snapshot() { +async fn list_all_tools_blocks_while_client_is_pending_without_cached_tool_info_snapshot() { let pending_client = futures::future::pending::>() .boxed() .shared(); @@ -822,7 +967,8 @@ async fn list_all_tools_blocks_while_client_is_pending_without_startup_snapshot( CODEX_APPS_MCP_SERVER_NAME.to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: None, + cached_tool_info_snapshot: None, + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -835,7 +981,7 @@ async fn list_all_tools_blocks_while_client_is_pending_without_startup_snapshot( } #[tokio::test] -async fn list_all_tools_does_not_block_when_startup_snapshot_cache_hit_is_empty() { +async fn list_all_tools_does_not_block_when_cached_tool_info_snapshot_is_empty() { let pending_client = futures::future::pending::>() .boxed() .shared(); @@ -850,7 +996,8 @@ async fn list_all_tools_does_not_block_when_startup_snapshot_cache_hit_is_empty( CODEX_APPS_MCP_SERVER_NAME.to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: Some(Vec::new()), + cached_tool_info_snapshot: Some(Vec::new()), + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -864,11 +1011,12 @@ async fn list_all_tools_does_not_block_when_startup_snapshot_cache_hit_is_empty( } #[tokio::test] -async fn list_all_tools_uses_startup_snapshot_when_client_startup_fails() { +async fn list_all_tools_uses_cached_tool_info_snapshot_when_client_startup_fails() { let startup_tools = vec![create_test_tool( CODEX_APPS_MCP_SERVER_NAME, "calendar_create_event", )]; + let server_info = create_test_server_info("Codex Apps"); let failed_client = futures::future::ready::>(Err( StartupOutcomeError::Failed { error: "startup failed".to_string(), @@ -888,7 +1036,8 @@ async fn list_all_tools_uses_startup_snapshot_when_client_startup_fails() { CODEX_APPS_MCP_SERVER_NAME.to_string(), AsyncManagedClient { client: failed_client, - startup_snapshot: Some(startup_tools), + cached_tool_info_snapshot: Some(startup_tools), + cached_server_info: Some(server_info.clone()), startup_complete, tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), @@ -905,6 +1054,13 @@ async fn list_all_tools_uses_startup_snapshot_when_client_startup_fails() { .expect("tool from startup cache"); assert_eq!(tool.server_name, CODEX_APPS_MCP_SERVER_NAME); assert_eq!(tool.callable_name, "calendar_create_event"); + assert_eq!( + manager + .list_available_server_infos() + .await + .get(CODEX_APPS_MCP_SERVER_NAME), + Some(&server_info) + ); } #[tokio::test] @@ -935,7 +1091,8 @@ async fn list_all_tools_adds_server_metadata_to_cached_tools() { server_name.to_string(), AsyncManagedClient { client: pending_client, - startup_snapshot: Some(startup_tools), + cached_tool_info_snapshot: Some(startup_tools), + cached_server_info: None, startup_complete: Arc::new(std::sync::atomic::AtomicBool::new(false)), tool_plugin_provenance: Arc::new(ToolPluginProvenance::default()), cancel_token: CancellationToken::new(), diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index 7b45bcc7a7..83419175d4 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -1,4 +1,5 @@ pub use connection_manager::McpConnectionManager; +pub use connection_manager::tool_is_model_visible; pub use elicitation::ElicitationReviewRequest; pub use elicitation::ElicitationReviewer; pub use elicitation::ElicitationReviewerHandle; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index d6b496ab08..51a6f18686 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -25,6 +25,7 @@ use codex_config::types::ApprovalsReviewer; use codex_config::types::OAuthCredentialsStoreMode; use codex_login::CodexAuth; use codex_plugin::PluginCapabilitySummary; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::mcp::Resource; use codex_protocol::mcp::ResourceTemplate; use codex_protocol::mcp::Tool; @@ -308,6 +309,7 @@ pub async fn read_mcp_resource( #[derive(Debug, Clone)] pub struct McpServerStatusSnapshot { + pub server_infos: HashMap, pub tools_by_server: HashMap>, pub resources: HashMap>, pub resource_templates: HashMap>, @@ -327,6 +329,7 @@ pub async fn collect_mcp_server_status_snapshot_with_detail( let tool_plugin_provenance = tool_plugin_provenance(config); if mcp_servers.is_empty() { return McpServerStatusSnapshot { + server_infos: HashMap::new(), tools_by_server: HashMap::new(), resources: HashMap::new(), resource_templates: HashMap::new(), @@ -599,6 +602,7 @@ async fn collect_mcp_server_status_snapshot_from_manager( } }, ); + let server_infos = mcp_connection_manager.list_available_server_infos().await; let mut tools_by_server = HashMap::>::new(); for tool_info in tools { @@ -614,6 +618,7 @@ async fn collect_mcp_server_status_snapshot_from_manager( } McpServerStatusSnapshot { + server_infos, tools_by_server, resources: convert_mcp_resources(resources), resource_templates: convert_mcp_resource_templates(resource_templates), diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index e268720aff..78078720e7 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -20,6 +20,7 @@ use crate::codex_apps::CachedCodexAppsToolsLoad; use crate::codex_apps::CodexAppsToolsCacheContext; use crate::codex_apps::filter_disallowed_codex_apps_tools; use crate::codex_apps::load_cached_codex_apps_tools; +use crate::codex_apps::load_startup_cached_codex_apps_server_info; use crate::codex_apps::load_startup_cached_codex_apps_tools_snapshot; use crate::codex_apps::normalize_codex_apps_callable_name; use crate::codex_apps::normalize_codex_apps_callable_namespace; @@ -47,6 +48,7 @@ use codex_config::McpServerTransportConfig; use codex_config::types::OAuthCredentialsStoreMode; use codex_exec_server::HttpClient; use codex_exec_server::ReqwestHttpClient; +use codex_protocol::mcp::McpServerInfo; use codex_protocol::protocol::Event; use codex_rmcp_client::ExecutorStdioServerLauncher; use codex_rmcp_client::LocalStdioServerLauncher; @@ -85,6 +87,7 @@ const UNTRUSTED_CONNECTOR_META_KEYS: &[&str] = &[ #[derive(Clone)] pub(crate) struct ManagedClient { pub(crate) client: Arc, + pub(crate) server_info: McpServerInfo, pub(crate) tools: Vec, pub(crate) tool_filter: ToolFilter, pub(crate) tool_timeout: Option, @@ -123,7 +126,8 @@ impl ManagedClient { #[derive(Clone)] pub(crate) struct AsyncManagedClient { pub(crate) client: Shared>>, - pub(crate) startup_snapshot: Option>, + pub(crate) cached_tool_info_snapshot: Option>, + pub(crate) cached_server_info: Option, pub(crate) startup_complete: Arc, pub(crate) tool_plugin_provenance: Arc, pub(crate) cancel_token: CancellationToken, @@ -150,11 +154,16 @@ impl AsyncManagedClient { .configured_config() .map(ToolFilter::from_config) .unwrap_or_default(); - let startup_snapshot = load_startup_cached_codex_apps_tools_snapshot( + let cached_tool_info_snapshot = load_startup_cached_codex_apps_tools_snapshot( &server_name, codex_apps_tools_cache_context.as_ref(), - ) - .map(|tools| filter_tools(tools, &tool_filter)); + ); + let cached_tool_info_snapshot = + cached_tool_info_snapshot.map(|tools| filter_tools(tools, &tool_filter)); + let cached_server_info = load_startup_cached_codex_apps_server_info( + &server_name, + codex_apps_tools_cache_context.as_ref(), + ); let startup_tool_filter = tool_filter; let startup_complete = Arc::new(AtomicBool::new(false)); let startup_complete_for_fut = Arc::clone(&startup_complete); @@ -207,7 +216,7 @@ impl AsyncManagedClient { outcome }; let client = fut.boxed().shared(); - if startup_snapshot.is_some() { + if cached_tool_info_snapshot.is_some() { let startup_task = client.clone(); tokio::spawn(async move { let _ = startup_task.await; @@ -216,7 +225,8 @@ impl AsyncManagedClient { Self { client, - startup_snapshot, + cached_tool_info_snapshot, + cached_server_info, startup_complete, tool_plugin_provenance, cancel_token, @@ -238,9 +248,9 @@ impl AsyncManagedClient { } } - fn startup_snapshot_while_initializing(&self) -> Option> { + fn cached_tool_info_snapshot_while_initializing(&self) -> Option> { if !self.startup_complete.load(Ordering::Acquire) { - return self.startup_snapshot.clone(); + return self.cached_tool_info_snapshot.clone(); } None } @@ -298,12 +308,13 @@ impl AsyncManagedClient { }; // Keep cache payloads raw; plugin provenance is resolved per-session at read time. - let tools = if let Some(startup_tools) = self.startup_snapshot_while_initializing() { + let tools = if let Some(startup_tools) = self.cached_tool_info_snapshot_while_initializing() + { Some(startup_tools) } else { match self.client().await { Ok(client) => Some(client.listed_tools()), - Err(_) => self.startup_snapshot.clone(), + Err(_) => self.cached_tool_info_snapshot.clone(), } }; tools.map(annotate_tools) @@ -506,9 +517,11 @@ async fn start_server_task( fetch_start.elapsed(), &[], ); + let server_info = mcp_server_info_from_implementation(initialize_result.server_info); write_cached_codex_apps_tools_if_needed( &server_name, codex_apps_tools_cache_context.as_ref(), + &server_info, &tools, ); if server_name == CODEX_APPS_MCP_SERVER_NAME { @@ -522,6 +535,7 @@ async fn start_server_task( let managed = ManagedClient { client: Arc::clone(&client), + server_info, tools, tool_timeout: Some(tool_timeout), tool_filter, @@ -533,6 +547,22 @@ async fn start_server_task( Ok(managed) } +fn mcp_server_info_from_implementation(server_info: Implementation) -> McpServerInfo { + McpServerInfo { + name: server_info.name, + title: server_info.title, + version: server_info.version, + description: server_info.description, + icons: server_info.icons.map(|icons| { + icons + .into_iter() + .filter_map(|icon| serde_json::to_value(icon).ok()) + .collect() + }), + website_url: server_info.website_url, + } +} + struct StartServerTaskParams { startup_timeout: Option, // TODO: cancel_token should handle this. tool_timeout: Duration, diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index 93d16d3ccf..9be87746e7 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -245,14 +245,14 @@ impl NetworkUnixSocketPermissionsToml { #[serde(rename_all = "lowercase")] pub enum NetworkUnixSocketPermissionToml { Allow, - None, + Deny, } impl std::fmt::Display for NetworkUnixSocketPermissionToml { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let permission = match self { Self::Allow => "allow", - Self::None => "none", + Self::Deny => "deny", }; f.write_str(permission) } @@ -2868,6 +2868,7 @@ command = "python3 /enterprise/hooks/pre.py" [experimental_network.unix_sockets] "/tmp/example.sock" = "allow" + "/tmp/blocked.sock" = "deny" "#; let source = RequirementSource::CloudRequirements; @@ -2912,10 +2913,16 @@ command = "python3 /enterprise/hooks/pre.py" assert_eq!( sourced_network.value.unix_sockets.as_ref(), Some(&NetworkUnixSocketPermissionsToml { - entries: BTreeMap::from([( - "/tmp/example.sock".to_string(), - NetworkUnixSocketPermissionToml::Allow, - )]), + entries: BTreeMap::from([ + ( + "/tmp/blocked.sock".to_string(), + NetworkUnixSocketPermissionToml::Deny, + ), + ( + "/tmp/example.sock".to_string(), + NetworkUnixSocketPermissionToml::Allow, + ), + ]), }) ); assert_eq!(sourced_network.value.allow_local_binding, Some(false)); @@ -3053,7 +3060,7 @@ command = "python3 /enterprise/hooks/pre.py" ), ( "/tmp/ignored.sock".to_string(), - NetworkUnixSocketPermissionToml::None, + NetworkUnixSocketPermissionToml::Deny, ), ]), }; diff --git a/codex-rs/config/src/permissions_toml.rs b/codex-rs/config/src/permissions_toml.rs index a4ef5d266e..0baec2a5cc 100644 --- a/codex-rs/config/src/permissions_toml.rs +++ b/codex-rs/config/src/permissions_toml.rs @@ -327,14 +327,14 @@ impl NetworkUnixSocketPermissionsToml { #[serde(rename_all = "lowercase")] pub enum NetworkUnixSocketPermissionToml { Allow, - None, + Deny, } impl std::fmt::Display for NetworkUnixSocketPermissionToml { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let permission = match self { Self::Allow => "allow", - Self::None => "none", + Self::Deny => "deny", }; f.write_str(permission) } @@ -547,7 +547,7 @@ impl NetworkToml { NetworkUnixSocketPermissionToml::Allow => { ProxyNetworkUnixSocketPermission::Allow } - NetworkUnixSocketPermissionToml::None => ProxyNetworkUnixSocketPermission::None, + NetworkUnixSocketPermissionToml::Deny => ProxyNetworkUnixSocketPermission::Deny, }; proxy_unix_sockets.entries.insert(path.clone(), permission); } diff --git a/codex-rs/connectors/src/metadata.rs b/codex-rs/connectors/src/metadata.rs index 64becb766d..0a7eebe4e4 100644 --- a/codex-rs/connectors/src/metadata.rs +++ b/codex-rs/connectors/src/metadata.rs @@ -5,7 +5,11 @@ pub fn connector_display_label(connector: &AppInfo) -> String { } pub fn connector_mention_slug(connector: &AppInfo) -> String { - crate::connector_name_slug(&connector_display_label(connector)) + connector_mention_slug_from_name(&connector_display_label(connector)) +} + +pub fn connector_mention_slug_from_name(name: &str) -> String { + crate::connector_name_slug(name) } pub fn connector_install_url(name: &str, connector_id: &str) -> String { diff --git a/codex-rs/core-skills/src/injection.rs b/codex-rs/core-skills/src/injection.rs index df62f42e85..45979fa5c4 100644 --- a/codex-rs/core-skills/src/injection.rs +++ b/codex-rs/core-skills/src/injection.rs @@ -132,7 +132,7 @@ pub fn collect_explicit_skill_mentions( let mut blocked_plain_names: HashSet = HashSet::new(); for input in inputs { - if let UserInput::Skill { name, path } = input { + if let UserInput::Skill { name, path, .. } = input { blocked_plain_names.insert(name.clone()); let Ok(path) = AbsolutePathBuf::relative_to_current_dir(path) else { continue; diff --git a/codex-rs/core-skills/src/loader.rs b/codex-rs/core-skills/src/loader.rs index 00d1cbba14..8663737ee5 100644 --- a/codex-rs/core-skills/src/loader.rs +++ b/codex-rs/core-skills/src/loader.rs @@ -235,6 +235,7 @@ pub(crate) async fn skill_roots( config_layer_stack: &ConfigLayerStack, cwd: &AbsolutePathBuf, plugin_skill_roots: Vec, + extra_skill_roots: Vec, ) -> Vec { let home_dir = home_dir().and_then(|path| AbsolutePathBuf::from_absolute_path_checked(path).ok()); @@ -244,6 +245,7 @@ pub(crate) async fn skill_roots( cwd, home_dir.as_ref(), plugin_skill_roots, + extra_skill_roots, ) .await } @@ -254,6 +256,7 @@ async fn skill_roots_with_home_dir( cwd: &AbsolutePathBuf, home_dir: Option<&AbsolutePathBuf>, plugin_skill_roots: Vec, + extra_skill_roots: Vec, ) -> Vec { let mut roots = skill_roots_from_layer_stack_inner(config_layer_stack, home_dir, fs.clone()); roots.extend(plugin_skill_roots.into_iter().map(|root| SkillRoot { @@ -263,6 +266,13 @@ async fn skill_roots_with_home_dir( plugin_id: Some(root.plugin_id), plugin_root: Some(root.plugin_root), })); + roots.extend(extra_skill_roots.into_iter().map(|path| SkillRoot { + path, + scope: SkillScope::User, + file_system: Arc::clone(&LOCAL_FS), + plugin_id: None, + plugin_root: None, + })); roots.extend(repo_agents_skill_roots(fs, config_layer_stack, cwd).await); dedupe_skill_roots_by_path(&mut roots); roots @@ -1051,7 +1061,15 @@ pub(crate) async fn skill_roots_from_layer_stack( cwd: &AbsolutePathBuf, home_dir: Option<&AbsolutePathBuf>, ) -> Vec { - skill_roots_with_home_dir(Some(fs), config_layer_stack, cwd, home_dir, Vec::new()).await + skill_roots_with_home_dir( + Some(fs), + config_layer_stack, + cwd, + home_dir, + Vec::new(), + Vec::new(), + ) + .await } #[cfg(test)] diff --git a/codex-rs/core-skills/src/loader_tests.rs b/codex-rs/core-skills/src/loader_tests.rs index 84867ca66b..69e357d93d 100644 --- a/codex-rs/core-skills/src/loader_tests.rs +++ b/codex-rs/core-skills/src/loader_tests.rs @@ -1900,6 +1900,7 @@ async fn skill_roots_include_admin_with_lowest_priority() { &cfg.config_layer_stack, &cfg.cwd, Vec::new(), + Vec::new(), ) .await .into_iter() diff --git a/codex-rs/core-skills/src/manager.rs b/codex-rs/core-skills/src/manager.rs index db19322acf..185eaa9320 100644 --- a/codex-rs/core-skills/src/manager.rs +++ b/codex-rs/core-skills/src/manager.rs @@ -51,6 +51,7 @@ impl SkillsLoadInput { pub struct SkillsManager { codex_home: AbsolutePathBuf, restriction_product: Option, + extra_roots: RwLock>, cache_by_cwd: RwLock>, cache_by_config: RwLock>, } @@ -68,6 +69,7 @@ impl SkillsManager { let manager = Self { codex_home, restriction_product, + extra_roots: RwLock::new(Vec::new()), cache_by_cwd: RwLock::new(HashMap::new()), cache_by_config: RwLock::new(HashMap::new()), }; @@ -81,6 +83,17 @@ impl SkillsManager { manager } + pub fn set_extra_roots(&self, extra_roots: Vec) { + { + let mut roots = self + .extra_roots + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *roots = extra_roots; + } + self.clear_cache(); + } + /// Load skills for an already-constructed [`Config`], avoiding any additional config-layer /// loading. /// @@ -118,6 +131,7 @@ impl SkillsManager { &input.config_layer_stack, &input.cwd, input.effective_skill_roots.clone(), + self.extra_roots(), ) .await; if !input.bundled_skills_enabled { @@ -145,6 +159,7 @@ impl SkillsManager { &input.config_layer_stack, &input.cwd, input.effective_skill_roots.clone(), + self.extra_roots(), ) .await; if !bundled_skills_enabled_from_stack(&input.config_layer_stack) { @@ -214,6 +229,13 @@ impl SkillsManager { Err(err) => err.into_inner().get(cache_key).cloned(), } } + + fn extra_roots(&self) -> Vec { + match self.extra_roots.read() { + Ok(roots) => roots.clone(), + Err(err) => err.into_inner().clone(), + } + } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/codex-rs/core-skills/src/manager_tests.rs b/codex-rs/core-skills/src/manager_tests.rs index 4afa83e21e..713b94d7b1 100644 --- a/codex-rs/core-skills/src/manager_tests.rs +++ b/codex-rs/core-skills/src/manager_tests.rs @@ -221,6 +221,128 @@ async fn skills_for_config_reuses_cache_for_same_effective_config() { assert_eq!(outcome2.skills, outcome1.skills); } +#[tokio::test] +async fn set_extra_roots_replaces_runtime_roots_and_clears_cache() { + let codex_home = tempfile::tempdir().expect("tempdir"); + let cwd = tempfile::tempdir().expect("tempdir"); + let extra_root = tempfile::tempdir().expect("tempdir"); + let config_layer_stack = config_stack(&codex_home, ""); + let skills_manager = SkillsManager::new( + codex_home.path().abs(), + /*bundled_skills_enabled*/ true, + ); + + let skills_input = SkillsLoadInput::new( + cwd.path().abs(), + Vec::new(), + config_layer_stack.clone(), + bundled_skills_enabled_from_stack(&config_layer_stack), + ); + let empty_outcome = skills_manager + .skills_for_cwd( + &skills_input, + /*force_reload*/ false, + Some(Arc::clone(&LOCAL_FS)), + ) + .await; + assert!( + empty_outcome + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); + + let extra_skills_root = extra_root.path().join("skills"); + let skill_dir = extra_skills_root.join("runtime-skill"); + fs::create_dir_all(&skill_dir).expect("create skill dir"); + fs::write( + skill_dir.join("SKILL.md"), + "---\nname: runtime-skill\ndescription: runtime skill\n---\n\n# Body\n", + ) + .expect("write skill"); + skills_manager.set_extra_roots(vec![extra_skills_root.abs()]); + + let runtime_outcome = skills_manager + .skills_for_cwd( + &skills_input, + /*force_reload*/ false, + Some(Arc::clone(&LOCAL_FS)), + ) + .await; + assert!( + runtime_outcome + .skills + .iter() + .any(|skill| skill.name == "runtime-skill") + ); + + skills_manager.set_extra_roots(vec![extra_root.path().join("missing-skills").abs()]); + let replaced_outcome = skills_manager + .skills_for_cwd( + &skills_input, + /*force_reload*/ false, + Some(Arc::clone(&LOCAL_FS)), + ) + .await; + assert_eq!(replaced_outcome.errors, Vec::new()); + assert!( + replaced_outcome + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); +} + +#[tokio::test] +async fn set_extra_roots_applies_to_config_loads_and_empty_clears() { + let codex_home = tempfile::tempdir().expect("tempdir"); + let cwd = tempfile::tempdir().expect("tempdir"); + let extra_root = tempfile::tempdir().expect("tempdir"); + let config_layer_stack = config_stack(&codex_home, ""); + let skills_manager = SkillsManager::new( + codex_home.path().abs(), + /*bundled_skills_enabled*/ true, + ); + + let empty_outcome = + skills_for_config_with_stack(&skills_manager, &cwd, &config_layer_stack, &[]).await; + assert!( + empty_outcome + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); + + let extra_skills_root = extra_root.path().join("skills"); + let skill_dir = extra_skills_root.join("runtime-skill"); + fs::create_dir_all(&skill_dir).expect("create skill dir"); + fs::write( + skill_dir.join("SKILL.md"), + "---\nname: runtime-skill\ndescription: runtime skill\n---\n\n# Body\n", + ) + .expect("write skill"); + skills_manager.set_extra_roots(vec![extra_skills_root.abs()]); + + let runtime_outcome = + skills_for_config_with_stack(&skills_manager, &cwd, &config_layer_stack, &[]).await; + assert!( + runtime_outcome + .skills + .iter() + .any(|skill| skill.name == "runtime-skill") + ); + + skills_manager.set_extra_roots(Vec::new()); + let cleared_outcome = + skills_for_config_with_stack(&skills_manager, &cwd, &config_layer_stack, &[]).await; + assert!( + cleared_outcome + .skills + .iter() + .all(|skill| skill.name != "runtime-skill") + ); +} + #[tokio::test] async fn skills_for_config_disables_plugin_skills_by_name() { let codex_home = tempfile::tempdir().expect("tempdir"); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index ab855d733b..b7bdff813b 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -473,6 +473,9 @@ "image_generation": { "type": "boolean" }, + "imagegenext": { + "type": "boolean" + }, "in_app_browser": { "type": "boolean" }, @@ -1770,7 +1773,7 @@ "NetworkProxyUnixSocketPermissionToml": { "enum": [ "allow", - "none" + "deny" ], "type": "string" }, @@ -1822,7 +1825,7 @@ "NetworkUnixSocketPermissionToml": { "enum": [ "allow", - "none" + "deny" ], "type": "string" }, @@ -4564,6 +4567,9 @@ "image_generation": { "type": "boolean" }, + "imagegenext": { + "type": "boolean" + }, "in_app_browser": { "type": "boolean" }, diff --git a/codex-rs/core/src/agent/control.rs b/codex-rs/core/src/agent/control.rs index 8f25074d76..7e87bf73d6 100644 --- a/codex-rs/core/src/agent/control.rs +++ b/codex-rs/core/src/agent/control.rs @@ -704,22 +704,6 @@ impl AgentControl { result } - /// Append a prebuilt message to an existing agent thread outside the normal user-input path. - #[cfg(test)] - pub(crate) async fn append_message( - &self, - agent_id: ThreadId, - message: ResponseItem, - ) -> CodexResult { - let state = self.upgrade()?; - self.handle_thread_request_result( - agent_id, - &state, - state.append_message(agent_id, message).await, - ) - .await - } - pub(crate) async fn send_inter_agent_communication( &self, agent_id: ThreadId, @@ -788,15 +772,45 @@ impl AgentControl { /// agent and any live descendants reached from the in-memory tree. pub(crate) async fn close_agent(&self, agent_id: ThreadId) -> CodexResult { let state = self.upgrade()?; - if let Ok(thread) = state.get_thread(agent_id).await - && let Some(state_db_ctx) = thread.state_db() - && let Err(err) = state_db_ctx - .set_thread_spawn_edge_status(agent_id, DirectionalThreadSpawnEdgeStatus::Closed) - .await - { - warn!("failed to persist thread-spawn edge status for {agent_id}: {err}"); + let known_agent = self.state.agent_metadata_for_thread(agent_id).is_some(); + match state.get_thread(agent_id).await { + Ok(thread) => { + if let Some(state_db_ctx) = thread.state_db() + && let Err(err) = state_db_ctx + .set_thread_spawn_edge_status( + agent_id, + DirectionalThreadSpawnEdgeStatus::Closed, + ) + .await + { + warn!("failed to persist thread-spawn edge status for {agent_id}: {err}"); + } + } + Err(CodexErr::ThreadNotFound(_)) if known_agent => { + if let Some(state_db_ctx) = state.state_db() + && let Err(err) = state_db_ctx + .set_thread_spawn_edge_status( + agent_id, + DirectionalThreadSpawnEdgeStatus::Closed, + ) + .await + { + return Err(CodexErr::Fatal(format!( + "failed to persist stale thread-spawn edge status for {agent_id}: {err}" + ))); + } + } + Err(CodexErr::ThreadNotFound(_)) => {} + Err(err) => { + warn!("failed to inspect agent before close {agent_id}: {err}"); + } + } + match Box::pin(self.shutdown_agent_tree(agent_id)).await { + Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) if known_agent => { + Ok(String::new()) + } + result => result, } - Box::pin(self.shutdown_agent_tree(agent_id)).await } /// Shut down `agent_id` and any live descendants reachable from the in-memory spawn tree. @@ -1282,8 +1296,10 @@ pub(crate) fn render_input_preview(initial_operation: &Op) -> String { UserInput::LocalImage { path, .. } => { format!("[local_image:{}]", path.display()) } - UserInput::Skill { name, path } => format!("[skill:${name}]({})", path.display()), - UserInput::Mention { name, path } => format!("[mention:${name}]({path})"), + UserInput::Skill { name, path, .. } => { + format!("[skill:${name}]({})", path.display()) + } + UserInput::Mention { name, path, .. } => format!("[mention:${name}]({path})"), _ => "[input]".to_string(), }) .collect::>() diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs index b5ba938ef7..43a6e47bfd 100644 --- a/codex-rs/core/src/agent/control_tests.rs +++ b/codex-rs/core/src/agent/control_tests.rs @@ -518,60 +518,6 @@ async fn send_inter_agent_communication_without_turn_queues_message_without_trig )); } -#[tokio::test] -async fn append_message_records_assistant_message() { - let harness = AgentControlHarness::new().await; - let (thread_id, thread) = harness.start_thread().await; - let message = - "author: /root\nrecipient: /root/worker\nother_recipients: []\nContent: hello from tests"; - - let submission_id = harness - .control - .append_message( - thread_id, - ResponseItem::Message { - id: None, - role: "assistant".to_string(), - content: vec![ContentItem::InputText { - text: message.to_string(), - }], - phase: None, - }, - ) - .await - .expect("append_message should succeed"); - assert!(!submission_id.is_empty()); - - timeout(Duration::from_secs(5), async { - loop { - let history_items = thread - .codex - .session - .clone_history() - .await - .raw_items() - .to_vec(); - let recorded = history_items.iter().any(|item| { - matches!( - item, - ResponseItem::Message { role, content, .. } - if role == "assistant" - && content.iter().any(|content_item| matches!( - content_item, - ContentItem::InputText { text } if text == message - )) - ) - }); - if recorded { - break; - } - sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("assistant message should be recorded"); -} - #[tokio::test] async fn spawn_agent_creates_thread_and_sends_prompt() { let harness = AgentControlHarness::new().await; diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 6c87400edd..f47be864fb 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -218,6 +218,7 @@ impl RequestRouteTelemetry { #[derive(Debug, Clone)] pub struct ModelClient { state: Arc, + prompt_cache_key_override: Option, } /// A turn-scoped streaming session created from a [`ModelClient`]. @@ -352,9 +353,24 @@ impl ModelClient { disable_websockets: AtomicBool::new(false), cached_websocket_session: StdMutex::new(WebsocketSession::default()), }), + prompt_cache_key_override: None, } } + pub(crate) fn with_prompt_cache_key_override( + mut self, + prompt_cache_key_override: Option, + ) -> Self { + self.prompt_cache_key_override = prompt_cache_key_override; + self + } + + fn prompt_cache_key(&self) -> String { + self.prompt_cache_key_override + .clone() + .unwrap_or_else(|| self.state.thread_id.to_string()) + } + /// Creates a fresh turn-scoped streaming session. /// /// This constructor does not perform network I/O itself; the session opens a websocket lazily @@ -749,7 +765,7 @@ impl ModelClient { &prompt.output_schema, prompt.output_schema_strict, ); - let prompt_cache_key = Some(self.state.thread_id.to_string()); + let prompt_cache_key = Some(self.prompt_cache_key()); let service_tier = model_info.service_tier_for_request(service_tier); let request = ResponsesApiRequest { model: model_info.slug.clone(), diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 2afbeb45c9..3c55f63761 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -218,6 +218,7 @@ pub(crate) async fn run_codex_thread_one_shot( .send(Submission { id: "shutdown".to_string(), op: Op::Shutdown {}, + client_user_message_id: None, trace: None, }) .await; diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 66cde8d1ea..04f6ae3965 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -129,6 +129,7 @@ async fn forward_ops_preserves_submission_trace_context() { let submission = Submission { id: "sub-1".to_string(), op: Op::Interrupt, + client_user_message_id: None, trace: Some(codex_protocol::protocol::W3cTraceContext { traceparent: Some( "00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(), diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index cec34c67b9..dec1ce6895 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -18,7 +18,6 @@ use codex_protocol::mcp::CallToolResult; use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::ContentItem; use codex_protocol::models::PermissionProfile; -use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AdditionalContextEntry; @@ -230,6 +229,17 @@ impl CodexThread { self.codex.submit_with_trace(op, trace).await } + pub async fn submit_user_input_with_client_user_message_id( + &self, + op: Op, + trace: Option, + client_user_message_id: Option, + ) -> CodexResult { + self.codex + .submit_user_input_with_client_user_message_id(op, trace, client_user_message_id) + .await + } + /// Persist whether this thread is eligible for future memory generation. pub async fn set_thread_memory_mode(&self, mode: ThreadMemoryMode) -> anyhow::Result<()> { self.codex.set_thread_memory_mode(mode).await @@ -240,6 +250,7 @@ impl CodexThread { input: Vec, additional_context: BTreeMap, expected_turn_id: Option<&str>, + client_user_message_id: Option, responsesapi_client_metadata: Option>, ) -> Result { self.codex @@ -247,20 +258,22 @@ impl CodexThread { input, additional_context, expected_turn_id, + client_user_message_id, responsesapi_client_metadata, ) .await } - /// Injects hidden model-visible items into the currently active turn. + /// Injects model-visible items into the currently active turn. /// - /// This is the runtime-owned counterpart to user-facing `steer_input`. + /// This is the thread-level bridge to `Session::inject_if_running` for + /// callers that only hold a `CodexThread`. /// It returns the unchanged items when this thread has no active turn. - pub async fn inject_response_items_into_active_turn( + pub async fn inject_if_running( &self, - items: Vec, - ) -> Result<(), Vec> { - self.codex.session.inject_response_items(items).await + items: Vec, + ) -> Result<(), Vec> { + self.codex.session.inject_if_running(items).await } pub async fn set_app_server_client_info( @@ -366,61 +379,19 @@ impl CodexThread { /// Records a user-role session-prefix message without creating a new user turn boundary. pub(crate) async fn inject_user_message_without_turn(&self, message: String) { - let message = ResponseItem::Message { + let item = ResponseItem::Message { id: None, role: "user".to_string(), content: vec![ContentItem::InputText { text: message }], phase: None, }; - let pending_item = match pending_message_input_item(&message) { - Ok(pending_item) => pending_item, - Err(err) => { - debug_assert!(false, "session-prefix message append should succeed: {err}"); - return; - } - }; - if self - .codex + self.codex .session - .inject_response_items(vec![pending_item]) - .await - .is_err() - { - let turn_context = self.codex.session.new_default_turn().await; - self.codex - .session - .record_conversation_items(turn_context.as_ref(), &[message]) - .await; - } + .inject_no_new_turn(vec![item], /*current_turn_context*/ None) + .await; } - /// Append a prebuilt message to the thread history without treating it as a user turn. - /// - /// If the thread already has an active turn, the message is queued as pending input for that - /// turn. Otherwise it is queued at session scope and a regular turn is started so the agent - /// can consume that pending input through the normal turn pipeline. - #[cfg(test)] - pub(crate) async fn append_message(&self, message: ResponseItem) -> CodexResult { - let submission_id = uuid::Uuid::new_v4().to_string(); - let pending_item = pending_message_input_item(&message)?; - if let Err(items) = self - .codex - .session - .inject_response_items(vec![pending_item]) - .await - { - self.codex - .session - .input_queue - .queue_response_items_for_next_turn(items) - .await; - self.codex.session.maybe_start_turn_for_pending_work().await; - } - - Ok(submission_id) - } - - /// Append raw Responses API items to the thread's model-visible history. + /// Record raw Responses API items without starting a new turn. pub async fn inject_response_items(&self, items: Vec) -> CodexResult<()> { if items.is_empty() { return Err(CodexErr::InvalidRequest( @@ -437,7 +408,7 @@ impl CodexThread { } self.codex .session - .record_conversation_items(turn_context.as_ref(), &items) + .inject_no_new_turn(items, Some(turn_context.as_ref())) .await; self.codex.session.flush_rollout().await?; Ok(()) @@ -598,21 +569,3 @@ impl CodexThread { Ok(*guard) } } - -fn pending_message_input_item(message: &ResponseItem) -> CodexResult { - match message { - ResponseItem::Message { - role, - content, - phase, - .. - } => Ok(ResponseInputItem::Message { - role: role.clone(), - content: content.clone(), - phase: phase.clone(), - }), - _ => Err(CodexErr::InvalidRequest( - "append_message only supports ResponseItem::Message".to_string(), - )), - } -} diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index 1a6256ad76..fd388b273c 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -568,7 +568,7 @@ async fn drain_to_completed( }; match event { Ok(ResponseEvent::OutputItemDone(item)) => { - sess.record_into_history(std::slice::from_ref(&item), turn_context) + sess.record_conversation_items(turn_context, std::slice::from_ref(&item)) .await; } Ok(ResponseEvent::ServerReasoningIncluded(included)) => { diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index e8866aab3a..9501035625 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1554,7 +1554,6 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std:: .await?; let cwd_root = cwd.path().abs(); - let memories_root = codex_home.path().join("memories").abs(); assert_eq!( config.permissions.file_system_sandbox_policy(), FileSystemSandboxPolicy::restricted(vec![ @@ -1576,18 +1575,12 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std:: }, access: FileSystemAccessMode::Read, }, - FileSystemSandboxEntry { - path: FileSystemPath::Path { - path: memories_root.clone(), - }, - access: FileSystemAccessMode::Write, - }, ]), ); assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![memories_root], + writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -1816,7 +1809,7 @@ async fn managed_unrestricted_permission_profile_still_enables_network_requireme } #[tokio::test] -async fn permission_profile_override_applies_runtime_roots_to_legacy_projection() +async fn permission_profile_override_keeps_memories_root_out_of_legacy_projection() -> std::io::Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; @@ -1851,7 +1844,7 @@ async fn permission_profile_override_applies_runtime_roots_to_legacy_projection( let memories_root = codex_home.path().join("memories").abs(); assert!( - config + !config .permissions .file_system_sandbox_policy() .can_write_path_with_cwd(memories_root.as_path(), cwd.path()) @@ -1859,7 +1852,7 @@ async fn permission_profile_override_applies_runtime_roots_to_legacy_projection( assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![memories_root], + writable_roots: vec![], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -2757,9 +2750,6 @@ async fn permissions_profiles_allow_direct_write_roots_outside_workspace_root() description: Some("Workspace access.".to_string()), }] ); - let memories_root = AbsolutePathBuf::from_absolute_path(std::fs::canonicalize( - codex_home.path().join("memories"), - )?)?; assert!( config .permissions @@ -2769,7 +2759,7 @@ async fn permissions_profiles_allow_direct_write_roots_outside_workspace_root() assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::WorkspaceWrite { - writable_roots: vec![external_write_path, memories_root], + writable_roots: vec![external_write_path], network_access: false, exclude_tmpdir_env_var: true, exclude_slash_tmp: true, @@ -4514,13 +4504,15 @@ async fn sqlite_home_defaults_to_codex_home_for_workspace_write() -> std::io::Re } #[tokio::test] -async fn workspace_write_always_includes_memories_root_once() -> std::io::Result<()> { +async fn workspace_write_includes_configured_writable_root_once_without_memories_root() +-> std::io::Result<()> { let codex_home = TempDir::new()?; let memories_root = codex_home.path().join("memories"); + let writable_root = codex_home.path().join("writable").abs(); let config = Config::load_from_base_config_with_overrides( ConfigToml { sandbox_workspace_write: Some(SandboxWorkspaceWrite { - writable_roots: vec![memories_root.abs()], + writable_roots: vec![writable_root.clone(), writable_root.clone()], ..Default::default() }), ..Default::default() @@ -4540,21 +4532,22 @@ async fn workspace_write_always_includes_memories_root_once() -> std::io::Result } } else { assert!( - memories_root.is_dir(), - "expected memories root directory to exist at {}", + !memories_root.exists(), + "expected config load not to create memories root at {}", memories_root.display() ); let expected_memories_root = memories_root.abs(); match &config.legacy_sandbox_policy() { SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + assert!(!writable_roots.contains(&expected_memories_root)); assert_eq!( writable_roots .iter() - .filter(|root| **root == expected_memories_root) + .filter(|root| **root == writable_root) .count(), 1, "expected single writable root entry for {}", - expected_memories_root.display() + writable_root.display() ); } other => panic!("expected workspace-write policy, got {other:?}"), @@ -4564,6 +4557,62 @@ async fn workspace_write_always_includes_memories_root_once() -> std::io::Result Ok(()) } +#[tokio::test] +async fn memory_tool_makes_memories_root_readable_without_creating_or_widening_writes() +-> std::io::Result<()> { + let codex_home = TempDir::new()?; + let cwd = TempDir::new()?; + let memories_root = codex_home.path().join("memories"); + let memories_root_abs = memories_root.abs(); + + let config = Config::load_from_base_config_with_overrides( + ConfigToml { + features: Some(FeaturesToml::from(BTreeMap::from([( + "memories".to_string(), + true, + )]))), + sandbox_workspace_write: Some(SandboxWorkspaceWrite { + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + ..Default::default() + }), + ..Default::default() + }, + ConfigOverrides { + cwd: Some(cwd.path().to_path_buf()), + sandbox_mode: Some(SandboxMode::WorkspaceWrite), + ..Default::default() + }, + codex_home.abs(), + ) + .await?; + + assert!( + !memories_root.exists(), + "expected config load not to create memories root at {}", + memories_root.display() + ); + let file_system_policy = config.permissions.file_system_sandbox_policy(); + assert!(file_system_policy.can_read_path_with_cwd(memories_root_abs.as_path(), cwd.path())); + assert!(!file_system_policy.can_write_path_with_cwd(memories_root_abs.as_path(), cwd.path())); + + if cfg!(target_os = "windows") { + match &config.legacy_sandbox_policy() { + SandboxPolicy::ReadOnly { .. } => {} + other => panic!("expected read-only policy on Windows, got {other:?}"), + } + } else { + match &config.legacy_sandbox_policy() { + SandboxPolicy::WorkspaceWrite { writable_roots, .. } => { + assert!(!writable_roots.contains(&memories_root_abs)); + } + other => panic!("expected workspace-write policy, got {other:?}"), + } + } + + Ok(()) +} + #[tokio::test] async fn config_defaults_to_file_cli_auth_store_mode() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 290edf6fb8..862660ba2e 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -24,6 +24,8 @@ use toml_edit::value; const NOTICE_TABLE_KEY: &str = "notice"; +mod document_helpers; + /// Discrete config mutations supported by the persistence engine. #[derive(Clone, Debug)] pub enum ConfigEdit { @@ -198,319 +200,6 @@ pub fn model_availability_nux_count_edits(shown_count: &HashMap) -> edits } -// TODO(jif) move to a dedicated file -mod document_helpers { - use codex_config::types::AppToolApproval; - use codex_config::types::McpServerConfig; - use codex_config::types::McpServerEnvVar; - use codex_config::types::McpServerToolConfig; - use codex_config::types::McpServerTransportConfig; - use codex_config::types::ToolSuggestDisabledTool; - use codex_config::types::ToolSuggestDiscoverableType; - use toml_edit::Array as TomlArray; - use toml_edit::InlineTable; - use toml_edit::Item as TomlItem; - use toml_edit::Table as TomlTable; - use toml_edit::Value as TomlValue; - use toml_edit::value; - - pub(super) fn ensure_table_for_write(item: &mut TomlItem) -> Option<&mut TomlTable> { - match item { - TomlItem::Table(table) => Some(table), - TomlItem::Value(value) => { - if let Some(inline) = value.as_inline_table() { - *item = TomlItem::Table(table_from_inline(inline)); - item.as_table_mut() - } else { - *item = TomlItem::Table(new_implicit_table()); - item.as_table_mut() - } - } - TomlItem::None => { - *item = TomlItem::Table(new_implicit_table()); - item.as_table_mut() - } - _ => None, - } - } - - pub(super) fn ensure_table_for_read(item: &mut TomlItem) -> Option<&mut TomlTable> { - match item { - TomlItem::Table(table) => Some(table), - TomlItem::Value(value) => { - let inline = value.as_inline_table()?; - *item = TomlItem::Table(table_from_inline(inline)); - item.as_table_mut() - } - _ => None, - } - } - - fn serialize_mcp_server_table(config: &McpServerConfig) -> TomlTable { - let mut entry = TomlTable::new(); - entry.set_implicit(false); - - match &config.transport { - McpServerTransportConfig::Stdio { - command, - args, - env, - env_vars, - cwd, - } => { - entry["command"] = value(command.clone()); - if !args.is_empty() { - entry["args"] = array_from_iter(args.iter().cloned()); - } - if let Some(env) = env - && !env.is_empty() - { - entry["env"] = table_from_pairs(env.iter()); - } - if !env_vars.is_empty() { - entry["env_vars"] = array_from_env_vars(env_vars); - } - if let Some(cwd) = cwd { - entry["cwd"] = value(cwd.to_string_lossy().to_string()); - } - } - McpServerTransportConfig::StreamableHttp { - url, - bearer_token_env_var, - http_headers, - env_http_headers, - } => { - entry["url"] = value(url.clone()); - if let Some(env_var) = bearer_token_env_var { - entry["bearer_token_env_var"] = value(env_var.clone()); - } - if let Some(headers) = http_headers - && !headers.is_empty() - { - entry["http_headers"] = table_from_pairs(headers.iter()); - } - if let Some(headers) = env_http_headers - && !headers.is_empty() - { - entry["env_http_headers"] = table_from_pairs(headers.iter()); - } - } - } - - if !config.enabled { - entry["enabled"] = value(false); - } - if !config.is_local_environment() { - entry["environment_id"] = value(config.environment_id.clone()); - } - if config.required { - entry["required"] = value(true); - } - if config.supports_parallel_tool_calls { - entry["supports_parallel_tool_calls"] = value(true); - } - if let Some(timeout) = config.startup_timeout_sec { - entry["startup_timeout_sec"] = value(timeout.as_secs_f64()); - } - if let Some(timeout) = config.tool_timeout_sec { - entry["tool_timeout_sec"] = value(timeout.as_secs_f64()); - } - if let Some(approval_mode) = config.default_tools_approval_mode { - entry["default_tools_approval_mode"] = value(match approval_mode { - AppToolApproval::Auto => "auto", - AppToolApproval::Prompt => "prompt", - AppToolApproval::Approve => "approve", - }); - } - if let Some(enabled_tools) = &config.enabled_tools - && !enabled_tools.is_empty() - { - entry["enabled_tools"] = array_from_iter(enabled_tools.iter().cloned()); - } - if let Some(disabled_tools) = &config.disabled_tools - && !disabled_tools.is_empty() - { - entry["disabled_tools"] = array_from_iter(disabled_tools.iter().cloned()); - } - if let Some(scopes) = &config.scopes - && !scopes.is_empty() - { - entry["scopes"] = array_from_iter(scopes.iter().cloned()); - } - if let Some(oauth) = &config.oauth - && let Some(client_id) = &oauth.client_id - && !client_id.is_empty() - { - let mut oauth_table = TomlTable::new(); - oauth_table.set_implicit(false); - oauth_table["client_id"] = value(client_id.clone()); - entry["oauth"] = TomlItem::Table(oauth_table); - } - if let Some(resource) = &config.oauth_resource - && !resource.is_empty() - { - entry["oauth_resource"] = value(resource.clone()); - } - if !config.tools.is_empty() { - let mut tools = new_implicit_table(); - let mut tool_entries: Vec<_> = config.tools.iter().collect(); - tool_entries.sort_by_key(|(name, _)| *name); - for (name, tool_config) in tool_entries { - tools.insert(name, serialize_mcp_server_tool(tool_config)); - } - entry.insert("tools", TomlItem::Table(tools)); - } - - entry - } - - fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> TomlItem { - let mut entry = TomlTable::new(); - entry.set_implicit(false); - if let Some(approval_mode) = config.approval_mode { - entry["approval_mode"] = value(match approval_mode { - AppToolApproval::Auto => "auto", - AppToolApproval::Prompt => "prompt", - AppToolApproval::Approve => "approve", - }); - } - TomlItem::Table(entry) - } - - pub(super) fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { - TomlItem::Table(serialize_mcp_server_table(config)) - } - - pub(super) fn serialize_mcp_server_inline(config: &McpServerConfig) -> InlineTable { - serialize_mcp_server_table(config).into_inline_table() - } - - pub(super) fn merge_inline_table(existing: &mut InlineTable, replacement: InlineTable) { - existing.retain(|key, _| replacement.get(key).is_some()); - - for (key, value) in replacement.iter() { - if let Some(existing_value) = existing.get_mut(key) { - let mut updated_value = value.clone(); - *updated_value.decor_mut() = existing_value.decor().clone(); - *existing_value = updated_value; - } else { - existing.insert(key.to_string(), value.clone()); - } - } - } - - fn table_from_inline(inline: &InlineTable) -> TomlTable { - let mut table = new_implicit_table(); - for (key, value) in inline.iter() { - let mut value = value.clone(); - let decor = value.decor_mut(); - decor.set_suffix(""); - table.insert(key, TomlItem::Value(value)); - } - table - } - - pub(super) fn new_implicit_table() -> TomlTable { - let mut table = TomlTable::new(); - table.set_implicit(true); - table - } - - pub(super) fn parse_tool_suggest_disabled_tool( - value: &TomlValue, - ) -> Option { - let table = value.as_inline_table()?; - let kind = match table.get("type").and_then(TomlValue::as_str) { - Some("connector") => ToolSuggestDiscoverableType::Connector, - Some("plugin") => ToolSuggestDiscoverableType::Plugin, - _ => return None, - }; - let id = table.get("id").and_then(TomlValue::as_str)?; - Some(ToolSuggestDisabledTool { - kind, - id: id.to_string(), - }) - } - - pub(super) fn parse_tool_suggest_disabled_tool_table( - table: &TomlTable, - ) -> Option { - let kind = match table.get("type").and_then(TomlItem::as_str) { - Some("connector") => ToolSuggestDiscoverableType::Connector, - Some("plugin") => ToolSuggestDiscoverableType::Plugin, - _ => return None, - }; - let id = table.get("id").and_then(TomlItem::as_str)?; - Some(ToolSuggestDisabledTool { - kind, - id: id.to_string(), - }) - } - - pub(super) fn tool_suggest_disabled_tools_value( - disabled_tools: &[ToolSuggestDisabledTool], - ) -> TomlItem { - let mut array = TomlArray::new(); - for disabled_tool in disabled_tools { - let mut table = InlineTable::new(); - table.insert( - "type", - match disabled_tool.kind { - ToolSuggestDiscoverableType::Connector => "connector", - ToolSuggestDiscoverableType::Plugin => "plugin", - } - .into(), - ); - table.insert("id", disabled_tool.id.clone().into()); - array.push(table); - } - TomlItem::Value(array.into()) - } - - fn array_from_iter(iter: I) -> TomlItem - where - I: Iterator, - { - let mut array = TomlArray::new(); - for value in iter { - array.push(value); - } - TomlItem::Value(array.into()) - } - - fn array_from_env_vars(env_vars: &[McpServerEnvVar]) -> TomlItem { - let mut array = TomlArray::new(); - for env_var in env_vars { - match env_var { - McpServerEnvVar::Name(name) => array.push(name.clone()), - McpServerEnvVar::Config { name, source } => { - let mut table = InlineTable::new(); - table.insert("name", name.clone().into()); - if let Some(source) = source { - table.insert("source", source.clone().into()); - } - array.push(table); - } - } - } - TomlItem::Value(array.into()) - } - - fn table_from_pairs<'a, I>(pairs: I) -> TomlItem - where - I: IntoIterator, - { - let mut entries: Vec<_> = pairs.into_iter().collect(); - entries.sort_by_key(|(key, _)| *key); - let mut table = TomlTable::new(); - table.set_implicit(false); - for (key, val) in entries { - table.insert(key, value(val.clone())); - } - TomlItem::Table(table) - } -} - struct ConfigDocument { doc: DocumentMut, } diff --git a/codex-rs/core/src/config/edit/document_helpers.rs b/codex-rs/core/src/config/edit/document_helpers.rs new file mode 100644 index 0000000000..5b99306eb9 --- /dev/null +++ b/codex-rs/core/src/config/edit/document_helpers.rs @@ -0,0 +1,309 @@ +use codex_config::types::AppToolApproval; +use codex_config::types::McpServerConfig; +use codex_config::types::McpServerEnvVar; +use codex_config::types::McpServerToolConfig; +use codex_config::types::McpServerTransportConfig; +use codex_config::types::ToolSuggestDisabledTool; +use codex_config::types::ToolSuggestDiscoverableType; +use toml_edit::Array as TomlArray; +use toml_edit::InlineTable; +use toml_edit::Item as TomlItem; +use toml_edit::Table as TomlTable; +use toml_edit::Value as TomlValue; +use toml_edit::value; + +pub(super) fn ensure_table_for_write(item: &mut TomlItem) -> Option<&mut TomlTable> { + match item { + TomlItem::Table(table) => Some(table), + TomlItem::Value(value) => { + if let Some(inline) = value.as_inline_table() { + *item = TomlItem::Table(table_from_inline(inline)); + item.as_table_mut() + } else { + *item = TomlItem::Table(new_implicit_table()); + item.as_table_mut() + } + } + TomlItem::None => { + *item = TomlItem::Table(new_implicit_table()); + item.as_table_mut() + } + _ => None, + } +} + +pub(super) fn ensure_table_for_read(item: &mut TomlItem) -> Option<&mut TomlTable> { + match item { + TomlItem::Table(table) => Some(table), + TomlItem::Value(value) => { + let inline = value.as_inline_table()?; + *item = TomlItem::Table(table_from_inline(inline)); + item.as_table_mut() + } + _ => None, + } +} + +fn serialize_mcp_server_table(config: &McpServerConfig) -> TomlTable { + let mut entry = TomlTable::new(); + entry.set_implicit(false); + + match &config.transport { + McpServerTransportConfig::Stdio { + command, + args, + env, + env_vars, + cwd, + } => { + entry["command"] = value(command.clone()); + if !args.is_empty() { + entry["args"] = array_from_iter(args.iter().cloned()); + } + if let Some(env) = env + && !env.is_empty() + { + entry["env"] = table_from_pairs(env.iter()); + } + if !env_vars.is_empty() { + entry["env_vars"] = array_from_env_vars(env_vars); + } + if let Some(cwd) = cwd { + entry["cwd"] = value(cwd.to_string_lossy().to_string()); + } + } + McpServerTransportConfig::StreamableHttp { + url, + bearer_token_env_var, + http_headers, + env_http_headers, + } => { + entry["url"] = value(url.clone()); + if let Some(env_var) = bearer_token_env_var { + entry["bearer_token_env_var"] = value(env_var.clone()); + } + if let Some(headers) = http_headers + && !headers.is_empty() + { + entry["http_headers"] = table_from_pairs(headers.iter()); + } + if let Some(headers) = env_http_headers + && !headers.is_empty() + { + entry["env_http_headers"] = table_from_pairs(headers.iter()); + } + } + } + + if !config.enabled { + entry["enabled"] = value(false); + } + if !config.is_local_environment() { + entry["environment_id"] = value(config.environment_id.clone()); + } + if config.required { + entry["required"] = value(true); + } + if config.supports_parallel_tool_calls { + entry["supports_parallel_tool_calls"] = value(true); + } + if let Some(timeout) = config.startup_timeout_sec { + entry["startup_timeout_sec"] = value(timeout.as_secs_f64()); + } + if let Some(timeout) = config.tool_timeout_sec { + entry["tool_timeout_sec"] = value(timeout.as_secs_f64()); + } + if let Some(approval_mode) = config.default_tools_approval_mode { + entry["default_tools_approval_mode"] = value(match approval_mode { + AppToolApproval::Auto => "auto", + AppToolApproval::Prompt => "prompt", + AppToolApproval::Approve => "approve", + }); + } + if let Some(enabled_tools) = &config.enabled_tools + && !enabled_tools.is_empty() + { + entry["enabled_tools"] = array_from_iter(enabled_tools.iter().cloned()); + } + if let Some(disabled_tools) = &config.disabled_tools + && !disabled_tools.is_empty() + { + entry["disabled_tools"] = array_from_iter(disabled_tools.iter().cloned()); + } + if let Some(scopes) = &config.scopes + && !scopes.is_empty() + { + entry["scopes"] = array_from_iter(scopes.iter().cloned()); + } + if let Some(oauth) = &config.oauth + && let Some(client_id) = &oauth.client_id + && !client_id.is_empty() + { + let mut oauth_table = TomlTable::new(); + oauth_table.set_implicit(false); + oauth_table["client_id"] = value(client_id.clone()); + entry["oauth"] = TomlItem::Table(oauth_table); + } + if let Some(resource) = &config.oauth_resource + && !resource.is_empty() + { + entry["oauth_resource"] = value(resource.clone()); + } + if !config.tools.is_empty() { + let mut tools = new_implicit_table(); + let mut tool_entries: Vec<_> = config.tools.iter().collect(); + tool_entries.sort_by_key(|(name, _)| *name); + for (name, tool_config) in tool_entries { + tools.insert(name, serialize_mcp_server_tool(tool_config)); + } + entry.insert("tools", TomlItem::Table(tools)); + } + + entry +} + +fn serialize_mcp_server_tool(config: &McpServerToolConfig) -> TomlItem { + let mut entry = TomlTable::new(); + entry.set_implicit(false); + if let Some(approval_mode) = config.approval_mode { + entry["approval_mode"] = value(match approval_mode { + AppToolApproval::Auto => "auto", + AppToolApproval::Prompt => "prompt", + AppToolApproval::Approve => "approve", + }); + } + TomlItem::Table(entry) +} + +pub(super) fn serialize_mcp_server(config: &McpServerConfig) -> TomlItem { + TomlItem::Table(serialize_mcp_server_table(config)) +} + +pub(super) fn serialize_mcp_server_inline(config: &McpServerConfig) -> InlineTable { + serialize_mcp_server_table(config).into_inline_table() +} + +pub(super) fn merge_inline_table(existing: &mut InlineTable, replacement: InlineTable) { + existing.retain(|key, _| replacement.get(key).is_some()); + + for (key, value) in replacement.iter() { + if let Some(existing_value) = existing.get_mut(key) { + let mut updated_value = value.clone(); + *updated_value.decor_mut() = existing_value.decor().clone(); + *existing_value = updated_value; + } else { + existing.insert(key.to_string(), value.clone()); + } + } +} + +fn table_from_inline(inline: &InlineTable) -> TomlTable { + let mut table = new_implicit_table(); + for (key, value) in inline.iter() { + let mut value = value.clone(); + let decor = value.decor_mut(); + decor.set_suffix(""); + table.insert(key, TomlItem::Value(value)); + } + table +} + +pub(super) fn new_implicit_table() -> TomlTable { + let mut table = TomlTable::new(); + table.set_implicit(true); + table +} + +pub(super) fn parse_tool_suggest_disabled_tool( + value: &TomlValue, +) -> Option { + let table = value.as_inline_table()?; + let kind = match table.get("type").and_then(TomlValue::as_str) { + Some("connector") => ToolSuggestDiscoverableType::Connector, + Some("plugin") => ToolSuggestDiscoverableType::Plugin, + _ => return None, + }; + let id = table.get("id").and_then(TomlValue::as_str)?; + Some(ToolSuggestDisabledTool { + kind, + id: id.to_string(), + }) +} + +pub(super) fn parse_tool_suggest_disabled_tool_table( + table: &TomlTable, +) -> Option { + let kind = match table.get("type").and_then(TomlItem::as_str) { + Some("connector") => ToolSuggestDiscoverableType::Connector, + Some("plugin") => ToolSuggestDiscoverableType::Plugin, + _ => return None, + }; + let id = table.get("id").and_then(TomlItem::as_str)?; + Some(ToolSuggestDisabledTool { + kind, + id: id.to_string(), + }) +} + +pub(super) fn tool_suggest_disabled_tools_value( + disabled_tools: &[ToolSuggestDisabledTool], +) -> TomlItem { + let mut array = TomlArray::new(); + for disabled_tool in disabled_tools { + let mut table = InlineTable::new(); + table.insert( + "type", + match disabled_tool.kind { + ToolSuggestDiscoverableType::Connector => "connector", + ToolSuggestDiscoverableType::Plugin => "plugin", + } + .into(), + ); + table.insert("id", disabled_tool.id.clone().into()); + array.push(table); + } + TomlItem::Value(array.into()) +} + +fn array_from_iter(iter: I) -> TomlItem +where + I: Iterator, +{ + let mut array = TomlArray::new(); + for value in iter { + array.push(value); + } + TomlItem::Value(array.into()) +} + +fn array_from_env_vars(env_vars: &[McpServerEnvVar]) -> TomlItem { + let mut array = TomlArray::new(); + for env_var in env_vars { + match env_var { + McpServerEnvVar::Name(name) => array.push(name.clone()), + McpServerEnvVar::Config { name, source } => { + let mut table = InlineTable::new(); + table.insert("name", name.clone().into()); + if let Some(source) = source { + table.insert("source", source.clone().into()); + } + array.push(table); + } + } + } + TomlItem::Value(array.into()) +} + +fn table_from_pairs<'a, I>(pairs: I) -> TomlItem +where + I: IntoIterator, +{ + let mut entries: Vec<_> = pairs.into_iter().collect(); + entries.sort_by_key(|(key, _)| *key); + let mut table = TomlTable::new(); + table.set_implicit(false); + for (key, val) in entries { + table.insert(key, value(val.clone())); + } + TomlItem::Table(table) +} diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3115921c2d..618520b7bc 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -2631,9 +2631,8 @@ impl Config { Some(WindowsSandboxModeToml::Unelevated) => WindowsSandboxLevel::RestrictedToken, None => WindowsSandboxLevel::from_features(&features), }; + let memories_config: MemoriesConfig = cfg.memories.clone().unwrap_or_default().into(); let memories_root = memory_root(&codex_home); - std::fs::create_dir_all(&memories_root)?; - let internal_writable_roots = vec![memories_root]; let profiles_are_active = effective_permission_selection.profiles_are_active( default_permissions_override.as_deref(), @@ -2701,8 +2700,8 @@ impl Config { file_system_sandbox_policy, mut active_permission_profile, mut profile_workspace_roots, - ) = if let Some(mut permission_profile) = permission_profile { - let (mut file_system_sandbox_policy, network_sandbox_policy) = + ) = if let Some(permission_profile) = permission_profile { + let (file_system_sandbox_policy, _network_sandbox_policy) = permission_profile.to_runtime_permissions(); let configured_network_proxy_config = if profile_allows_configured_network_proxy(&permission_profile) @@ -2726,30 +2725,6 @@ impl Config { } else { NetworkProxyConfig::default() }; - let materialized_file_system_sandbox_policy = file_system_sandbox_policy - .clone() - .materialize_project_roots_with_workspace_roots(&workspace_roots); - let materialized_permission_profile = - PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &materialized_file_system_sandbox_policy, - network_sandbox_policy, - ); - let sandbox_policy = compatibility_sandbox_policy_for_permission_profile( - &materialized_permission_profile, - &materialized_file_system_sandbox_policy, - network_sandbox_policy, - resolved_cwd.as_path(), - ); - if matches!(sandbox_policy, SandboxPolicy::WorkspaceWrite { .. }) { - file_system_sandbox_policy = file_system_sandbox_policy - .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); - permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &file_system_sandbox_policy, - network_sandbox_policy, - ); - } ( configured_network_proxy_config, permission_profile, @@ -2794,7 +2769,7 @@ impl Config { dedupe_absolute_paths(&mut configured_workspace_roots); file_system_sandbox_policy = file_system_sandbox_policy .with_materialized_project_roots_for_workspace_roots(&configured_workspace_roots); - let mut permission_profile = if let Some(permission_profile) = + let permission_profile = if let Some(permission_profile) = builtin_permission_profile(default_permissions, builtin_workspace_write_settings) { permission_profile @@ -2804,30 +2779,6 @@ impl Config { network_sandbox_policy, ) }; - let materialized_file_system_sandbox_policy = file_system_sandbox_policy - .clone() - .materialize_project_roots_with_workspace_roots(&workspace_roots); - let materialized_permission_profile = - PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &materialized_file_system_sandbox_policy, - network_sandbox_policy, - ); - let sandbox_policy = compatibility_sandbox_policy_for_permission_profile( - &materialized_permission_profile, - &materialized_file_system_sandbox_policy, - network_sandbox_policy, - resolved_cwd.as_path(), - ); - if matches!(sandbox_policy, SandboxPolicy::WorkspaceWrite { .. }) { - file_system_sandbox_policy = file_system_sandbox_policy - .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); - permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &file_system_sandbox_policy, - network_sandbox_policy, - ); - } let active_permission_profile = if using_implicit_builtin_profile && default_permissions == BUILT_IN_WORKSPACE_PROFILE && cfg.sandbox_workspace_write.is_some() @@ -2885,29 +2836,8 @@ impl Config { ); permission_profile = PermissionProfile::read_only(); } - let (mut file_system_sandbox_policy, network_sandbox_policy) = + let (file_system_sandbox_policy, _network_sandbox_policy) = permission_profile.to_runtime_permissions(); - let materialized_file_system_sandbox_policy = permission_profile - .clone() - .materialize_project_roots_with_workspace_roots(&workspace_roots) - .file_system_sandbox_policy(); - if matches!(permission_profile.enforcement(), SandboxEnforcement::Managed) - && materialized_file_system_sandbox_policy.can_write_path_with_cwd( - resolved_cwd.as_path(), - resolved_cwd.as_path(), - ) - && !materialized_file_system_sandbox_policy.has_full_disk_write_access() - { - // Keep Codex runtime write access while storing the runtime - // workspace roots separately on the thread. - file_system_sandbox_policy = file_system_sandbox_policy - .with_additional_legacy_workspace_writable_roots(&internal_writable_roots); - permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &file_system_sandbox_policy, - network_sandbox_policy, - ); - } ( configured_network_proxy_config, permission_profile, @@ -3324,11 +3254,14 @@ impl Config { network_requirements, &network_permission_profile, )?; - let helper_readable_roots = get_readable_roots_required_for_codex_runtime( + let mut helper_readable_roots = get_readable_roots_required_for_codex_runtime( &codex_home, zsh_path.as_ref(), main_execve_wrapper_exe.as_ref(), ); + if features.enabled(Feature::MemoryTool) && memories_config.use_memories { + helper_readable_roots.push(memories_root); + } let effective_permission_profile = constrained_permission_profile.value.get().clone(); let (mut effective_file_system_sandbox_policy, effective_network_sandbox_policy) = effective_permission_profile.to_runtime_permissions(); @@ -3438,7 +3371,7 @@ impl Config { agent_max_threads, agent_max_depth, agent_roles, - memories: cfg.memories.unwrap_or_default().into(), + memories: memories_config, agent_job_max_runtime_seconds, agent_interrupt_message_enabled, codex_home, diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rs index 3aaa7d66f8..a8546858f1 100644 --- a/codex-rs/core/src/config/permissions.rs +++ b/codex-rs/core/src/config/permissions.rs @@ -176,8 +176,8 @@ pub(crate) fn apply_network_proxy_feature_config( NetworkProxyUnixSocketPermissionToml::Allow => { NetworkUnixSocketPermissionToml::Allow } - NetworkProxyUnixSocketPermissionToml::None => { - NetworkUnixSocketPermissionToml::None + NetworkProxyUnixSocketPermissionToml::Deny => { + NetworkUnixSocketPermissionToml::Deny } }; (path.clone(), permission) diff --git a/codex-rs/core/src/config/permissions_tests.rs b/codex-rs/core/src/config/permissions_tests.rs index 8f9d6732e4..41f4179ba8 100644 --- a/codex-rs/core/src/config/permissions_tests.rs +++ b/codex-rs/core/src/config/permissions_tests.rs @@ -149,7 +149,7 @@ fn network_permission_containers_project_allowed_and_denied_entries() { ), ( "/tmp/ignored.sock".to_string(), - NetworkUnixSocketPermissionToml::None, + NetworkUnixSocketPermissionToml::Deny, ), ]), }; @@ -211,7 +211,7 @@ fn network_toml_overlays_unix_socket_permissions_by_path() { ), ( "/tmp/override.sock".to_string(), - NetworkUnixSocketPermissionToml::None, + NetworkUnixSocketPermissionToml::Deny, ), ]), }), @@ -233,7 +233,7 @@ fn network_toml_overlays_unix_socket_permissions_by_path() { ), ( "/tmp/override.sock".to_string(), - ProxyNetworkUnixSocketPermission::None, + ProxyNetworkUnixSocketPermission::Deny, ), ]), }) @@ -265,6 +265,7 @@ enabled = true [base.network.unix_sockets] "/tmp/base.sock" = "allow" +"/tmp/blocked.sock" = "deny" [child] extends = "base" @@ -319,6 +320,7 @@ allow_local_binding = true [network.unix_sockets] "/tmp/base.sock" = "allow" +"/tmp/blocked.sock" = "deny" "/tmp/child.sock" = "allow" "#, ) diff --git a/codex-rs/core/src/context/contextual_user_message.rs b/codex-rs/core/src/context/contextual_user_message.rs index 940a938fce..79768dd3a3 100644 --- a/codex-rs/core/src/context/contextual_user_message.rs +++ b/codex-rs/core/src/context/contextual_user_message.rs @@ -6,7 +6,7 @@ use super::AdditionalContextUserFragment; use super::EnvironmentContext; use super::FragmentRegistration; use super::FragmentRegistrationProxy; -use super::GoalContext; +use super::InternalModelContextFragment; use super::LegacyApplyPatchExecCommandWarning; use super::LegacyModelMismatchWarning; use super::LegacyUnifiedExecProcessLimitWarning; @@ -30,8 +30,9 @@ static TURN_ABORTED_REGISTRATION: FragmentRegistrationProxy = FragmentRegistrationProxy::new(); static SUBAGENT_NOTIFICATION_REGISTRATION: FragmentRegistrationProxy = FragmentRegistrationProxy::new(); -static GOAL_CONTEXT_REGISTRATION: FragmentRegistrationProxy = - FragmentRegistrationProxy::new(); +static INTERNAL_MODEL_CONTEXT_REGISTRATION: FragmentRegistrationProxy< + InternalModelContextFragment, +> = FragmentRegistrationProxy::new(); static LEGACY_UNIFIED_EXEC_PROCESS_LIMIT_WARNING_REGISTRATION: FragmentRegistrationProxy< LegacyUnifiedExecProcessLimitWarning, > = FragmentRegistrationProxy::new(); @@ -50,7 +51,7 @@ static CONTEXTUAL_USER_FRAGMENTS: &[&dyn FragmentRegistration] = &[ &USER_SHELL_COMMAND_REGISTRATION, &TURN_ABORTED_REGISTRATION, &SUBAGENT_NOTIFICATION_REGISTRATION, - &GOAL_CONTEXT_REGISTRATION, + &INTERNAL_MODEL_CONTEXT_REGISTRATION, &LEGACY_UNIFIED_EXEC_PROCESS_LIMIT_WARNING_REGISTRATION, &LEGACY_APPLY_PATCH_EXEC_COMMAND_WARNING_REGISTRATION, &LEGACY_MODEL_MISMATCH_WARNING_REGISTRATION, diff --git a/codex-rs/core/src/context/contextual_user_message_tests.rs b/codex-rs/core/src/context/contextual_user_message_tests.rs index 195b189929..dc7cb0f534 100644 --- a/codex-rs/core/src/context/contextual_user_message_tests.rs +++ b/codex-rs/core/src/context/contextual_user_message_tests.rs @@ -1,6 +1,7 @@ use super::*; use crate::context::ContextualUserFragment; -use crate::context::GoalContext; +use crate::context::InternalContextSource; +use crate::context::InternalModelContextFragment; use crate::context::SubagentNotification; use codex_protocol::items::HookPromptFragment; use codex_protocol::items::build_hook_prompt_message; @@ -30,23 +31,55 @@ fn detects_subagent_notification_fragment_case_insensitively() { } #[test] -fn detects_goal_context_fragment() { - let text = GoalContext::new("Continue working toward the active thread goal.").render(); +fn detects_internal_model_context_fragment() { + let text = InternalModelContextFragment::new( + InternalContextSource::from_static("goal"), + "Continue working toward the active thread goal.", + ) + .render(); + assert_eq!( + text, + "\nContinue working toward the active thread goal.\n" + ); assert!(is_contextual_user_fragment(&ContentItem::InputText { text })); } +#[test] +fn detects_legacy_goal_context_fragment() { + assert!(is_contextual_user_fragment(&ContentItem::InputText { + text: "\nContinue working toward the active thread goal.\n" + .to_string(), + })); +} + +#[test] +fn does_not_hide_arbitrary_context_tags() { + assert!(!is_contextual_user_fragment(&ContentItem::InputText { + text: "\nbody\n".to_string(), + })); +} + +#[test] +fn rejects_invalid_internal_model_context_source() { + assert!(!is_contextual_user_fragment(&ContentItem::InputText { + text: "\nbody\n" + .to_string(), + })); +} + #[test] fn contextual_user_fragment_is_dyn_compatible() { - let fragment: Box = Box::new(GoalContext::new( + let fragment: Box = Box::new(InternalModelContextFragment::new( + InternalContextSource::from_static("goal"), "Continue working toward the active thread goal.", )); assert_eq!( fragment.render(), - "\nContinue working toward the active thread goal.\n" + "\nContinue working toward the active thread goal.\n" ); } diff --git a/codex-rs/core/src/context/environment_context.rs b/codex-rs/core/src/context/environment_context.rs index a3052b6642..051147b7cd 100644 --- a/codex-rs/core/src/context/environment_context.rs +++ b/codex-rs/core/src/context/environment_context.rs @@ -1,9 +1,17 @@ use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnEnvironment; use crate::shell::Shell; +use codex_protocol::models::ManagedFileSystemPermissions; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::TurnContextNetworkItem; use codex_utils_absolute_path::AbsolutePathBuf; +use std::collections::HashSet; +use std::path::PathBuf; use super::ContextualUserFragment; @@ -13,6 +21,7 @@ pub(crate) struct EnvironmentContext { pub(crate) current_date: Option, pub(crate) timezone: Option, pub(crate) network: Option, + pub(crate) filesystem: Option, pub(crate) subagents: Option, } @@ -83,6 +92,208 @@ impl EnvironmentContextEnvironments { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct FileSystemContext { + workspace_roots: Vec, + permission_profile: FileSystemPermissionProfileContext, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum FileSystemPermissionProfileContext { + Managed(ManagedFileSystemContext), + Disabled, + External, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum ManagedFileSystemContext { + Restricted { + entries: Vec, + glob_scan_max_depth: Option, + }, + Unrestricted, +} + +impl FileSystemContext { + fn from_permission_profile( + permission_profile: &PermissionProfile, + workspace_roots: &[AbsolutePathBuf], + ) -> Self { + let permission_profile = permission_profile + .clone() + .materialize_project_roots_with_workspace_roots(workspace_roots); + let workspace_roots = workspace_roots + .iter() + .map(|root| root.to_string_lossy().into_owned()) + .collect(); + let permission_profile = match permission_profile { + PermissionProfile::Managed { file_system, .. } => { + FileSystemPermissionProfileContext::Managed(ManagedFileSystemContext::from( + file_system, + )) + } + PermissionProfile::Disabled => FileSystemPermissionProfileContext::Disabled, + PermissionProfile::External { .. } => FileSystemPermissionProfileContext::External, + }; + Self { + workspace_roots, + permission_profile, + } + } + + fn render(&self) -> String { + let mut rendered = "".to_string(); + if !self.workspace_roots.is_empty() { + rendered.push_str(""); + for root in &self.workspace_roots { + push_text_element(&mut rendered, "root", root); + } + rendered.push_str(""); + } + self.permission_profile.render(&mut rendered); + rendered.push_str(""); + rendered + } +} + +impl From for ManagedFileSystemContext { + fn from(file_system: ManagedFileSystemPermissions) -> Self { + match file_system { + ManagedFileSystemPermissions::Restricted { + mut entries, + glob_scan_max_depth, + } => { + dedupe_file_system_entries(&mut entries); + Self::Restricted { + entries, + glob_scan_max_depth: glob_scan_max_depth.map(usize::from), + } + } + ManagedFileSystemPermissions::Unrestricted => Self::Unrestricted, + } + } +} + +impl FileSystemPermissionProfileContext { + fn render(&self, rendered: &mut String) { + match self { + Self::Managed(file_system) => { + rendered.push_str(""); + file_system.render(rendered); + rendered.push_str(""); + } + Self::Disabled => { + rendered.push_str( + "", + ); + } + Self::External => { + rendered.push_str( + "", + ); + } + } + } +} + +impl ManagedFileSystemContext { + fn render(&self, rendered: &mut String) { + match self { + Self::Restricted { + entries, + glob_scan_max_depth, + } => { + if entries.is_empty() && glob_scan_max_depth.is_none() { + rendered.push_str(""); + return; + } + + rendered.push_str("'); + for entry in entries { + render_file_system_entry(rendered, entry); + } + rendered.push_str(""); + } + Self::Unrestricted => { + rendered.push_str(""); + } + } + } +} + +fn render_file_system_entry(rendered: &mut String, entry: &FileSystemSandboxEntry) { + rendered.push_str(""); + match &entry.path { + FileSystemPath::Path { path } => { + push_text_element(rendered, "path", path.to_string_lossy().as_ref()); + } + FileSystemPath::GlobPattern { pattern } => { + push_text_element(rendered, "glob", pattern); + } + FileSystemPath::Special { value } => { + let value = render_special_path(value); + push_text_element(rendered, "special", &value); + } + } + rendered.push_str(""); +} + +fn render_special_path(value: &FileSystemSpecialPath) -> String { + match value { + FileSystemSpecialPath::Root => ":root".to_string(), + FileSystemSpecialPath::Minimal => ":minimal".to_string(), + FileSystemSpecialPath::ProjectRoots { subpath } => { + render_special_path_with_subpath(":workspace_roots", subpath) + } + FileSystemSpecialPath::Tmpdir => ":tmpdir".to_string(), + FileSystemSpecialPath::SlashTmp => ":slash_tmp".to_string(), + FileSystemSpecialPath::Unknown { path, subpath } => { + render_special_path_with_subpath(path, subpath) + } + } +} + +fn render_special_path_with_subpath(base: &str, subpath: &Option) -> String { + match subpath { + Some(subpath) => format!("{base}/{}", subpath.display()), + None => base.to_string(), + } +} + +fn dedupe_file_system_entries(entries: &mut Vec) { + let mut seen = HashSet::new(); + entries.retain(|entry| seen.insert(entry.clone())); +} + +fn push_text_element(rendered: &mut String, name: &str, value: &str) { + rendered.push_str(&format!("<{name}>")); + push_xml_escaped_text(rendered, value); + rendered.push_str(&format!("")); +} + +fn push_xml_escaped_text(rendered: &mut String, value: &str) { + for ch in value.chars() { + match ch { + '&' => rendered.push_str("&"), + '<' => rendered.push_str("<"), + '>' => rendered.push_str(">"), + '"' => rendered.push_str("""), + '\'' => rendered.push_str("'"), + _ => rendered.push(ch), + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct NetworkContext { allowed_domains: Vec, @@ -129,6 +340,7 @@ impl EnvironmentContext { current_date, timezone, network, + filesystem: None, subagents, } } @@ -138,6 +350,7 @@ impl EnvironmentContext { current_date: Option, timezone: Option, network: Option, + filesystem: Option, subagents: Option, ) -> Self { Self { @@ -145,6 +358,7 @@ impl EnvironmentContext { current_date, timezone, network, + filesystem, subagents, } } @@ -157,6 +371,7 @@ impl EnvironmentContext { && self.current_date == other.current_date && self.timezone == other.timezone && self.network == other.network + && self.filesystem == other.filesystem && self.subagents == other.subagents } @@ -165,6 +380,7 @@ impl EnvironmentContext { after: &EnvironmentContext, ) -> Self { let before_network = Self::network_from_turn_context_item(before); + let before_filesystem = Self::filesystem_from_turn_context_item(before); let environments = match &after.environments { EnvironmentContextEnvironments::Single(environment) => { if before.cwd.as_path() != environment.cwd.as_path() { @@ -186,17 +402,23 @@ impl EnvironmentContext { } else { before_network }; + let filesystem = if before_filesystem != after.filesystem { + after.filesystem.clone() + } else { + before_filesystem + }; EnvironmentContext::new_with_environments( environments, after.current_date.clone(), after.timezone.clone(), network, + filesystem, /*subagents*/ None, ) } pub(crate) fn from_turn_context(turn_context: &TurnContext, shell: &Shell) -> Self { - Self::new( + let mut context = Self::new( EnvironmentContextEnvironment::from_turn_environments( &turn_context.environments.turn_environments, shell, @@ -205,7 +427,12 @@ impl EnvironmentContext { turn_context.timezone.clone(), Self::network_from_turn_context(turn_context), /*subagents*/ None, - ) + ); + context.filesystem = Some(FileSystemContext::from_permission_profile( + &turn_context.permission_profile, + &turn_context.config.effective_workspace_roots(), + )); + context } pub(crate) fn from_turn_context_item( @@ -216,11 +443,14 @@ impl EnvironmentContext { Ok(cwd) => cwd, Err(_) => AbsolutePathBuf::resolve_path_against_base(&turn_context_item.cwd, "/"), }; - Self::new( - vec![EnvironmentContextEnvironment::legacy(cwd, shell)], + Self::new_with_environments( + EnvironmentContextEnvironments::from_vec(vec![EnvironmentContextEnvironment::legacy( + cwd, shell, + )]), turn_context_item.current_date.clone(), turn_context_item.timezone.clone(), Self::network_from_turn_context_item(turn_context_item), + Self::filesystem_from_turn_context_item(turn_context_item), /*subagents*/ None, ) } @@ -266,6 +496,30 @@ impl EnvironmentContext { denied_domains.clone(), )) } + + fn filesystem_from_turn_context_item( + turn_context_item: &TurnContextItem, + ) -> Option { + Some(FileSystemContext::from_permission_profile( + &turn_context_item.permission_profile(), + &workspace_roots_from_turn_context_item(turn_context_item), + )) + } +} + +fn workspace_roots_from_turn_context_item( + turn_context_item: &TurnContextItem, +) -> Vec { + if let Some(workspace_roots) = turn_context_item.workspace_roots.as_ref() { + return workspace_roots.clone(); + } + + // Older rollout items did not persist workspace roots. Fall back to the + // legacy cwd binding only when reconstructing that historical context. + match AbsolutePathBuf::try_from(turn_context_item.cwd.clone()) { + Ok(cwd) => vec![cwd], + Err(_) => Vec::new(), + } } impl ContextualUserFragment for EnvironmentContext { @@ -324,6 +578,9 @@ impl ContextualUserFragment for EnvironmentContext { // lines.push(" ".to_string()); } } + if let Some(filesystem) = &self.filesystem { + lines.push(format!(" {}", filesystem.render())); + } if let Some(subagents) = &self.subagents { lines.push(" ".to_string()); lines.extend(subagents.lines().map(|line| format!(" {line}"))); diff --git a/codex-rs/core/src/context/environment_context_tests.rs b/codex-rs/core/src/context/environment_context_tests.rs index 68ff7c9d44..875ce20c09 100644 --- a/codex-rs/core/src/context/environment_context_tests.rs +++ b/codex-rs/core/src/context/environment_context_tests.rs @@ -1,9 +1,21 @@ use crate::shell::ShellType; use super::*; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_protocol::permissions::project_roots_glob_pattern; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::TurnContextItem; use codex_utils_absolute_path::test_support::PathBufExt; use core_test_support::test_path_buf; use pretty_assertions::assert_eq; +use std::path::Path; use std::path::PathBuf; fn fake_shell_name() -> String { @@ -79,6 +91,125 @@ fn serialize_environment_context_with_network() { assert_eq!(context.render(), expected); } +fn workspace_write_permission_profile_with_private_denials() -> PermissionProfile { + PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(Some(PathBuf::from("private"))), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: project_roots_glob_pattern(Path::new("private/**")), + }, + access: FileSystemAccessMode::Deny, + }, + ]), + NetworkSandboxPolicy::Restricted, + ) +} + +#[test] +fn serialize_environment_context_with_full_filesystem_profile() { + let repo = test_abs_path("/repo"); + let other_repo = test_abs_path("/other-repo"); + let repo_private = repo.join("private"); + let other_repo_private = other_repo.join("private"); + let repo_private_glob = + AbsolutePathBuf::resolve_path_against_base(Path::new("private/**"), repo.as_path()); + let other_repo_private_glob = + AbsolutePathBuf::resolve_path_against_base(Path::new("private/**"), other_repo.as_path()); + let mut context = EnvironmentContext::new( + vec![EnvironmentContextEnvironment { + id: "local".to_string(), + cwd: test_path_buf("/repo").abs(), + shell: fake_shell_name(), + }], + /*current_date*/ None, + /*timezone*/ None, + /*network*/ None, + /*subagents*/ None, + ); + context.filesystem = Some(FileSystemContext::from_permission_profile( + &workspace_write_permission_profile_with_private_denials(), + &[repo.clone(), other_repo.clone()], + )); + + let expected = format!( + r#" + {} + bash + {repo}{other_repo}{repo}{other_repo}{repo_private}{other_repo_private}{repo_private_glob}{other_repo_private_glob} +"#, + test_path_buf("/repo").display(), + repo = repo.to_string_lossy(), + other_repo = other_repo.to_string_lossy(), + repo_private = repo_private.to_string_lossy(), + other_repo_private = other_repo_private.to_string_lossy(), + repo_private_glob = repo_private_glob.to_string_lossy(), + other_repo_private_glob = other_repo_private_glob.to_string_lossy(), + ); + + assert_eq!(context.render(), expected); +} + +#[test] +fn turn_context_item_filesystem_uses_workspace_roots_instead_of_cwd() { + let repo = test_abs_path("/repo"); + let other_repo = test_abs_path("/other-repo"); + let repo_private = repo.join("private"); + let item = TurnContextItem { + turn_id: None, + cwd: test_path_buf("/not-the-workspace"), + workspace_roots: Some(vec![repo.clone(), other_repo.clone()]), + current_date: None, + timezone: None, + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + permission_profile: Some(workspace_write_permission_profile_with_private_denials()), + network: None, + file_system_sandbox_policy: None, + model: "gpt-5".to_string(), + personality: None, + collaboration_mode: None, + realtime_active: None, + effort: None, + summary: codex_protocol::config_types::ReasoningSummary::Auto, + }; + + let context = EnvironmentContext::from_turn_context_item(&item, fake_shell_name()).render(); + + assert!( + context.contains(&format!( + "{}{}", + repo.to_string_lossy(), + other_repo.to_string_lossy() + )), + "{context}" + ); + assert!( + context.contains(&format!("{}", repo_private.to_string_lossy())), + "{context}" + ); + assert!( + !context.contains( + test_abs_path("/not-the-workspace") + .join("private") + .to_string_lossy() + .as_ref() + ), + "{context}" + ); +} + #[test] fn serialize_read_only_environment_context() { let context = EnvironmentContext::new( diff --git a/codex-rs/core/src/context/goal_context.rs b/codex-rs/core/src/context/goal_context.rs deleted file mode 100644 index ad4c47ef06..0000000000 --- a/codex-rs/core/src/context/goal_context.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Hidden user-context fragment for runtime-owned goal steering prompts. - -use super::ContextualUserFragment; - -/// Hidden runtime-owned goal steering context injected into model input. -#[derive(Debug, Clone, PartialEq)] -pub struct GoalContext { - prompt: String, -} - -impl GoalContext { - /// Creates goal context around an already-rendered steering prompt. - pub fn new(prompt: impl Into) -> Self { - Self { - prompt: prompt.into(), - } - } -} - -impl ContextualUserFragment for GoalContext { - fn role() -> &'static str { - "user" - } - - fn markers(&self) -> (&'static str, &'static str) { - Self::type_markers() - } - - fn type_markers() -> (&'static str, &'static str) { - ("", "") - } - - fn body(&self) -> String { - format!("\n{}\n", self.prompt) - } -} diff --git a/codex-rs/core/src/context/internal_model_context.rs b/codex-rs/core/src/context/internal_model_context.rs new file mode 100644 index 0000000000..a25e77a82a --- /dev/null +++ b/codex-rs/core/src/context/internal_model_context.rs @@ -0,0 +1,129 @@ +//! Hidden user-context fragment for extension-owned model steering. + +use super::ContextualUserFragment; +use std::error::Error; +use std::fmt; + +const CONTEXT_START_MARKER: &str = ""; + +/// Source label for hidden internal model context. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InternalContextSource(String); + +impl InternalContextSource { + /// Creates a source label for an internal model-context fragment. + /// + /// Sources are intentionally constrained so the value can be embedded in the + /// wrapper without escaping and still remain easy to audit in stored history. + pub fn new(source: impl Into) -> Result { + let source = source.into(); + if is_valid_source(&source) { + Ok(Self(source)) + } else { + Err(InvalidInternalContextSource { source }) + } + } + + /// Creates a source label from a trusted static string. + pub fn from_static(source: &'static str) -> Self { + Self::new(source) + .unwrap_or_else(|_| panic!("invalid static internal context source: {source}")) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Error returned when an internal model-context source is invalid. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InvalidInternalContextSource { + source: String, +} + +impl fmt::Display for InvalidInternalContextSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let source = &self.source; + write!( + f, + "invalid internal model context source {source:?}; expected [a-z][a-z0-9_]*" + ) + } +} + +impl Error for InvalidInternalContextSource {} + +/// Hidden runtime-owned context injected into model input. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InternalModelContextFragment { + source: InternalContextSource, + body: String, +} + +impl InternalModelContextFragment { + /// Creates hidden model context with an extension-owned source label. + pub fn new(source: InternalContextSource, body: impl Into) -> Self { + Self { + source, + body: body.into(), + } + } +} + +impl ContextualUserFragment for InternalModelContextFragment { + fn role() -> &'static str { + "user" + } + + fn markers(&self) -> (&'static str, &'static str) { + Self::type_markers() + } + + fn type_markers() -> (&'static str, &'static str) { + (CONTEXT_START_MARKER, CONTEXT_END_MARKER) + } + + fn matches_text(text: &str) -> bool { + let trimmed = text.trim(); + if matches_legacy_goal_context(trimmed) { + return true; + } + + let Some(rest) = trimmed.strip_prefix(CONTEXT_START_MARKER) else { + return false; + }; + let Some(rest) = rest.strip_prefix(SOURCE_ATTR_START) else { + return false; + }; + let Some((source, body_and_close)) = rest.split_once(SOURCE_ATTR_END) else { + return false; + }; + + is_valid_source(source) && body_and_close.ends_with(CONTEXT_END_MARKER) + } + + fn body(&self) -> String { + let source = self.source.as_str(); + let body = &self.body; + format!(" source=\"{source}\">\n{body}\n") + } +} + +fn matches_legacy_goal_context(text: &str) -> bool { + text.starts_with(LEGACY_GOAL_CONTEXT_START_MARKER) + && text.ends_with(LEGACY_GOAL_CONTEXT_END_MARKER) +} + +fn is_valid_source(source: &str) -> bool { + let mut chars = source.chars(); + let Some(first) = chars.next() else { + return false; + }; + first.is_ascii_lowercase() + && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_') +} diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index 6d88df87e2..3e01d5212e 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -9,10 +9,10 @@ mod contextual_user_message; mod environment_context; mod fragment; mod fragments; -mod goal_context; mod guardian_followup_review_reminder; mod hook_additional_context; mod image_generation_instructions; +mod internal_model_context; mod legacy_apply_patch_exec_command_warning; mod legacy_model_mismatch_warning; mod legacy_unified_exec_process_limit_warning; @@ -43,10 +43,12 @@ pub(crate) use fragment::FragmentRegistration; pub(crate) use fragment::FragmentRegistrationProxy; pub(crate) use fragments::AdditionalContextDeveloperFragment; pub(crate) use fragments::AdditionalContextUserFragment; -pub use goal_context::GoalContext; pub(crate) use guardian_followup_review_reminder::GuardianFollowupReviewReminder; pub(crate) use hook_additional_context::HookAdditionalContext; pub(crate) use image_generation_instructions::ImageGenerationInstructions; +pub use internal_model_context::InternalContextSource; +pub use internal_model_context::InternalModelContextFragment; +pub use internal_model_context::InvalidInternalContextSource; pub(crate) use legacy_apply_patch_exec_command_warning::LegacyApplyPatchExecCommandWarning; pub(crate) use legacy_model_mismatch_warning::LegacyModelMismatchWarning; pub(crate) use legacy_unified_exec_process_limit_warning::LegacyUnifiedExecProcessLimitWarning; diff --git a/codex-rs/core/src/context/permissions_instructions.rs b/codex-rs/core/src/context/permissions_instructions.rs index db8f983c16..e87dceec01 100644 --- a/codex-rs/core/src/context/permissions_instructions.rs +++ b/codex-rs/core/src/context/permissions_instructions.rs @@ -4,6 +4,7 @@ use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::SandboxMode; use codex_protocol::models::PermissionProfile; use codex_protocol::models::format_allow_prefixes; +use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::GranularApprovalConfig; @@ -68,9 +69,11 @@ impl PermissionsInstructions { exec_permission_approvals_enabled: bool, request_permissions_tool_enabled: bool, ) -> Self { - let (sandbox_mode, writable_roots) = sandbox_prompt_from_profile(permission_profile, cwd); + let file_system_sandbox_policy = permission_profile.file_system_sandbox_policy(); + let (sandbox_mode, writable_roots) = + sandbox_prompt_from_policy(&file_system_sandbox_policy, cwd); - Self::from_permissions_with_network( + Self::from_permissions_with_network_and_denied_reads( sandbox_mode, network_access_from_policy(permission_profile.network_sandbox_policy()), PermissionsPromptConfig { @@ -81,14 +84,32 @@ impl PermissionsInstructions { request_permissions_tool_enabled, }, writable_roots, + denied_reads_text(&file_system_sandbox_policy, cwd), ) } + #[cfg(test)] fn from_permissions_with_network( sandbox_mode: SandboxMode, network_access: NetworkAccess, config: PermissionsPromptConfig<'_>, writable_roots: Option>, + ) -> Self { + Self::from_permissions_with_network_and_denied_reads( + sandbox_mode, + network_access, + config, + writable_roots, + /*denied_reads*/ None, + ) + } + + fn from_permissions_with_network_and_denied_reads( + sandbox_mode: SandboxMode, + network_access: NetworkAccess, + config: PermissionsPromptConfig<'_>, + writable_roots: Option>, + denied_reads: Option, ) -> Self { let mut text = String::new(); append_section(&mut text, &sandbox_text(sandbox_mode, network_access)); @@ -105,6 +126,9 @@ impl PermissionsInstructions { if let Some(writable_roots) = writable_roots_text(writable_roots) { append_section(&mut text, &writable_roots); } + if let Some(denied_reads) = denied_reads { + append_section(&mut text, &denied_reads); + } if !text.ends_with('\n') { text.push('\n'); } @@ -112,27 +136,19 @@ impl PermissionsInstructions { } } -fn sandbox_prompt_from_profile( - permission_profile: &PermissionProfile, +fn sandbox_prompt_from_policy( + file_system_policy: &FileSystemSandboxPolicy, cwd: &Path, ) -> (SandboxMode, Option>) { - match permission_profile { - PermissionProfile::Disabled | PermissionProfile::External { .. } => { - (SandboxMode::DangerFullAccess, None) - } - PermissionProfile::Managed { .. } => { - let file_system_policy = permission_profile.file_system_sandbox_policy(); - if file_system_policy.has_full_disk_write_access() { - return (SandboxMode::DangerFullAccess, None); - } + if file_system_policy.has_full_disk_write_access() { + return (SandboxMode::DangerFullAccess, None); + } - let writable_roots = file_system_policy.get_writable_roots_with_cwd(cwd); - if writable_roots.is_empty() { - (SandboxMode::ReadOnly, None) - } else { - (SandboxMode::WorkspaceWrite, Some(writable_roots)) - } - } + let writable_roots = file_system_policy.get_writable_roots_with_cwd(cwd); + if writable_roots.is_empty() { + (SandboxMode::ReadOnly, None) + } else { + (SandboxMode::WorkspaceWrite, Some(writable_roots)) } } @@ -254,6 +270,28 @@ fn writable_roots_text(writable_roots: Option>) -> Option Option { + let mut entries = file_system_policy + .get_unreadable_roots_with_cwd(cwd) + .into_iter() + .map(|root| format!("- path `{}`", root.to_string_lossy())) + .collect::>(); + entries.extend( + file_system_policy + .get_unreadable_globs_with_cwd(cwd) + .into_iter() + .map(|glob| format!("- glob `{glob}`")), + ); + if entries.is_empty() { + return None; + } + + Some(format!( + "## Denied filesystem reads\nThe active permission profile denies reading these paths/globs. Do not request escalation or additional permissions to read them; these denials are policy restrictions.\n{}", + entries.join("\n") + )) +} + fn approved_command_prefixes_text(exec_policy: &Policy) -> Option { format_allow_prefixes(exec_policy.get_allowed_prefixes()) .filter(|prefixes| !prefixes.is_empty()) diff --git a/codex-rs/core/src/context/permissions_instructions_tests.rs b/codex-rs/core/src/context/permissions_instructions_tests.rs index 6d1aa5d886..580e9781ce 100644 --- a/codex-rs/core/src/context/permissions_instructions_tests.rs +++ b/codex-rs/core/src/context/permissions_instructions_tests.rs @@ -6,6 +6,7 @@ use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_absolute_path::test_support::test_path_buf; use pretty_assertions::assert_eq; use std::path::PathBuf; @@ -83,6 +84,52 @@ fn builds_permissions_from_profile() { assert!(text.contains(writable_root.to_string_lossy().as_ref())); } +#[test] +fn builds_permissions_from_profile_with_denied_reads() { + let cwd = test_path_buf("/tmp"); + let denied_root = + AbsolutePathBuf::from_absolute_path(cwd.join("blocked")).expect("absolute path"); + let denied_glob = cwd.join("blocked").join("**"); + let permission_profile = PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: codex_protocol::permissions::FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_root.clone(), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: denied_glob.to_string_lossy().into_owned(), + }, + access: FileSystemAccessMode::Deny, + }, + ]), + NetworkSandboxPolicy::Restricted, + ); + + let instructions = PermissionsInstructions::from_permission_profile( + &permission_profile, + AskForApproval::OnRequest, + ApprovalsReviewer::AutoReview, + &Policy::empty(), + &cwd, + /*exec_permission_approvals_enabled*/ false, + /*request_permissions_tool_enabled*/ false, + ); + let text = instructions.body(); + assert!(text.contains("## Denied filesystem reads")); + assert!(text.contains("Do not request escalation or additional permissions")); + assert!(text.contains(denied_root.to_string_lossy().as_ref())); + assert!(text.contains(&format!("glob `{}`", denied_glob.to_string_lossy()))); +} + #[test] fn includes_request_rule_instructions_for_on_request() { let mut exec_policy = Policy::empty(); diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index f63ae6ec1f..42179c42b5 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -121,6 +121,7 @@ fn reference_context_item() -> TurnContextItem { TurnContextItem { turn_id: Some("reference-turn".to_string()), cwd: PathBuf::from("/tmp/reference-cwd"), + workspace_roots: None, current_date: Some("2026-03-23".to_string()), timezone: Some("America/Los_Angeles".to_string()), approval_policy: AskForApproval::OnRequest, diff --git a/codex-rs/core/src/event_mapping_tests.rs b/codex-rs/core/src/event_mapping_tests.rs index 57d6362f55..df636d4a6b 100644 --- a/codex-rs/core/src/event_mapping_tests.rs +++ b/codex-rs/core/src/event_mapping_tests.rs @@ -1,6 +1,7 @@ use super::parse_turn_item; use crate::context::ContextualUserFragment; -use crate::context::GoalContext; +use crate::context::InternalContextSource; +use crate::context::InternalModelContextFragment; use codex_protocol::items::AgentMessageContent; use codex_protocol::items::HookPromptFragment; use codex_protocol::items::TurnItem; @@ -317,12 +318,16 @@ fn parses_hook_prompt_and_hides_other_contextual_fragments() { } #[test] -fn goal_context_does_not_parse_as_visible_turn_item() { +fn internal_model_context_does_not_parse_as_visible_turn_item() { let item = ResponseItem::Message { id: Some("msg-1".to_string()), role: "user".to_string(), content: vec![ContentItem::InputText { - text: GoalContext::new("Continue working toward the active thread goal.").render(), + text: InternalModelContextFragment::new( + InternalContextSource::from_static("goal"), + "Continue working toward the active thread goal.", + ) + .render(), }], phase: None, }; diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index a485047a32..e050552246 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -225,6 +225,17 @@ impl ExecExpiration { } } + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn cancellation_token(&self) -> Option { + match self { + ExecExpiration::Timeout(_) | ExecExpiration::DefaultTimeout => None, + ExecExpiration::Cancellation(cancellation) + | ExecExpiration::TimeoutOrCancellation { cancellation, .. } => { + Some(cancellation.clone()) + } + } + } + pub(crate) fn with_cancellation(self, cancellation: CancellationToken) -> Self { match self { ExecExpiration::Timeout(timeout) => ExecExpiration::TimeoutOrCancellation { @@ -297,6 +308,7 @@ pub async fn process_exec_tool_call( params: ExecParams, permission_profile: &PermissionProfile, sandbox_cwd: &AbsolutePathBuf, + windows_sandbox_workspace_roots: &[AbsolutePathBuf], codex_linux_sandbox_exe: &Option, use_legacy_landlock: bool, stdout_stream: Option, @@ -305,6 +317,7 @@ pub async fn process_exec_tool_call( params, permission_profile, sandbox_cwd, + windows_sandbox_workspace_roots, codex_linux_sandbox_exe, use_legacy_landlock, )?; @@ -319,6 +332,7 @@ pub fn build_exec_request( params: ExecParams, permission_profile: &PermissionProfile, sandbox_cwd: &AbsolutePathBuf, + windows_sandbox_workspace_roots: &[AbsolutePathBuf], codex_linux_sandbox_exe: &Option, use_legacy_landlock: bool, ) -> Result { @@ -388,7 +402,17 @@ pub fn build_exec_request( .map(|request| { let windows_sandbox_policy_cwd = AbsolutePathBuf::try_from(sandbox_cwd.to_path_buf()) .unwrap_or_else(|_| request.cwd.clone()); - ExecRequest::from_sandbox_exec_request(request, options, windows_sandbox_policy_cwd) + let windows_sandbox_workspace_roots = if windows_sandbox_workspace_roots.is_empty() { + vec![windows_sandbox_policy_cwd.clone()] + } else { + windows_sandbox_workspace_roots.to_vec() + }; + ExecRequest::from_sandbox_exec_request( + request, + options, + windows_sandbox_policy_cwd, + windows_sandbox_workspace_roots, + ) }) .map_err(CodexErr::from)?; let use_windows_elevated_backend = windows_sandbox_uses_elevated_backend( @@ -434,6 +458,7 @@ pub(crate) async fn execute_exec_request( capture_policy, sandbox, windows_sandbox_policy_cwd, + windows_sandbox_workspace_roots, windows_sandbox_level, windows_sandbox_private_desktop, permission_profile, @@ -466,6 +491,7 @@ pub(crate) async fn execute_exec_request( sandbox, &permission_profile, &windows_sandbox_policy_cwd, + &windows_sandbox_workspace_roots, windows_sandbox_filesystem_overrides.as_ref(), ) .await; @@ -482,6 +508,8 @@ async fn get_raw_output_result( #[cfg_attr(not(windows), allow(unused_variables))] sandbox: SandboxType, #[cfg_attr(not(windows), allow(unused_variables))] permission_profile: &PermissionProfile, #[cfg_attr(not(windows), allow(unused_variables))] windows_sandbox_policy_cwd: &AbsolutePathBuf, + #[cfg_attr(not(windows), allow(unused_variables))] + windows_sandbox_workspace_roots: &[AbsolutePathBuf], #[cfg_attr(not(windows), allow(unused_variables))] windows_sandbox_filesystem_overrides: Option< &WindowsSandboxFilesystemOverrides, >, @@ -492,6 +520,7 @@ async fn get_raw_output_result( params, permission_profile, windows_sandbox_policy_cwd, + windows_sandbox_workspace_roots, windows_sandbox_filesystem_overrides, ) .await; @@ -571,6 +600,7 @@ async fn exec_windows_sandbox( params: ExecParams, permission_profile: &PermissionProfile, windows_sandbox_policy_cwd: &AbsolutePathBuf, + windows_sandbox_workspace_roots: &[AbsolutePathBuf], windows_sandbox_filesystem_overrides: Option<&WindowsSandboxFilesystemOverrides>, ) -> Result { use crate::config::find_codex_home; @@ -592,15 +622,23 @@ async fn exec_windows_sandbox( network.apply_to_env(&mut env); } - // TODO(iceweasel-oai): run_windows_sandbox_capture should support all - // variants of ExecExpiration, not just timeout. - let timeout_ms = if capture_policy.uses_expiration() { - expiration.timeout_ms() + // Windows sandbox capture still receives timeout and cancellation separately. + let (cancellation, timeout_ms) = if capture_policy.uses_expiration() { + let cancellation = expiration.cancellation_token().map(|token| { + codex_windows_sandbox::WindowsSandboxCancellationToken::new(move || { + token.is_cancelled() + }) + }); + (cancellation, expiration.timeout_ms()) } else { - None + (None, None) }; - let sandbox_cwd = windows_sandbox_policy_cwd.clone(); + let workspace_roots = if windows_sandbox_workspace_roots.is_empty() { + vec![windows_sandbox_policy_cwd.clone()] + } else { + windows_sandbox_workspace_roots.to_vec() + }; let permission_profile = permission_profile.clone(); let codex_home = find_codex_home().map_err(|err| { CodexErr::Io(io::Error::other(format!( @@ -628,12 +666,13 @@ async fn exec_windows_sandbox( run_windows_sandbox_capture_for_permission_profile_elevated( codex_windows_sandbox::ElevatedSandboxProfileCaptureRequest { permission_profile: &permission_profile, - permission_profile_cwd: &sandbox_cwd, + workspace_roots: workspace_roots.as_slice(), codex_home: codex_home.as_ref(), command, cwd: &cwd, env_map: env, timeout_ms, + cancellation, use_private_desktop: windows_sandbox_private_desktop, proxy_enforced, read_roots_override: elevated_read_roots_override.as_deref(), @@ -647,12 +686,13 @@ async fn exec_windows_sandbox( } else { run_windows_sandbox_capture_with_filesystem_overrides( &permission_profile, - &sandbox_cwd, + workspace_roots.as_slice(), codex_home.as_ref(), command, &cwd, env, timeout_ms, + cancellation, &additional_deny_read_paths, &additional_deny_write_paths, windows_sandbox_private_desktop, diff --git a/codex-rs/core/src/exec_tests.rs b/codex-rs/core/src/exec_tests.rs index 504bac622e..1c71d02651 100644 --- a/codex-rs/core/src/exec_tests.rs +++ b/codex-rs/core/src/exec_tests.rs @@ -364,6 +364,7 @@ async fn process_exec_tool_call_preserves_full_buffer_capture_policy() -> Result }, &permission_profile, &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, @@ -1009,6 +1010,41 @@ fn process_exec_tool_call_uses_platform_sandbox_for_network_only_restrictions() ); } +#[test] +fn build_exec_request_preserves_windows_workspace_roots() -> Result<()> { + let temp_dir = tempfile::TempDir::new()?; + let cwd = temp_dir.path().abs(); + let additional_root = temp_dir.path().join("additional").abs(); + let workspace_roots = vec![cwd.clone(), additional_root]; + + let exec_request = build_exec_request( + ExecParams { + command: vec!["echo".to_string(), "ok".to_string()], + cwd: cwd.clone(), + expiration: ExecExpiration::DefaultTimeout, + capture_policy: ExecCapturePolicy::ShellTool, + env: HashMap::new(), + network: None, + sandbox_permissions: SandboxPermissions::UseDefault, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + justification: None, + arg0: None, + }, + &PermissionProfile::Disabled, + &cwd, + workspace_roots.as_slice(), + &None, + /*use_legacy_landlock*/ false, + )?; + + assert_eq!( + exec_request.windows_sandbox_workspace_roots, + workspace_roots + ); + Ok(()) +} + #[cfg(unix)] #[test] fn sandbox_detection_flags_sigsys_exit_code() { @@ -1114,6 +1150,7 @@ async fn process_exec_tool_call_respects_cancellation_token() -> Result<()> { params, &PermissionProfile::Disabled, &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, @@ -1193,6 +1230,7 @@ while :; do sleep 1; done"# params, &PermissionProfile::Disabled, &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/core/src/goals.rs b/codex-rs/core/src/goals.rs index c8e76f7d41..00b6854342 100644 --- a/codex-rs/core/src/goals.rs +++ b/codex-rs/core/src/goals.rs @@ -6,7 +6,8 @@ use crate::StateDbHandle; use crate::context::ContextualUserFragment; -use crate::context::GoalContext; +use crate::context::InternalContextSource; +use crate::context::InternalModelContextFragment; use crate::session::TurnInput; use crate::session::session::Session; use crate::session::turn_context::TurnContext; @@ -26,7 +27,7 @@ use codex_otel::GOAL_TOKEN_COUNT_METRIC; use codex_otel::GOAL_USAGE_LIMITED_METRIC; use codex_protocol::ThreadId; use codex_protocol::config_types::ModeKind; -use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::ThreadGoal; use codex_protocol::protocol::ThreadGoalStatus; @@ -177,7 +178,7 @@ pub(crate) struct GoalRuntimeState { struct GoalContinuationCandidate { goal_id: String, - items: Vec, + items: Vec, } impl GoalRuntimeState { @@ -686,7 +687,7 @@ impl Session { .await; if let Some(goal) = goal_for_steering { let item = goal_context_input_item(objective_updated_prompt(&goal)); - if self.inject_response_items(vec![item]).await.is_err() { + if self.inject_if_running(vec![item]).await.is_err() { tracing::debug!( "skipping objective-updated goal steering because no turn is active" ); @@ -1074,7 +1075,7 @@ impl Session { .await; if should_steer_budget_limit { let item = budget_limit_steering_item(&goal); - if self.inject_response_items(vec![item]).await.is_err() { + if self.inject_if_running(vec![item]).await.is_err() { tracing::debug!("skipping budget-limit goal steering because no turn is active"); } *self.goal_runtime.budget_limit_reported_goal_id.lock().await = Some(goal_id); @@ -1332,7 +1333,7 @@ impl Session { candidate .items .into_iter() - .map(TurnInput::ResponseInputItem) + .map(TurnInput::ResponseItem) .collect(), ) .await; @@ -1371,14 +1372,6 @@ impl Session { tracing::debug!("skipping active goal continuation because a turn is already active"); return None; } - if self - .input_queue - .has_queued_response_items_for_next_turn() - .await - { - tracing::debug!("skipping active goal continuation because queued input exists"); - return None; - } if self.input_queue.has_trigger_turn_mailbox_items().await { tracing::debug!( "skipping active goal continuation because trigger-turn mailbox input is pending" @@ -1416,10 +1409,6 @@ impl Session { return None; } if self.active_turn.lock().await.is_some() - || self - .input_queue - .has_queued_response_items_for_next_turn() - .await || self.input_queue.has_trigger_turn_mailbox_items().await { tracing::debug!("skipping active goal continuation because pending work appeared"); @@ -1604,12 +1593,15 @@ fn escape_xml_text(input: &str) -> String { .replace('>', ">") } -fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseInputItem { +fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseItem { goal_context_input_item(budget_limit_prompt(goal)) } -fn goal_context_input_item(prompt: String) -> ResponseInputItem { - GoalContext::new(prompt).into_response_input_item() +fn goal_context_input_item(prompt: String) -> ResponseItem { + ContextualUserFragment::into(InternalModelContextFragment::new( + InternalContextSource::from_static("goal"), + prompt, + )) } pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal { @@ -1678,7 +1670,7 @@ mod tests { use codex_protocol::ThreadId; use codex_protocol::config_types::ModeKind; use codex_protocol::models::ContentItem; - use codex_protocol::models::ResponseInputItem; + use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ThreadGoal; use codex_protocol::protocol::ThreadGoalStatus; use codex_protocol::protocol::TokenUsage; @@ -1807,10 +1799,11 @@ mod tests { assert_eq!( item, - ResponseInputItem::Message { + ResponseItem::Message { + id: None, role: "user".to_string(), content: vec![ContentItem::InputText { - text: "\nContinue working.\n".to_string(), + text: "\nContinue working.\n".to_string(), }], phase: None, } diff --git a/codex-rs/core/src/guardian/metrics.rs b/codex-rs/core/src/guardian/metrics.rs new file mode 100644 index 0000000000..9b9d35a526 --- /dev/null +++ b/codex-rs/core/src/guardian/metrics.rs @@ -0,0 +1,418 @@ +use std::time::Duration; + +use codex_analytics::GuardianApprovalRequestSource; +use codex_analytics::GuardianReviewAnalyticsResult; +use codex_analytics::GuardianReviewDecision; +use codex_analytics::GuardianReviewFailureReason; +use codex_analytics::GuardianReviewSessionKind; +use codex_analytics::GuardianReviewTerminalStatus; +use codex_analytics::GuardianReviewedAction; +use codex_otel::GUARDIAN_REVIEW_COUNT_METRIC; +use codex_otel::GUARDIAN_REVIEW_DURATION_METRIC; +use codex_otel::GUARDIAN_REVIEW_TOKEN_USAGE_METRIC; +use codex_otel::GUARDIAN_REVIEW_TTFT_DURATION_METRIC; +use codex_otel::SessionTelemetry; +use codex_otel::sanitize_metric_tag_value; +use codex_protocol::protocol::GuardianAssessmentOutcome; +use codex_protocol::protocol::GuardianRiskLevel; +use codex_protocol::protocol::GuardianUserAuthorization; +use codex_protocol::protocol::TokenUsage; + +pub(crate) fn emit_guardian_review_metrics( + session_telemetry: &SessionTelemetry, + result: &GuardianReviewAnalyticsResult, + approval_request_source: GuardianApprovalRequestSource, + reviewed_action: &GuardianReviewedAction, + completion_latency_ms: u64, +) { + let tags = guardian_review_metric_tags(result, approval_request_source, reviewed_action); + let tag_refs: Vec<(&str, &str)> = tags + .iter() + .map(|(key, value)| (*key, value.as_str())) + .collect(); + + session_telemetry.counter(GUARDIAN_REVIEW_COUNT_METRIC, /*inc*/ 1, &tag_refs); + session_telemetry.record_duration( + GUARDIAN_REVIEW_DURATION_METRIC, + Duration::from_millis(completion_latency_ms), + &tag_refs, + ); + + if let Some(time_to_first_token_ms) = result.time_to_first_token_ms { + session_telemetry.record_duration( + GUARDIAN_REVIEW_TTFT_DURATION_METRIC, + Duration::from_millis(time_to_first_token_ms), + &tag_refs, + ); + } + + if let Some(token_usage) = result.token_usage.as_ref() { + emit_guardian_token_usage_histograms(session_telemetry, token_usage, tags); + } +} + +fn emit_guardian_token_usage_histograms( + session_telemetry: &SessionTelemetry, + token_usage: &TokenUsage, + base_tags: Vec<(&'static str, String)>, +) { + for (token_type, value) in [ + ("total", token_usage.total_tokens.max(0)), + ("input", token_usage.input_tokens.max(0)), + ("cached_input", token_usage.cached_input()), + ("non_cached_input", token_usage.non_cached_input()), + ("output", token_usage.output_tokens.max(0)), + ( + "reasoning_output", + token_usage.reasoning_output_tokens.max(0), + ), + ] { + let mut tags = base_tags.clone(); + tags.push(("token_type", token_type.to_string())); + let tag_refs: Vec<(&str, &str)> = tags + .iter() + .map(|(key, value)| (*key, value.as_str())) + .collect(); + session_telemetry.histogram(GUARDIAN_REVIEW_TOKEN_USAGE_METRIC, value, &tag_refs); + } +} + +fn guardian_review_metric_tags( + result: &GuardianReviewAnalyticsResult, + approval_request_source: GuardianApprovalRequestSource, + reviewed_action: &GuardianReviewedAction, +) -> Vec<(&'static str, String)> { + vec![ + ("decision", decision_tag(result.decision).to_string()), + ( + "terminal_status", + terminal_status_tag(result.terminal_status).to_string(), + ), + ( + "failure_reason", + failure_reason_tag(result.failure_reason).to_string(), + ), + ( + "approval_request_source", + approval_request_source_tag(approval_request_source).to_string(), + ), + ("action", reviewed_action_tag(reviewed_action).to_string()), + ( + "session_kind", + session_kind_tag(result.guardian_session_kind).to_string(), + ), + ( + "had_prior_review_context", + optional_bool_tag(result.had_prior_review_context).to_string(), + ), + ( + "reviewed_action_truncated", + bool_tag(result.reviewed_action_truncated).to_string(), + ), + ("risk_level", risk_level_tag(result.risk_level).to_string()), + ( + "user_authorization", + user_authorization_tag(result.user_authorization).to_string(), + ), + ("outcome", outcome_tag(result.outcome).to_string()), + ( + "guardian_model", + result + .guardian_model + .as_deref() + .map(sanitize_metric_tag_value) + .unwrap_or_else(|| "none".to_string()), + ), + ( + "guardian_reasoning_effort", + result + .guardian_reasoning_effort + .as_deref() + .map(sanitize_metric_tag_value) + .unwrap_or_else(|| "none".to_string()), + ), + ] +} + +fn decision_tag(decision: GuardianReviewDecision) -> &'static str { + match decision { + GuardianReviewDecision::Approved => "approved", + GuardianReviewDecision::Denied => "denied", + GuardianReviewDecision::Aborted => "aborted", + } +} + +fn terminal_status_tag(status: GuardianReviewTerminalStatus) -> &'static str { + match status { + GuardianReviewTerminalStatus::Approved => "approved", + GuardianReviewTerminalStatus::Denied => "denied", + GuardianReviewTerminalStatus::Aborted => "aborted", + GuardianReviewTerminalStatus::TimedOut => "timed_out", + GuardianReviewTerminalStatus::FailedClosed => "failed_closed", + } +} + +fn failure_reason_tag(reason: Option) -> &'static str { + match reason { + Some(GuardianReviewFailureReason::Timeout) => "timeout", + Some(GuardianReviewFailureReason::Cancelled) => "cancelled", + Some(GuardianReviewFailureReason::PromptBuildError) => "prompt_build_error", + Some(GuardianReviewFailureReason::SessionError) => "session_error", + Some(GuardianReviewFailureReason::ParseError) => "parse_error", + None => "none", + } +} + +fn approval_request_source_tag(source: GuardianApprovalRequestSource) -> &'static str { + match source { + GuardianApprovalRequestSource::MainTurn => "main_turn", + GuardianApprovalRequestSource::DelegatedSubagent => "delegated_subagent", + } +} + +fn reviewed_action_tag(action: &GuardianReviewedAction) -> &'static str { + match action { + GuardianReviewedAction::Shell { .. } => "shell", + GuardianReviewedAction::UnifiedExec { .. } => "unified_exec", + GuardianReviewedAction::Execve { .. } => "execve", + GuardianReviewedAction::ApplyPatch {} => "apply_patch", + GuardianReviewedAction::NetworkAccess { .. } => "network_access", + GuardianReviewedAction::McpToolCall { .. } => "mcp_tool_call", + GuardianReviewedAction::RequestPermissions {} => "request_permissions", + } +} + +fn session_kind_tag(kind: Option) -> &'static str { + match kind { + Some(GuardianReviewSessionKind::TrunkNew) => "trunk_new", + Some(GuardianReviewSessionKind::TrunkReused) => "trunk_reused", + Some(GuardianReviewSessionKind::EphemeralForked) => "ephemeral_forked", + None => "none", + } +} + +fn optional_bool_tag(value: Option) -> &'static str { + match value { + Some(true) => "true", + Some(false) => "false", + None => "unknown", + } +} + +fn bool_tag(value: bool) -> &'static str { + if value { "true" } else { "false" } +} + +fn risk_level_tag(risk_level: Option) -> &'static str { + match risk_level { + Some(GuardianRiskLevel::Low) => "low", + Some(GuardianRiskLevel::Medium) => "medium", + Some(GuardianRiskLevel::High) => "high", + Some(GuardianRiskLevel::Critical) => "critical", + None => "none", + } +} + +fn user_authorization_tag(user_authorization: Option) -> &'static str { + match user_authorization { + Some(GuardianUserAuthorization::Unknown) => "unknown", + Some(GuardianUserAuthorization::Low) => "low", + Some(GuardianUserAuthorization::Medium) => "medium", + Some(GuardianUserAuthorization::High) => "high", + None => "none", + } +} + +fn outcome_tag(outcome: Option) -> &'static str { + match outcome { + Some(GuardianAssessmentOutcome::Allow) => "allow", + Some(GuardianAssessmentOutcome::Deny) => "deny", + None => "none", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use codex_otel::MetricsClient; + use codex_otel::MetricsConfig; + use codex_protocol::ThreadId; + use codex_protocol::protocol::SessionSource; + use opentelemetry::KeyValue; + use opentelemetry_sdk::metrics::InMemoryMetricExporter; + use opentelemetry_sdk::metrics::data::AggregatedMetrics; + use opentelemetry_sdk::metrics::data::Metric; + use opentelemetry_sdk::metrics::data::MetricData; + use opentelemetry_sdk::metrics::data::ResourceMetrics; + use pretty_assertions::assert_eq; + use std::collections::BTreeMap; + + fn test_session_telemetry() -> SessionTelemetry { + let exporter = InMemoryMetricExporter::default(); + let metrics = MetricsClient::new( + MetricsConfig::in_memory("test", "codex-core", env!("CARGO_PKG_VERSION"), exporter) + .with_runtime_reader(), + ) + .expect("in-memory metrics client"); + SessionTelemetry::new( + ThreadId::new(), + "gpt-5.4", + "gpt-5.4", + /*account_id*/ None, + /*account_email*/ None, + /*auth_mode*/ None, + "test_originator".to_string(), + /*log_user_prompts*/ false, + "tty".to_string(), + SessionSource::Cli, + ) + .with_metrics_without_metadata_tags(metrics) + } + + fn find_metric<'a>(resource_metrics: &'a ResourceMetrics, name: &str) -> &'a Metric { + for scope_metrics in resource_metrics.scope_metrics() { + for metric in scope_metrics.metrics() { + if metric.name() == name { + return metric; + } + } + } + panic!("metric {name} missing"); + } + + fn attributes_to_map<'a>( + attributes: impl Iterator, + ) -> BTreeMap { + attributes + .map(|kv| (kv.key.as_str().to_string(), kv.value.as_str().to_string())) + .collect() + } + + fn counter_point( + resource_metrics: &ResourceMetrics, + name: &str, + ) -> (BTreeMap, u64) { + let metric = find_metric(resource_metrics, name); + match metric.data() { + AggregatedMetrics::U64(data) => match data { + MetricData::Sum(sum) => { + let points: Vec<_> = sum.data_points().collect(); + assert_eq!(points.len(), 1); + let point = points[0]; + (attributes_to_map(point.attributes()), point.value()) + } + _ => panic!("unexpected counter aggregation"), + }, + _ => panic!("unexpected counter data type"), + } + } + + fn histogram_sums(resource_metrics: &ResourceMetrics, name: &str) -> BTreeMap { + let metric = find_metric(resource_metrics, name); + match metric.data() { + AggregatedMetrics::F64(data) => match data { + MetricData::Histogram(histogram) => histogram + .data_points() + .map(|point| { + let attrs = attributes_to_map(point.attributes()); + ( + attrs + .get("token_type") + .cloned() + .unwrap_or_else(|| "sample".to_string()), + point.sum() as u64, + ) + }) + .collect(), + _ => panic!("unexpected histogram aggregation"), + }, + _ => panic!("unexpected histogram data type"), + } + } + + #[test] + fn guardian_review_metrics_record_counts_durations_and_token_usage() { + let session_telemetry = test_session_telemetry(); + let result = GuardianReviewAnalyticsResult { + decision: GuardianReviewDecision::Approved, + terminal_status: GuardianReviewTerminalStatus::Approved, + risk_level: Some(GuardianRiskLevel::Low), + user_authorization: Some(GuardianUserAuthorization::High), + outcome: Some(GuardianAssessmentOutcome::Allow), + guardian_session_kind: Some(GuardianReviewSessionKind::TrunkReused), + guardian_model: Some("gpt-5.4 guardian".to_string()), + guardian_reasoning_effort: Some("low".to_string()), + had_prior_review_context: Some(true), + reviewed_action_truncated: true, + token_usage: Some(TokenUsage { + input_tokens: 10, + cached_input_tokens: 4, + output_tokens: 3, + reasoning_output_tokens: 2, + total_tokens: 15, + }), + time_to_first_token_ms: Some(123), + ..GuardianReviewAnalyticsResult::without_session() + }; + + emit_guardian_review_metrics( + &session_telemetry, + &result, + GuardianApprovalRequestSource::DelegatedSubagent, + &GuardianReviewedAction::NetworkAccess { + protocol: codex_protocol::approvals::NetworkApprovalProtocol::Https, + port: 443, + }, + /*completion_latency_ms*/ 456, + ); + + let snapshot = session_telemetry + .snapshot_metrics() + .expect("runtime metrics snapshot"); + let (attrs, value) = counter_point(&snapshot, GUARDIAN_REVIEW_COUNT_METRIC); + + assert_eq!(value, 1); + assert_eq!( + attrs, + BTreeMap::from([ + ("action".to_string(), "network_access".to_string()), + ( + "approval_request_source".to_string(), + "delegated_subagent".to_string() + ), + ("decision".to_string(), "approved".to_string()), + ("failure_reason".to_string(), "none".to_string()), + ("guardian_model".to_string(), "gpt-5.4_guardian".to_string()), + ("guardian_reasoning_effort".to_string(), "low".to_string()), + ("had_prior_review_context".to_string(), "true".to_string()), + ("outcome".to_string(), "allow".to_string()), + ("reviewed_action_truncated".to_string(), "true".to_string()), + ("risk_level".to_string(), "low".to_string()), + ("session_kind".to_string(), "trunk_reused".to_string()), + ("terminal_status".to_string(), "approved".to_string()), + ("user_authorization".to_string(), "high".to_string()), + ]) + ); + + assert_eq!( + histogram_sums(&snapshot, GUARDIAN_REVIEW_TOKEN_USAGE_METRIC), + BTreeMap::from([ + ("cached_input".to_string(), 4), + ("input".to_string(), 10), + ("non_cached_input".to_string(), 6), + ("output".to_string(), 3), + ("reasoning_output".to_string(), 2), + ("total".to_string(), 15), + ]) + ); + assert_eq!( + histogram_sums(&snapshot, GUARDIAN_REVIEW_DURATION_METRIC), + BTreeMap::from([("sample".to_string(), 456)]) + ); + assert_eq!( + histogram_sums(&snapshot, GUARDIAN_REVIEW_TTFT_DURATION_METRIC), + BTreeMap::from([("sample".to_string(), 123)]) + ); + } +} diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index 058c19d008..8cc04e5c42 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -12,6 +12,7 @@ //! 4. Apply the guardian's explicit allow/deny outcome. mod approval_request; +mod metrics; mod prompt; mod review; mod review_session; @@ -40,6 +41,7 @@ pub(crate) use review::review_approval_request_with_cancel; pub(crate) use review::routes_approval_to_guardian; pub(crate) use review::spawn_approval_request_review; pub(crate) use review_session::GuardianReviewSessionManager; +pub(crate) use review_session::prompt_cache_key_override_for_review_session; pub(crate) const GUARDIAN_REVIEW_TIMEOUT: Duration = Duration::from_secs(90); pub(crate) const GUARDIAN_REVIEWER_NAME: &str = "guardian"; @@ -147,6 +149,8 @@ use prompt::GuardianTranscriptEntryKind; #[cfg(test)] use prompt::build_guardian_prompt_items; #[cfg(test)] +use prompt::build_guardian_prompt_items_with_parent_turn; +#[cfg(test)] use prompt::collect_guardian_transcript_entries; #[cfg(test)] use prompt::guardian_output_schema; diff --git a/codex-rs/core/src/guardian/prompt.rs b/codex-rs/core/src/guardian/prompt.rs index b1b132a984..062a21deef 100644 --- a/codex-rs/core/src/guardian/prompt.rs +++ b/codex-rs/core/src/guardian/prompt.rs @@ -10,6 +10,7 @@ use serde_json::Value; use crate::compact::content_items_to_text; use crate::event_mapping::is_contextual_user_message_content; use crate::session::session::Session; +use crate::session::turn_context::TurnContext; use codex_utils_output_truncation::approx_bytes_for_tokens; use codex_utils_output_truncation::approx_token_count; use codex_utils_output_truncation::approx_tokens_from_byte_count; @@ -86,11 +87,29 @@ pub(crate) enum GuardianPromptMode { /// Split the variable request into separate user content items so the /// Responses request snapshot shows clear boundaries while preserving exact /// prompt text through trailing newlines. +#[cfg(test)] pub(crate) async fn build_guardian_prompt_items( session: &Session, retry_reason: Option, request: GuardianApprovalRequest, mode: GuardianPromptMode, +) -> serde_json::Result { + build_guardian_prompt_items_with_parent_turn( + session, + /*parent_turn*/ None, + retry_reason, + request, + mode, + ) + .await +} + +pub(crate) async fn build_guardian_prompt_items_with_parent_turn( + session: &Session, + parent_turn: Option<&TurnContext>, + retry_reason: Option, + request: GuardianApprovalRequest, + mode: GuardianPromptMode, ) -> serde_json::Result { let history = session.clone_history().await; let transcript_entries = collect_guardian_transcript_entries(history.raw_items()); @@ -172,6 +191,11 @@ pub(crate) async fn build_guardian_prompt_items( if let Some(note) = omission_note { push_text(format!("\n{note}\n")); } + if let Some(denied_reads_context) = parent_turn.and_then(parent_turn_denied_reads_context) { + push_text("\n>>> PARENT TURN PERMISSION CONTEXT START\n".to_string()); + push_text(denied_reads_context); + push_text(">>> PARENT TURN PERMISSION CONTEXT END\n".to_string()); + } match &request { GuardianApprovalRequest::NetworkAccess { trigger, .. } => { push_text(">>> APPROVAL REQUEST START\n".to_string()); @@ -216,6 +240,31 @@ pub(crate) async fn build_guardian_prompt_items( }) } +fn parent_turn_denied_reads_context(turn: &TurnContext) -> Option { + #[allow(deprecated)] + let cwd = &turn.cwd; + let file_system_policy = turn.permission_profile.file_system_sandbox_policy(); + let mut entries = file_system_policy + .get_unreadable_roots_with_cwd(cwd) + .into_iter() + .map(|root| format!("- path `{}`", root.to_string_lossy())) + .collect::>(); + entries.extend( + file_system_policy + .get_unreadable_globs_with_cwd(cwd) + .into_iter() + .map(|glob| format!("- glob `{glob}`")), + ); + if entries.is_empty() { + return None; + } + + Some(format!( + "The parent turn's active permission profile denies reading these paths/globs. These are policy restrictions; do not approve escalation whose purpose is to read them.\n{}\n", + entries.join("\n") + )) +} + enum GuardianPromptShape { Full, Delta { already_seen_entry_count: usize }, diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 7df7a96928..db4343448f 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -4,6 +4,7 @@ use codex_analytics::GuardianReviewDecision; use codex_analytics::GuardianReviewFailureReason; use codex_analytics::GuardianReviewTerminalStatus; use codex_analytics::GuardianReviewTrackContext; +use codex_analytics::GuardianReviewedAction; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -36,6 +37,7 @@ use super::approval_request::guardian_assessment_action; use super::approval_request::guardian_request_target_item_id; use super::approval_request::guardian_request_turn_id; use super::approval_request::guardian_reviewed_action; +use super::metrics::emit_guardian_review_metrics; use super::prompt::guardian_output_schema; use super::prompt::parse_guardian_assessment; use super::review_session::GuardianReviewSessionOutcome; @@ -162,9 +164,18 @@ pub(crate) fn is_guardian_reviewer_source( fn track_guardian_review( session: &Session, tracking: &GuardianReviewTrackContext, + approval_request_source: GuardianApprovalRequestSource, + reviewed_action: &GuardianReviewedAction, result: GuardianReviewAnalyticsResult, completed_at_ms: u64, ) { + emit_guardian_review_metrics( + &session.services.session_telemetry, + &result, + approval_request_source, + reviewed_action, + completed_at_ms.saturating_sub(tracking.started_at_ms), + ); session .services .analytics_events_client @@ -244,13 +255,14 @@ async fn run_guardian_review( let target_item_id = guardian_request_target_item_id(&request).map(str::to_string); let assessment_turn_id = guardian_request_turn_id(&request, &turn.sub_id).to_string(); let action_summary = guardian_assessment_action(&request); + let reviewed_action = guardian_reviewed_action(&request); let review_tracking = GuardianReviewTrackContext::new( session.conversation_id.to_string(), assessment_turn_id.clone(), review_id.clone(), target_item_id.clone(), approval_request_source, - guardian_reviewed_action(&request), + reviewed_action.clone(), GUARDIAN_REVIEW_TIMEOUT.as_millis() as u64, ); let started_at_ms = review_tracking.started_at_ms.try_into().unwrap_or_default(); @@ -281,6 +293,8 @@ async fn run_guardian_review( track_guardian_review( session.as_ref(), &review_tracking, + approval_request_source, + &reviewed_action, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Aborted, terminal_status: GuardianReviewTerminalStatus::Aborted, @@ -330,6 +344,8 @@ async fn run_guardian_review( track_guardian_review( session.as_ref(), &review_tracking, + approval_request_source, + &reviewed_action, GuardianReviewAnalyticsResult { decision: if approved { GuardianReviewDecision::Approved @@ -361,6 +377,8 @@ async fn run_guardian_review( track_guardian_review( session.as_ref(), &review_tracking, + approval_request_source, + &reviewed_action, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Denied, terminal_status: GuardianReviewTerminalStatus::TimedOut, @@ -402,6 +420,8 @@ async fn run_guardian_review( track_guardian_review( session.as_ref(), &review_tracking, + approval_request_source, + &reviewed_action, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Aborted, terminal_status: GuardianReviewTerminalStatus::Aborted, @@ -446,6 +466,8 @@ async fn run_guardian_review( track_guardian_review( session.as_ref(), &review_tracking, + approval_request_source, + &reviewed_action, GuardianReviewAnalyticsResult { decision: GuardianReviewDecision::Denied, terminal_status: GuardianReviewTerminalStatus::FailedClosed, diff --git a/codex-rs/core/src/guardian/review_session.rs b/codex-rs/core/src/guardian/review_session.rs index 67f733e0ba..fed87cd75f 100644 --- a/codex-rs/core/src/guardian/review_session.rs +++ b/codex-rs/core/src/guardian/review_session.rs @@ -7,6 +7,7 @@ use std::time::Duration; use anyhow::anyhow; use codex_analytics::GuardianReviewAnalyticsResult; use codex_analytics::GuardianReviewSessionKind; +use codex_protocol::ThreadId; use codex_protocol::config_types::AutoCompactTokenLimitScope; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; @@ -20,6 +21,7 @@ use codex_protocol::protocol::InitialHistory; use codex_protocol::protocol::Op; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::TokenUsage; use serde_json::Value; @@ -49,7 +51,7 @@ use super::GUARDIAN_REVIEWER_NAME; use super::GuardianApprovalRequest; use super::prompt::GuardianPromptMode; use super::prompt::GuardianTranscriptCursor; -use super::prompt::build_guardian_prompt_items; +use super::prompt::build_guardian_prompt_items_with_parent_turn; use super::prompt::guardian_policy_prompt; use super::prompt::guardian_policy_prompt_with_config; @@ -183,6 +185,20 @@ impl GuardianReviewSessionReuseKey { } } +pub(crate) fn prompt_cache_key_override_for_review_session( + session_source: &SessionSource, + parent_thread_id: Option, +) -> Option { + let SessionSource::SubAgent(SubAgentSource::Other(name)) = session_source else { + return None; + }; + if name != GUARDIAN_REVIEWER_NAME { + return None; + } + let parent_thread_id = parent_thread_id?; + Some(format!("guardian:{parent_thread_id}")) +} + impl GuardianReviewSession { async fn shutdown(&self) { self.cancel_token.cancel(); @@ -670,8 +686,9 @@ async fn run_review_on_session( ) .await; - build_guardian_prompt_items( + build_guardian_prompt_items_with_parent_turn( params.parent_session.as_ref(), + Some(params.parent_turn.as_ref()), params.retry_reason.clone(), params.request.clone(), prompt_mode, @@ -774,12 +791,11 @@ async fn run_review_on_session( } async fn append_guardian_followup_reminder(review_session: &GuardianReviewSession) { - let turn_context = review_session.codex.session.new_default_turn().await; let reminder: ResponseItem = ContextualUserFragment::into(GuardianFollowupReviewReminder); review_session .codex .session - .record_conversation_items(turn_context.as_ref(), std::slice::from_ref(&reminder)) + .inject_no_new_turn(vec![reminder], /*current_turn_context*/ None) .await; } @@ -1160,6 +1176,46 @@ mod tests { ); } + #[tokio::test] + async fn guardian_prompt_cache_key_is_scoped_to_parent_thread() { + let session_source = + SessionSource::SubAgent(SubAgentSource::Other(GUARDIAN_REVIEWER_NAME.to_string())); + let parent_thread_id = ThreadId::new(); + let key = + prompt_cache_key_override_for_review_session(&session_source, Some(parent_thread_id)) + .expect("guardian prompt cache key"); + + assert_eq!(key, format!("guardian:{parent_thread_id}")); + assert!( + key.len() <= 64, + "guardian prompt cache key should fit the Responses API limit" + ); + assert_eq!( + key, + prompt_cache_key_override_for_review_session(&session_source, Some(parent_thread_id)) + .expect("same guardian prompt cache key") + ); + assert_ne!( + key, + prompt_cache_key_override_for_review_session(&session_source, Some(ThreadId::new())) + .expect("different parent guardian prompt cache key") + ); + assert_eq!( + None, + prompt_cache_key_override_for_review_session( + &SessionSource::Cli, + Some(parent_thread_id) + ) + ); + assert_eq!( + None, + prompt_cache_key_override_for_review_session( + &session_source, + /*parent_thread_id*/ None + ) + ); + } + #[tokio::test] async fn guardian_review_session_compact_scope_change_invalidates_cached_session() { let parent_config = crate::config::test_config().await; diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 00f0d9be38..3d44fa41de 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -33,6 +33,11 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -191,7 +196,8 @@ async fn guardian_test_session_and_turn_with_base_url( async fn seed_guardian_parent_history(session: &Arc, turn: &Arc) { session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -225,7 +231,6 @@ async fn seed_guardian_parent_history(session: &Arc, turn: &Arc an Ok(()) } +#[tokio::test(flavor = "current_thread")] +async fn build_guardian_prompt_includes_parent_turn_denied_reads() -> anyhow::Result<()> { + let (mut session, mut turn) = crate::session::tests::make_session_and_context().await; + session.conversation_id = fixed_guardian_parent_session_id(); + let denied_root = test_path_buf("/repo/private").abs(); + let denied_glob = test_path_buf("/repo/private/**").display().to_string(); + turn.permission_profile = PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: codex_protocol::permissions::FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_root.clone(), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: denied_glob.clone(), + }, + access: FileSystemAccessMode::Deny, + }, + ]), + NetworkSandboxPolicy::Restricted, + ); + let session = Arc::new(session); + let turn = Arc::new(turn); + seed_guardian_parent_history(&session, &turn).await; + + let prompt = build_guardian_prompt_items_with_parent_turn( + session.as_ref(), + Some(turn.as_ref()), + Some("Sandbox denied reading /repo/private/secret.txt.".to_string()), + GuardianApprovalRequest::Shell { + id: "shell-1".to_string(), + command: vec!["cat".to_string(), "/repo/private/secret.txt".to_string()], + cwd: test_path_buf("/repo").abs(), + sandbox_permissions: crate::sandboxing::SandboxPermissions::RequireEscalated, + additional_permissions: None, + justification: Some("Need to inspect the secret file.".to_string()), + }, + GuardianPromptMode::Full, + ) + .await?; + + let text = guardian_prompt_text(&prompt.items); + assert!(text.contains("PARENT TURN PERMISSION CONTEXT START")); + assert!(text.contains("do not approve escalation whose purpose is to read them")); + assert!(text.contains(denied_root.to_string_lossy().as_ref())); + assert!(text.contains(&format!("glob `{denied_glob}`"))); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn build_guardian_prompt_delta_mode_preserves_original_numbering() -> anyhow::Result<()> { let (session, turn) = guardian_test_session_and_turn_with_base_url("http://localhost").await; seed_guardian_parent_history(&session, &turn).await; session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -381,7 +445,6 @@ async fn build_guardian_prompt_delta_mode_preserves_original_numbering() -> anyh phase: None, }, ], - turn.as_ref(), ) .await; @@ -516,7 +579,8 @@ async fn build_guardian_prompt_stale_delta_version_falls_back_to_full_prompt() - ) .await; session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -535,7 +599,6 @@ async fn build_guardian_prompt_stale_delta_version_falls_back_to_full_prompt() - phase: None, }, ], - turn.as_ref(), ) .await; @@ -1469,7 +1532,8 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: ) .await; session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -1488,7 +1552,6 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: phase: None, }, ], - turn.as_ref(), ) .await; let second_request = GuardianApprovalRequest::Shell { @@ -1513,7 +1576,8 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: ) .await; session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -1532,7 +1596,6 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: phase: None, }, ], - turn.as_ref(), ) .await; let third_request = GuardianApprovalRequest::Shell { @@ -2005,7 +2068,8 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a ReviewDecision::Approved ); session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -2024,7 +2088,6 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a phase: None, }, ], - turn.as_ref(), ) .await; @@ -2072,7 +2135,8 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a "second guardian request was not observed" ); session - .record_into_history( + .record_conversation_items( + turn.as_ref(), &[ ResponseItem::Message { id: None, @@ -2091,7 +2155,6 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a phase: None, }, ], - turn.as_ref(), ) .await; @@ -2106,7 +2169,13 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a assert_eq!(third_decision, ReviewDecision::Approved); let requests = server.requests().await; assert_eq!(requests.len(), 3); + let second_request_body = serde_json::from_slice::(&requests[1])?; let third_request_body = serde_json::from_slice::(&requests[2])?; + assert_eq!( + second_request_body["prompt_cache_key"], + third_request_body["prompt_cache_key"], + "forked guardian review should reuse the trunk guardian prompt cache key" + ); let third_request_body_text = third_request_body.to_string(); assert!( third_request_body_text.contains("first guardian rationale"), diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 6452e9d5ad..80a1997477 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -500,7 +500,7 @@ pub(crate) async fn inspect_pending_input( pending_input_item: &TurnInput, ) -> HookRuntimeOutcome { match pending_input_item { - TurnInput::UserInput(content) => { + TurnInput::UserInput { content, .. } => { let request = UserPromptSubmitRequest { session_id: sess.session_id().into(), turn_id: turn_context.sub_id.clone(), @@ -522,7 +522,7 @@ pub(crate) async fn inspect_pending_input( ) .await } - TurnInput::ResponseInputItem(_) => HookRuntimeOutcome { + TurnInput::ResponseItem(_) => HookRuntimeOutcome { should_stop: false, additional_contexts: Vec::new(), }, @@ -536,13 +536,16 @@ pub(crate) async fn record_pending_input( additional_contexts: Vec, ) { match pending_input { - TurnInput::UserInput(content) => { - sess.record_user_prompt_and_emit_turn_item(turn_context.as_ref(), content.as_slice()) - .await; + TurnInput::UserInput { content, client_id } => { + sess.record_user_prompt_and_emit_turn_item( + turn_context.as_ref(), + content.as_slice(), + client_id, + ) + .await; } - TurnInput::ResponseInputItem(input) => { - let response_item = ResponseItem::from(input); - sess.record_conversation_items(turn_context, std::slice::from_ref(&response_item)) + TurnInput::ResponseItem(item) => { + sess.record_conversation_items(turn_context, std::slice::from_ref(&item)) .await; } } diff --git a/codex-rs/core/src/mcp_tool_exposure.rs b/codex-rs/core/src/mcp_tool_exposure.rs index e58be65f9c..5dc66af734 100644 --- a/codex-rs/core/src/mcp_tool_exposure.rs +++ b/codex-rs/core/src/mcp_tool_exposure.rs @@ -3,6 +3,7 @@ use std::collections::HashSet; use codex_features::Feature; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_mcp::ToolInfo as McpToolInfo; +use codex_mcp::tool_is_model_visible; use crate::config::Config; use crate::connectors; @@ -51,7 +52,9 @@ pub(crate) fn build_mcp_tool_exposure( fn filter_non_codex_apps_mcp_tools_only(mcp_tools: &[McpToolInfo]) -> Vec { mcp_tools .iter() - .filter(|tool| tool.server_name != CODEX_APPS_MCP_SERVER_NAME) + .filter(|tool| { + tool.server_name != CODEX_APPS_MCP_SERVER_NAME && tool_is_model_visible(tool) + }) .cloned() .collect() } @@ -72,6 +75,9 @@ fn filter_codex_apps_mcp_tools( if tool.server_name != CODEX_APPS_MCP_SERVER_NAME { return false; } + if !tool_is_model_visible(tool) { + return false; + } let Some(connector_id) = tool.connector_id.as_deref() else { return false; }; diff --git a/codex-rs/core/src/mcp_tool_exposure_test.rs b/codex-rs/core/src/mcp_tool_exposure_test.rs index c23e1e3765..4918f768aa 100644 --- a/codex-rs/core/src/mcp_tool_exposure_test.rs +++ b/codex-rs/core/src/mcp_tool_exposure_test.rs @@ -7,6 +7,7 @@ use codex_mcp::ToolInfo; use codex_tools::ToolName; use pretty_assertions::assert_eq; use rmcp::model::JsonObject; +use rmcp::model::Meta; use rmcp::model::Tool; use super::*; @@ -80,6 +81,16 @@ fn tool_names(tools: &[ToolInfo]) -> HashSet { .collect() } +fn with_visibility(mut tool: ToolInfo, visibility: &[&str]) -> ToolInfo { + tool.tool.meta = Some(Meta( + serde_json::json!({ "ui": { "visibility": visibility } }) + .as_object() + .expect("metadata object") + .clone(), + )); + tool +} + #[tokio::test] async fn directly_exposes_small_effective_tool_sets() { let config = test_config().await; @@ -93,6 +104,84 @@ async fn directly_exposes_small_effective_tool_sets() { assert!(exposure.deferred_tools.is_none()); } +#[tokio::test] +async fn excludes_tools_hidden_from_model_exposure() { + let config = test_config().await; + let visible_tool = make_mcp_tool( + "rmcp", + "visible_tool", + "mcp__rmcp", + "visible_tool", + /*connector_id*/ None, + /*connector_name*/ None, + ); + let hidden_tool = with_visibility( + make_mcp_tool( + "rmcp", + "hidden_tool", + "mcp__rmcp", + "hidden_tool", + /*connector_id*/ None, + /*connector_name*/ None, + ), + &["app"], + ); + let empty_visibility_tool = with_visibility( + make_mcp_tool( + "rmcp", + "empty_visibility_tool", + "mcp__rmcp", + "empty_visibility_tool", + /*connector_id*/ None, + /*connector_name*/ None, + ), + &[], + ); + let visible_app_tool = with_visibility( + make_mcp_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_read", + "mcp__codex_apps__calendar", + "read", + Some("calendar"), + Some("Calendar"), + ), + &["app", "model"], + ); + let hidden_app_tool = with_visibility( + make_mcp_tool( + CODEX_APPS_MCP_SERVER_NAME, + "calendar_open", + "mcp__codex_apps__calendar", + "open", + Some("calendar"), + Some("Calendar"), + ), + &["app"], + ); + let mcp_tools = vec![ + visible_tool.clone(), + hidden_tool, + empty_visibility_tool, + visible_app_tool.clone(), + hidden_app_tool, + ]; + let connectors = vec![make_connector("calendar", "Calendar")]; + + let exposure = build_mcp_tool_exposure( + &mcp_tools, + Some(connectors.as_slice()), + &config, + /*search_tool_enabled*/ false, + ); + + assert_eq!( + tool_names(&exposure.direct_tools), + tool_names(&[visible_tool, visible_app_tool]) + ); + assert!(exposure.deferred_tools.is_none()); +} + #[tokio::test] async fn searches_large_effective_tool_sets() { let config = test_config().await; diff --git a/codex-rs/core/src/personality_migration_tests.rs b/codex-rs/core/src/personality_migration_tests.rs index b84d6dd3eb..ba9a037d7a 100644 --- a/codex-rs/core/src/personality_migration_tests.rs +++ b/codex-rs/core/src/personality_migration_tests.rs @@ -68,6 +68,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R let user_event = RolloutLine { timestamp: TEST_TIMESTAMP.to_string(), item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index 5070d8da3a..f853ea3ba6 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -52,6 +52,7 @@ pub struct ExecRequest { pub capture_policy: ExecCapturePolicy, pub sandbox: SandboxType, pub windows_sandbox_policy_cwd: AbsolutePathBuf, + pub windows_sandbox_workspace_roots: Vec, pub windows_sandbox_level: WindowsSandboxLevel, pub windows_sandbox_private_desktop: bool, pub permission_profile: PermissionProfile, @@ -71,6 +72,7 @@ impl ExecRequest { expiration: ExecExpiration, capture_policy: ExecCapturePolicy, sandbox: SandboxType, + windows_sandbox_workspace_roots: Vec, windows_sandbox_level: WindowsSandboxLevel, windows_sandbox_private_desktop: bool, permission_profile: PermissionProfile, @@ -89,6 +91,7 @@ impl ExecRequest { capture_policy, sandbox, windows_sandbox_policy_cwd, + windows_sandbox_workspace_roots, windows_sandbox_level, windows_sandbox_private_desktop, permission_profile, @@ -112,6 +115,7 @@ impl ExecRequest { request: SandboxExecRequest, options: ExecOptions, windows_sandbox_policy_cwd: AbsolutePathBuf, + windows_sandbox_workspace_roots: Vec, ) -> Self { let SandboxExecRequest { command, @@ -150,6 +154,7 @@ impl ExecRequest { capture_policy, sandbox, windows_sandbox_policy_cwd, + windows_sandbox_workspace_roots, windows_sandbox_level, windows_sandbox_private_desktop, permission_profile, diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index cf46ecba9a..135ea61194 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -27,6 +27,7 @@ use crate::tasks::UserShellCommandTask; use crate::tasks::execute_user_shell_command; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::Event; @@ -84,12 +85,18 @@ pub async fn realtime_conversation_list_voices(sess: &Session, sub_id: String) { .await; } -pub async fn user_input_or_turn(sess: &Arc, sub_id: String, op: Op) { +pub async fn user_input_or_turn( + sess: &Arc, + sub_id: String, + op: Op, + client_user_message_id: Option, +) { user_input_or_turn_inner( sess, sub_id, op, /*mirror_user_text_to_realtime*/ Some(()), + client_user_message_id, ) .await; } @@ -189,6 +196,7 @@ pub(super) async fn user_input_or_turn_inner( sub_id: String, op: Op, mirror_user_text_to_realtime: Option<()>, + client_user_message_id: Option, ) { let Op::UserInput { items, @@ -228,6 +236,7 @@ pub(super) async fn user_input_or_turn_inner( items.clone(), additional_context.clone(), /*expected_turn_id*/ None, + client_user_message_id.clone(), responsesapi_client_metadata.clone(), ) .await @@ -255,10 +264,14 @@ pub(super) async fn user_input_or_turn_inner( }; let mut task_input = additional_context_input .into_iter() - .map(TurnInput::ResponseInputItem) + .map(ResponseItem::from) + .map(TurnInput::ResponseItem) .collect::>(); if !items.is_empty() { - task_input.push(TurnInput::UserInput(items)); + task_input.push(TurnInput::UserInput { + content: items, + client_id: client_user_message_id, + }); } sess.spawn_task( Arc::clone(¤t_context), @@ -771,7 +784,8 @@ pub(super) async fn submission_loop( false } Op::UserInput { .. } => { - user_input_or_turn(&sess, sub.id.clone(), sub.op).await; + user_input_or_turn(&sess, sub.id.clone(), sub.op, sub.client_user_message_id) + .await; false } Op::ThreadSettings { thread_settings } => { @@ -899,17 +913,14 @@ Do not assume this also authorizes similar operations with different payloads. Approved action: {approved_action_json}"#, ); - let items = vec![ResponseInputItem::Message { + let items = vec![ResponseItem::from(ResponseInputItem::Message { role: "developer".to_string(), content: vec![ContentItem::InputText { text }], phase: None, - }]; + })]; - if let Err(items) = sess.inject_response_items(items).await { - sess.input_queue - .queue_response_items_for_next_turn(items) - .await; - } + sess.inject_no_new_turn(items, /*current_turn_context*/ None) + .await; } pub(super) fn submission_dispatch_span(sub: &Submission) -> tracing::Span { diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs new file mode 100644 index 0000000000..4a7189bbd6 --- /dev/null +++ b/codex-rs/core/src/session/inject.rs @@ -0,0 +1,50 @@ +use super::input_queue::TurnInput; +use super::session::Session; +use super::turn_context::TurnContext; +use codex_protocol::models::ResponseItem; + +impl Session { + /// Returns the input if there is no active turn to inject into. + #[expect( + clippy::await_holding_invalid_type, + reason = "active turn checks and turn state updates must remain atomic" + )] + pub async fn inject_if_running( + &self, + input: Vec, + ) -> Result<(), Vec> { + let mut active = self.active_turn.lock().await; + match active.as_mut() { + Some(active_turn) => { + self.input_queue + .extend_pending_input_for_turn_state( + active_turn.turn_state.as_ref(), + input.into_iter().map(TurnInput::ResponseItem).collect(), + ) + .await; + Ok(()) + } + None => Err(input), + } + } + + /// Injects items into active work, or records them without starting a turn. + pub(crate) async fn inject_no_new_turn( + &self, + items: Vec, + current_turn_context: Option<&TurnContext>, + ) { + let Err(items) = self.inject_if_running(items).await else { + return; + }; + let default_turn_context; + let turn_context = match current_turn_context { + Some(turn_context) => turn_context, + None => { + default_turn_context = self.new_default_turn().await; + default_turn_context.as_ref() + } + }; + self.record_conversation_items(turn_context, &items).await; + } +} diff --git a/codex-rs/core/src/session/input_queue.rs b/codex-rs/core/src/session/input_queue.rs index 620c410eb8..b62383e091 100644 --- a/codex-rs/core/src/session/input_queue.rs +++ b/codex-rs/core/src/session/input_queue.rs @@ -1,7 +1,7 @@ use crate::state::ActiveTurn; use crate::state::MailboxDeliveryPhase; use crate::state::TurnState; -use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::InterAgentCommunication; use codex_protocol::user_input::UserInput; use std::collections::VecDeque; @@ -11,8 +11,11 @@ use tokio::sync::watch; #[derive(Clone, Debug, PartialEq)] pub(crate) enum TurnInput { - UserInput(Vec), - ResponseInputItem(ResponseInputItem), + UserInput { + content: Vec, + client_id: Option, + }, + ResponseItem(ResponseItem), } /// Turn-local pending input storage owned by the input queue flow. @@ -25,8 +28,6 @@ pub(crate) struct TurnInputQueue { pub(crate) struct InputQueue { mailbox_tx: watch::Sender<()>, mailbox_pending_mails: Mutex>, - - idle_pending_input: Mutex>, } impl InputQueue { @@ -35,7 +36,6 @@ impl InputQueue { Self { mailbox_tx, mailbox_pending_mails: Mutex::new(VecDeque::new()), - idle_pending_input: Mutex::new(Vec::new()), } } @@ -70,31 +70,15 @@ impl InputQueue { .any(|mail| mail.trigger_turn) } - pub(crate) async fn drain_mailbox_input_items(&self) -> Vec { + pub(crate) async fn drain_mailbox_input_items(&self) -> Vec { self.mailbox_pending_mails .lock() .await .drain(..) - .map(|mail| mail.to_response_input_item()) + .map(|mail| ResponseItem::from(mail.to_response_input_item())) .collect() } - pub(crate) async fn queue_response_items_for_next_turn(&self, items: Vec) { - if items.is_empty() { - return; - } - - self.idle_pending_input.lock().await.extend(items); - } - - pub(crate) async fn take_queued_response_items_for_next_turn(&self) -> Vec { - std::mem::take(&mut *self.idle_pending_input.lock().await) - } - - pub(crate) async fn has_queued_response_items_for_next_turn(&self) -> bool { - !self.idle_pending_input.lock().await.is_empty() - } - pub(crate) async fn turn_state_for_sub_id( &self, active_turn: &Mutex>, @@ -181,32 +165,6 @@ impl InputQueue { turn_state.lock().await.pending_input.items.split_off(0) } - #[expect( - clippy::await_holding_invalid_type, - reason = "active turn checks and turn state updates must remain atomic" - )] - pub(crate) async fn inject_response_items( - &self, - active_turn: &Mutex>, - input: Vec, - ) -> Result<(), Vec> { - let mut active = active_turn.lock().await; - match active.as_mut() { - Some(active_turn) => { - self.extend_pending_input_for_turn_state( - active_turn.turn_state.as_ref(), - input - .into_iter() - .map(TurnInput::ResponseInputItem) - .collect(), - ) - .await; - Ok(()) - } - None => Err(input), - } - } - #[expect( clippy::await_holding_invalid_type, reason = "active turn checks and turn state updates must remain atomic" @@ -235,7 +193,7 @@ impl InputQueue { .drain_mailbox_input_items() .await .into_iter() - .map(TurnInput::ResponseInputItem); + .map(TurnInput::ResponseItem); if pending_input.is_empty() { mailbox_items.collect() } else { @@ -345,8 +303,8 @@ mod tests { assert_eq!( input_queue.drain_mailbox_input_items().await, vec![ - mail_one.to_response_input_item(), - mail_two.to_response_input_item() + ResponseItem::from(mail_one.to_response_input_item()), + ResponseItem::from(mail_two.to_response_input_item()) ] ); assert!(!input_queue.has_pending_mailbox_items().await); diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 245047c925..8c535cd728 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -196,6 +196,7 @@ use codex_protocol::exec_output::StreamOutput; mod config_lock; mod handlers; +mod inject; mod input_queue; mod mcp; mod multi_agents; @@ -324,7 +325,6 @@ use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; use codex_protocol::config_types::WindowsSandboxLevel; -use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; @@ -549,37 +549,9 @@ impl Codex { .or_else(|| conversation_history.get_base_instructions().map(|s| s.text)) .unwrap_or_else(|| model_info.get_model_instructions(config.personality)); - // Respect thread-start tools. When missing (resumed/forked threads), read from the db - // first, then fall back to rollout-file tools. - let persisted_tools = if dynamic_tools.is_empty() { - let thread_id = match &conversation_history { - InitialHistory::Resumed(resumed) => Some(resumed.conversation_id), - InitialHistory::Forked(_) => conversation_history.forked_from_id(), - InitialHistory::New | InitialHistory::Cleared => None, - }; - match thread_id { - Some(thread_id) => { - let state_db_ctx = if config.ephemeral { - None - } else if let Some(local_store) = - thread_store.as_any().downcast_ref::() - { - local_store.state_db().await - } else { - None - }; - state_db::get_dynamic_tools(state_db_ctx.as_deref(), thread_id, "codex_spawn") - .await - } - None => None, - } - } else { - None - }; + // Dynamic tools are defined at thread start and persisted in rollout session metadata. let dynamic_tools = if dynamic_tools.is_empty() { - persisted_tools - .or_else(|| conversation_history.get_dynamic_tools()) - .unwrap_or_default() + conversation_history.get_dynamic_tools().unwrap_or_default() } else { dynamic_tools }; @@ -695,6 +667,25 @@ impl Codex { let sub = Submission { id: id.clone(), op, + client_user_message_id: None, + trace, + }; + self.submit_with_id(sub).await?; + Ok(id) + } + + pub async fn submit_user_input_with_client_user_message_id( + &self, + op: Op, + trace: Option, + client_user_message_id: Option, + ) -> CodexResult { + debug_assert!(matches!(op, Op::UserInput { .. })); + let id = Uuid::now_v7().to_string(); + let sub = Submission { + id: id.clone(), + op, + client_user_message_id, trace, }; self.submit_with_id(sub).await?; @@ -750,6 +741,7 @@ impl Codex { input: Vec, additional_context: BTreeMap, expected_turn_id: Option<&str>, + client_user_message_id: Option, responsesapi_client_metadata: Option>, ) -> Result { self.session @@ -757,6 +749,7 @@ impl Codex { input, additional_context, expected_turn_id, + client_user_message_id, responsesapi_client_metadata, ) .await @@ -1102,6 +1095,7 @@ impl Session { thread_settings: Default::default(), }, /*mirror_user_text_to_realtime*/ None, + /*client_user_message_id*/ None, ) .await; } @@ -1870,27 +1864,11 @@ impl Session { warn!("execpolicy amendment for {sub_id} had no command prefix"); return; }; - let fragment = ApprovedCommandPrefixSaved::new(prefixes); - let text = fragment.render(); - let message: ResponseItem = ContextualUserFragment::into(fragment); - - if let Some(turn_context) = self.turn_context_for_sub_id(sub_id).await { - self.record_conversation_items(&turn_context, std::slice::from_ref(&message)) - .await; - return; - } - - if self - .inject_response_items(vec![ResponseInputItem::Message { - role: "developer".to_string(), - content: vec![ContentItem::InputText { text }], - phase: None, - }]) - .await - .is_err() - { - warn!("no active turn found to record execpolicy amendment message for {sub_id}"); - } + let message: ResponseItem = + ContextualUserFragment::into(ApprovedCommandPrefixSaved::new(prefixes)); + let turn_context = self.turn_context_for_sub_id(sub_id).await; + self.inject_no_new_turn(vec![message], turn_context.as_deref()) + .await; } pub(crate) async fn persist_network_policy_amendment( @@ -1967,27 +1945,10 @@ impl Session { sub_id: &str, amendment: &NetworkPolicyAmendment, ) { - let fragment = NetworkRuleSaved::new(amendment); - let text = fragment.render(); - let message: ResponseItem = ContextualUserFragment::into(fragment); - - if let Some(turn_context) = self.turn_context_for_sub_id(sub_id).await { - self.record_conversation_items(&turn_context, std::slice::from_ref(&message)) - .await; - return; - } - - if self - .inject_response_items(vec![ResponseInputItem::Message { - role: "developer".to_string(), - content: vec![ContentItem::InputText { text }], - phase: None, - }]) - .await - .is_err() - { - warn!("no active turn found to record network policy amendment message for {sub_id}"); - } + let message: ResponseItem = ContextualUserFragment::into(NetworkRuleSaved::new(amendment)); + let turn_context = self.turn_context_for_sub_id(sub_id).await; + self.inject_no_new_turn(vec![message], turn_context.as_deref()) + .await; } /// Emit an exec approval request event and await the user's decision. @@ -2538,28 +2499,21 @@ impl Session { } } - /// Records input items: always append to conversation history and - /// persist these response items to rollout. + /// Records conversation items: append to history, persist to rollout, and + /// notify clients observing raw response items. pub(crate) async fn record_conversation_items( &self, turn_context: &TurnContext, items: &[ResponseItem], ) { - self.record_into_history(items, turn_context).await; + { + let mut state = self.state.lock().await; + state.record_items(items.iter(), turn_context.truncation_policy); + } self.persist_rollout_response_items(items).await; self.send_raw_response_items(turn_context, items).await; } - /// Append ResponseItems to the in-memory conversation history only. - pub(crate) async fn record_into_history( - &self, - items: &[ResponseItem], - turn_context: &TurnContext, - ) { - let mut state = self.state.lock().await; - state.record_items(items.iter(), turn_context.truncation_policy); - } - async fn maybe_warn_on_server_model_mismatch( self: &Arc, turn_context: &Arc, @@ -3124,6 +3078,7 @@ impl Session { &self, turn_context: &TurnContext, input: &[UserInput], + client_id: Option, ) { // Persist the user message to history, but emit the turn item from `UserInput` so // UI-only `text_elements` are preserved. `ResponseItem::Message` does not carry @@ -3131,7 +3086,9 @@ impl Session { let response_item = ResponseItem::from(ResponseInputItem::from(input.to_vec())); self.record_conversation_items(turn_context, std::slice::from_ref(&response_item)) .await; - let turn_item = TurnItem::UserMessage(UserMessageItem::new(input)); + let mut user_message_item = UserMessageItem::new(input); + user_message_item.client_id = client_id; + let turn_item = TurnItem::UserMessage(user_message_item); self.emit_turn_item_started(turn_context, &turn_item).await; self.emit_turn_item_completed(turn_context, turn_item).await; self.ensure_rollout_materialized().await; @@ -3167,6 +3124,7 @@ impl Session { input: Vec, additional_context: BTreeMap, expected_turn_id: Option<&str>, + client_user_message_id: Option, responsesapi_client_metadata: Option>, ) -> Result { let mut active = self.active_turn.lock().await; @@ -3220,9 +3178,13 @@ impl Session { let mut pending_input = additional_context_input .into_iter() - .map(TurnInput::ResponseInputItem) + .map(ResponseItem::from) + .map(TurnInput::ResponseItem) .collect::>(); - pending_input.push(TurnInput::UserInput(input)); + pending_input.push(TurnInput::UserInput { + content: input, + client_id: client_user_message_id, + }); self.input_queue .extend_pending_input_and_accept_mailbox_delivery_for_turn_state( active_turn.turn_state.as_ref(), @@ -3232,16 +3194,6 @@ impl Session { Ok(active_turn_id.clone()) } - /// Returns the input if there was no task running to inject into. - pub async fn inject_response_items( - &self, - input: Vec, - ) -> Result<(), Vec> { - self.input_queue - .inject_response_items(&self.active_turn, input) - .await - } - pub(crate) async fn record_memory_citation_for_turn(&self, sub_id: &str) { let turn_state = self .input_queue diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs index 762ebc1458..bbb51a1821 100644 --- a/codex-rs/core/src/session/review.rs +++ b/codex-rs/core/src/session/review.rs @@ -1,4 +1,5 @@ use super::*; +use codex_protocol::openai_models::ToolMode; use std::sync::atomic::AtomicBool; /// Spawn a review thread using the given prompt. @@ -47,6 +48,15 @@ pub(super) async fn spawn_review_thread( let mut per_turn_config = (*config).clone(); per_turn_config.model = Some(model.clone()); per_turn_config.features = review_features.clone(); + let tool_mode = model_info.tool_mode.unwrap_or_else(|| { + if per_turn_config.features.enabled(Feature::CodeModeOnly) { + ToolMode::CodeModeOnly + } else if per_turn_config.features.enabled(Feature::CodeMode) { + ToolMode::CodeMode + } else { + ToolMode::Direct + } + }); if let Err(err) = per_turn_config.web_search_mode.set(review_web_search_mode) { let fallback_value = per_turn_config.web_search_mode.value(); tracing::warn!( @@ -96,6 +106,7 @@ pub(super) async fn spawn_review_thread( config: per_turn_config, auth_manager: auth_manager_for_context, model_info: model_info.clone(), + tool_mode, session_telemetry: session_telemetry_for_context, provider: provider_for_context, reasoning_effort, @@ -137,11 +148,14 @@ pub(super) async fn spawn_review_thread( }; // Seed the child task with the review prompt as the initial user message. - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: review_prompt, - // Review prompt is synthesized; no UI element ranges to preserve. - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: review_prompt, + // Review prompt is synthesized; no UI element ranges to preserve. + text_elements: Vec::new(), + }], + client_id: None, + }]; let tc = Arc::new(review_turn_context); tc.turn_metadata_state.spawn_git_enrichment_task(); // TODO(ccunningham): Review turns currently rely on `spawn_task` for TurnComplete but do not diff --git a/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/codex-rs/core/src/session/rollout_reconstruction_tests.rs index 11b8651ae6..05be3e8967 100644 --- a/codex-rs/core/src/session/rollout_reconstruction_tests.rs +++ b/codex-rs/core/src/session/rollout_reconstruction_tests.rs @@ -61,6 +61,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -98,6 +99,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -130,6 +132,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -198,6 +201,7 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_com )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -228,6 +232,7 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_com )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -300,6 +305,7 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_inc )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -330,6 +336,7 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_inc )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -394,6 +401,7 @@ async fn reconstruct_history_rollback_skips_non_user_turns_for_history_and_metad )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -424,6 +432,7 @@ async fn reconstruct_history_rollback_skips_non_user_turns_for_history_and_metad )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -517,6 +526,7 @@ async fn reconstruct_history_rollback_counts_inter_agent_assistant_turns() { )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -608,6 +618,7 @@ async fn reconstruct_history_rollback_clears_history_and_metadata_when_exceeding )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "only user".to_string(), images: None, local_images: Vec::new(), @@ -662,6 +673,7 @@ async fn record_initial_history_resumed_rollback_skips_only_user_turns() { )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -737,6 +749,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -765,6 +778,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "rolled back".to_string(), images: None, local_images: Vec::new(), @@ -898,6 +912,7 @@ async fn reconstruct_history_legacy_compaction_without_replacement_history_clear )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "after legacy compact".to_string(), images: None, local_images: Vec::new(), @@ -933,6 +948,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -963,6 +979,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -1009,6 +1026,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1036,6 +1054,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1068,6 +1087,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -1096,6 +1116,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "aborted".to_string(), images: None, local_images: Vec::new(), @@ -1151,6 +1172,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo turn_id: Some(current_turn_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1178,6 +1200,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -1206,6 +1229,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "current".to_string(), images: None, local_images: Vec::new(), @@ -1265,6 +1289,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1297,6 +1322,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -1325,6 +1351,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "incomplete".to_string(), images: None, local_images: Vec::new(), @@ -1377,6 +1404,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_ )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "incomplete".to_string(), images: None, local_images: Vec::new(), @@ -1419,6 +1447,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -1452,6 +1481,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: Vec::new(), @@ -1480,6 +1510,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "compacted".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 0823e93666..c9e1807fe6 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -966,6 +966,8 @@ impl Session { for contributor in extensions.thread_lifecycle_contributors() { contributor.on_thread_start(codex_extension_api::ThreadStartInput { config: config.as_ref(), + session_source: &session_configuration.session_source, + persistent_thread_state_available: state_db_ctx.is_some(), session_store: &session_extension_data, thread_store: &thread_extension_data, }).await; @@ -1034,6 +1036,12 @@ impl Session { config.features.enabled(Feature::RuntimeMetrics), Self::build_model_client_beta_features_header(config.as_ref()), attestation_provider, + ) + .with_prompt_cache_key_override( + crate::guardian::prompt_cache_key_override_for_review_session( + &session_configuration.session_source, + session_configuration.forked_from_thread_id, + ), ), code_mode_service: crate::tools::code_mode::CodeModeService::new(), environment_manager, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index f8bc8ae4e4..aa2586cae4 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -103,9 +103,9 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; use codex_protocol::models::BaseInstructions; use codex_protocol::models::ContentItem; -use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::CompactedItem; use codex_protocol::protocol::ConversationAudioParams; use codex_protocol::protocol::CreditsSnapshot; @@ -398,6 +398,12 @@ async fn interrupting_regular_turn_waiting_on_startup_prewarm_emits_turn_aborted sess.abort_all_tasks(TurnAbortReason::Interrupted).await; + let marker_evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("expected turn aborted marker event") + .expect("channel open"); + assert!(matches!(marker_evt.msg, EventMsg::RawResponseItem(_))); + let second = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) .await .expect("expected turn aborted event") @@ -1772,7 +1778,7 @@ async fn recompute_token_usage_uses_session_base_instructions() { let item = user_message("hello"); session - .record_into_history(std::slice::from_ref(&item), &turn_context) + .record_conversation_items(&turn_context, std::slice::from_ref(&item)) .await; let history = session.clone_history().await; @@ -2037,6 +2043,85 @@ async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { assert_eq!(vec![expected], actual); } +#[tokio::test] +async fn turn_error_lifecycle_exposes_error_and_stores() { + struct SessionTurnErrorMarker; + struct ThreadTurnErrorMarker; + + #[derive(Debug, PartialEq, Eq)] + struct RecordedTurnError { + session_level_id: String, + thread_level_id: String, + turn_level_id: String, + turn_id: String, + error: CodexErrorInfo, + saw_session_store: bool, + saw_thread_store: bool, + } + + struct TurnErrorRecorder { + records: Arc>>, + } + + #[async_trait::async_trait] + impl codex_extension_api::TurnLifecycleContributor for TurnErrorRecorder { + async fn on_turn_error(&self, input: codex_extension_api::TurnErrorInput<'_>) { + self.records + .lock() + .expect("turn error records lock") + .push(RecordedTurnError { + session_level_id: input.session_store.level_id().to_string(), + thread_level_id: input.thread_store.level_id().to_string(), + turn_level_id: input.turn_store.level_id().to_string(), + turn_id: input.turn_id.to_string(), + error: input.error, + saw_session_store: input + .session_store + .get::() + .is_some(), + saw_thread_store: input.thread_store.get::().is_some(), + }); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let records = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.turn_lifecycle_contributor(Arc::new(TurnErrorRecorder { + records: Arc::clone(&records), + })); + session.services.extensions = Arc::new(builder.build()); + session + .services + .session_extension_data + .insert(SessionTurnErrorMarker); + session + .services + .thread_extension_data + .insert(ThreadTurnErrorMarker); + + let expected = RecordedTurnError { + session_level_id: session.session_id().to_string(), + thread_level_id: session.conversation_id.to_string(), + turn_level_id: turn_context.sub_id.clone(), + turn_id: turn_context.sub_id.clone(), + error: CodexErrorInfo::UsageLimitExceeded, + saw_session_store: true, + saw_thread_store: true, + }; + + session + .emit_turn_error_lifecycle(&turn_context, CodexErrorInfo::UsageLimitExceeded) + .await; + + let actual = records + .lock() + .expect("turn error records lock") + .drain(..) + .collect::>(); + assert_eq!(vec![expected], actual); +} + #[tokio::test] async fn config_change_contributor_observes_effective_config_changes() { struct SessionConfigMarker; @@ -2375,6 +2460,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() { turn_id: Some(turn_context.sub_id.clone()), #[allow(deprecated)] cwd: turn_context.cwd.to_path_buf(), + workspace_roots: None, current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), approval_policy: turn_context.approval_policy.value(), @@ -2405,6 +2491,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() { )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "forked seed".to_string(), images: None, local_images: Vec::new(), @@ -2547,7 +2634,7 @@ async fn thread_rollback_fails_without_persisted_thread_history() { let (sess, tc, rx) = make_session_and_context_with_rx().await; let initial_context = sess.build_initial_context(tc.as_ref()).await; - sess.record_into_history(&initial_context, tc.as_ref()) + sess.record_conversation_items(tc.as_ref(), &initial_context) .await; handlers::thread_rollback(&sess, "sub-1".to_string(), /*num_turns*/ 1).await; @@ -2601,6 +2688,7 @@ async fn thread_rollback_recomputes_previous_turn_settings_and_reference_context )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -2629,6 +2717,7 @@ async fn thread_rollback_recomputes_previous_turn_settings_and_reference_context )), RolloutItem::EventMsg(EventMsg::UserMessage( codex_protocol::protocol::UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -2713,6 +2802,7 @@ async fn thread_rollback_restores_cleared_reference_context_item_after_compactio }, )), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -2759,6 +2849,7 @@ async fn thread_rollback_restores_cleared_reference_context_item_after_compactio }, )), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -2815,6 +2906,7 @@ async fn thread_rollback_persists_marker_and_replays_cumulatively() { }, )), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "turn 1 user".to_string(), images: None, local_images: Vec::new(), @@ -2841,6 +2933,7 @@ async fn thread_rollback_persists_marker_and_replays_cumulatively() { }, )), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "turn 2 user".to_string(), images: None, local_images: Vec::new(), @@ -2867,6 +2960,7 @@ async fn thread_rollback_persists_marker_and_replays_cumulatively() { }, )), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "turn 3 user".to_string(), images: None, local_images: Vec::new(), @@ -2920,7 +3014,7 @@ async fn thread_rollback_fails_when_turn_in_progress() { let (sess, tc, rx) = make_session_and_context_with_rx().await; let initial_context = sess.build_initial_context(tc.as_ref()).await; - sess.record_into_history(&initial_context, tc.as_ref()) + sess.record_conversation_items(tc.as_ref(), &initial_context) .await; *sess.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); @@ -2941,7 +3035,7 @@ async fn thread_rollback_fails_when_num_turns_is_zero() { let (sess, tc, rx) = make_session_and_context_with_rx().await; let initial_context = sess.build_initial_context(tc.as_ref()).await; - sess.record_into_history(&initial_context, tc.as_ref()) + sess.record_conversation_items(tc.as_ref(), &initial_context) .await; handlers::thread_rollback(&sess, "sub-1".to_string(), /*num_turns*/ 0).await; @@ -5325,6 +5419,7 @@ async fn submit_with_id_captures_current_span_trace_context() { .submit_with_id(Submission { id: "sub-1".into(), op: Op::Interrupt, + client_user_message_id: None, trace: None, }) .await @@ -5396,6 +5491,7 @@ fn submission_dispatch_span_prefers_submission_trace_context() { submission_dispatch_span(&Submission { id: "sub-1".into(), op: Op::Interrupt, + client_user_message_id: None, trace: Some(submission_trace), }) }); @@ -5422,6 +5518,7 @@ fn submission_dispatch_span_uses_debug_for_realtime_audio() { item_id: None, }, }), + client_user_message_id: None, trace: None, }); @@ -5489,6 +5586,7 @@ async fn user_turn_updates_approvals_reviewer() { ..Default::default() }, }, + /*client_user_message_id*/ None, ) .await; @@ -5782,6 +5880,7 @@ async fn spawn_task_turn_span_inherits_dispatch_trace_context() { let dispatch_span = submission_dispatch_span(&Submission { id: "sub-1".into(), op: Op::Interrupt, + client_user_message_id: None, trace: Some(submission_trace.clone()), }); let dispatch_span_id = dispatch_span.context().span().span_context().span_id(); @@ -5792,10 +5891,13 @@ async fn spawn_task_turn_span_inherits_dispatch_trace_context() { async { sess.spawn_task( Arc::clone(&tc), - vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])], + vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }], TraceCaptureTask { captured_trace: Arc::clone(&captured_trace), }, @@ -6604,10 +6706,13 @@ async fn spawn_task_does_not_update_previous_turn_settings_for_non_run_turn_task let (sess, tc, _rx) = make_session_and_context_with_rx().await; sess.set_previous_turn_settings(/*previous_turn_settings*/ None) .await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), @@ -7531,7 +7636,7 @@ async fn record_context_updates_and_set_reference_context_item_reinjects_full_co phase: None, }; session - .record_into_history(std::slice::from_ref(&compacted_summary), &turn_context) + .record_conversation_items(&turn_context, std::slice::from_ref(&compacted_summary)) .await; session .record_context_updates_and_set_reference_context_item(&turn_context) @@ -7690,6 +7795,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_full_rei session .persist_rollout_items(&[RolloutItem::EventMsg(EventMsg::UserMessage( UserMessageEvent { + client_id: None, message: "seed rollout".to_string(), images: None, local_images: Vec::new(), @@ -7809,6 +7915,29 @@ async fn realtime_conversation_list_voices_emits_builtin_list() { ); } +#[derive(Clone, Copy)] +struct CompletingTask; + +impl SessionTask for CompletingTask { + fn kind(&self) -> TaskKind { + TaskKind::Regular + } + + fn span_name(&self) -> &'static str { + "session_task.completing" + } + + async fn run( + self: Arc, + _session: Arc, + _ctx: Arc, + _input: Vec, + _cancellation_token: CancellationToken, + ) -> Option { + None + } +} + #[derive(Clone, Copy)] struct NeverEndingTask { kind: TaskKind, @@ -7873,10 +8002,13 @@ impl SessionTask for GuardianDeniedApprovalTask { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn guardian_auto_review_interrupts_after_three_consecutive_denials() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "trigger guardian denials".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "trigger guardian denials".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task(Arc::clone(&tc), input, GuardianDeniedApprovalTask) .await; @@ -7904,10 +8036,13 @@ async fn guardian_auto_review_interrupts_after_three_consecutive_denials() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn guardian_helper_review_interrupts_after_three_consecutive_denials() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "keep turn active for helper reviews".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "keep turn active for helper reviews".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -7962,12 +8097,15 @@ async fn guardian_helper_review_interrupts_after_three_consecutive_denials() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[test_log::test] -async fn abort_regular_task_emits_turn_aborted_only() { +async fn abort_regular_task_emits_marker_before_turn_aborted() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -7980,8 +8118,13 @@ async fn abort_regular_task_emits_turn_aborted_only() { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; - // Interrupts persist a model-visible `` marker into history, but there is no - // separate client-visible event for that marker (only `EventMsg::TurnAborted`). + // Interrupts surface the model-visible `` marker before the abort event. + let marker_evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("timeout waiting for marker event") + .expect("event"); + assert!(matches!(marker_evt.msg, EventMsg::RawResponseItem(_))); + let evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) .await .expect("timeout waiting for event") @@ -7995,12 +8138,15 @@ async fn abort_regular_task_emits_turn_aborted_only() { } #[tokio::test] -async fn abort_gracefully_emits_turn_aborted_only() { +async fn abort_gracefully_emits_marker_before_turn_aborted() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -8013,8 +8159,13 @@ async fn abort_gracefully_emits_turn_aborted_only() { sess.abort_all_tasks(TurnAbortReason::Interrupted).await; - // Even if tasks handle cancellation gracefully, interrupts still result in `TurnAborted` - // being the only client-visible signal. + // Gracefully cancelled tasks surface the model-visible marker before the abort event too. + let marker_evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("timeout waiting for marker event") + .expect("event"); + assert!(matches!(marker_evt.msg, EventMsg::RawResponseItem(_))); + let evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) .await .expect("timeout waiting for event") @@ -8030,10 +8181,13 @@ async fn abort_gracefully_emits_turn_aborted_only() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -8058,6 +8212,7 @@ async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() pending_user_input.clone(), /*additional_context*/ Default::default(), Some(&tc.sub_id), + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -8117,6 +8272,7 @@ async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() assert!(matches!( fourth.msg, EventMsg::UserMessage(UserMessageEvent { + client_id: None, message, images, text_elements, @@ -8143,6 +8299,86 @@ async fn task_finish_emits_turn_item_lifecycle_for_leftover_pending_user_input() )); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn task_finish_emits_thread_idle_lifecycle_after_active_turn_clears() { + struct ThreadIdleRecorder { + calls: Arc, + idle_tx: async_channel::Sender<()>, + expected_thread_id: ThreadId, + } + + #[async_trait::async_trait] + impl codex_extension_api::ThreadLifecycleContributor for ThreadIdleRecorder { + async fn on_thread_idle(&self, input: codex_extension_api::ThreadIdleInput<'_>) { + assert_eq!( + self.expected_thread_id.to_string(), + input.thread_store.level_id() + ); + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.idle_tx.send(()).await.expect("idle receiver open"); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (idle_tx, idle_rx) = async_channel::bounded(1); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.thread_lifecycle_contributor(Arc::new(ThreadIdleRecorder { + calls: Arc::clone(&calls), + idle_tx, + expected_thread_id: session.conversation_id, + })); + session.services.extensions = Arc::new(builder.build()); + + let session = Arc::new(session); + session + .spawn_task(Arc::new(turn_context), Vec::new(), CompletingTask) + .await; + + timeout(StdDuration::from_secs(2), idle_rx.recv()) + .await + .expect("thread idle lifecycle") + .expect("idle receiver open"); + assert_eq!(1, calls.load(std::sync::atomic::Ordering::SeqCst)); + assert!(session.active_turn.lock().await.is_none()); +} + +#[tokio::test] +async fn thread_idle_lifecycle_waits_for_trigger_turn_mailbox_work() { + struct ThreadIdleRecorder { + calls: Arc, + } + + #[async_trait::async_trait] + impl codex_extension_api::ThreadLifecycleContributor for ThreadIdleRecorder { + async fn on_thread_idle(&self, _input: codex_extension_api::ThreadIdleInput<'_>) { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + } + + let (mut session, _turn_context) = make_session_and_context().await; + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.thread_lifecycle_contributor(Arc::new(ThreadIdleRecorder { + calls: Arc::clone(&calls), + })); + session.services.extensions = Arc::new(builder.build()); + session + .input_queue + .enqueue_mailbox_communication(InterAgentCommunication::new( + AgentPath::root(), + AgentPath::root(), + Vec::new(), + "pending trigger".to_string(), + /*trigger_turn*/ true, + )) + .await; + + session.emit_thread_idle_lifecycle_if_idle().await; + + assert_eq!(0, calls.load(std::sync::atomic::Ordering::SeqCst)); +} + #[tokio::test] async fn steer_input_requires_active_turn() { let (sess, _tc, _rx) = make_session_and_context_with_rx().await; @@ -8156,6 +8392,7 @@ async fn steer_input_requires_active_turn() { input, /*additional_context*/ Default::default(), /*expected_turn_id*/ None, + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -8167,10 +8404,13 @@ async fn steer_input_requires_active_turn() { #[tokio::test] async fn steer_input_enforces_expected_turn_id() { let (sess, tc, _rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -8190,6 +8430,7 @@ async fn steer_input_enforces_expected_turn_id() { steer_input, /*additional_context*/ Default::default(), Some("different-turn-id"), + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -8213,10 +8454,13 @@ async fn steer_input_rejects_non_regular_turns() { (TaskKind::Compact, NonSteerableTurnKind::Compact), ] { let (sess, _tc, _rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; let turn_context = sess.new_default_turn_with_sub_id("turn".to_string()).await; sess.spawn_task( turn_context, @@ -8237,6 +8481,7 @@ async fn steer_input_rejects_non_regular_turns() { steer_input, /*additional_context*/ Default::default(), /*expected_turn_id*/ None, + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -8251,10 +8496,13 @@ async fn steer_input_rejects_non_regular_turns() { #[tokio::test] async fn steer_input_returns_active_turn_id() { let (sess, tc, _rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "hello".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "hello".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task( Arc::clone(&tc), input, @@ -8274,6 +8522,7 @@ async fn steer_input_returns_active_turn_id() { steer_input, /*additional_context*/ Default::default(), Some(&tc.sub_id), + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -8283,66 +8532,11 @@ async fn steer_input_returns_active_turn_id() { assert!(sess.input_queue.has_pending_input(&sess.active_turn).await); } -#[tokio::test] -async fn queued_response_items_for_next_turn_move_into_next_active_turn() { - let (sess, tc, _rx) = make_session_and_context_with_rx().await; - let queued_item = ResponseInputItem::Message { - role: "assistant".to_string(), - content: vec![ContentItem::InputText { - text: "queued before wake".to_string(), - }], - phase: None, - }; - - sess.input_queue - .queue_response_items_for_next_turn(vec![queued_item.clone()]) - .await; - - sess.spawn_task( - Arc::clone(&tc), - Vec::new(), - NeverEndingTask { - kind: TaskKind::Regular, - listen_to_cancellation_token: false, - }, - ) - .await; - - assert_eq!( - sess.input_queue.get_pending_input(&sess.active_turn).await, - vec![TurnInput::ResponseInputItem(queued_item)] - ); -} - -#[tokio::test] -async fn idle_interrupt_does_not_wake_queued_next_turn_items() { - let (sess, _tc, _rx) = make_session_and_context_with_rx().await; - let queued_item = ResponseInputItem::Message { - role: "assistant".to_string(), - content: vec![ContentItem::InputText { - text: "queued before interrupt".to_string(), - }], - phase: None, - }; - - sess.input_queue - .queue_response_items_for_next_turn(vec![queued_item]) - .await; - - sess.abort_all_tasks(TurnAbortReason::Interrupted).await; - - assert!(sess.active_turn.lock().await.is_none()); - assert!( - sess.input_queue - .has_queued_response_items_for_next_turn() - .await - ); -} - #[tokio::test] async fn abort_empty_active_turn_preserves_pending_input() { let (sess, _tc, _rx) = make_session_and_context_with_rx().await; - let pending_item = ResponseInputItem::Message { + let pending_item = ResponseItem::Message { + id: None, role: "user".to_string(), content: vec![ContentItem::InputText { text: "late pending input".to_string(), @@ -8357,7 +8551,7 @@ async fn abort_empty_active_turn_preserves_pending_input() { sess.input_queue .extend_pending_input_for_turn_state( turn_state.as_ref(), - vec![TurnInput::ResponseInputItem(pending_item.clone())], + vec![TurnInput::ResponseItem(pending_item.clone())], ) .await; @@ -8368,7 +8562,7 @@ async fn abort_empty_active_turn_preserves_pending_input() { sess.input_queue .take_pending_input_for_turn_state(turn_state.as_ref()) .await, - vec![TurnInput::ResponseInputItem(pending_item)] + vec![TurnInput::ResponseItem(pending_item)] ); } @@ -8516,24 +8710,13 @@ async fn active_goal_continuation_runs_again_after_no_tool_turn() -> anyhow::Res }) .await??; - let continuation_request = responses + let goal_context_text = responses .requests() .into_iter() - .find(|request| request.body_contains_text("")) - .expect("expected a goal continuation request"); - let body = continuation_request.body_json(); - let goal_context_message = body["input"] - .as_array() - .expect("input should be an array") - .iter() - .find(|item| item.to_string().contains("")) + .flat_map(|request| request.message_input_texts("user")) + .find(|text| text.contains("")) .expect("goal context message should be present"); - assert_eq!(goal_context_message["role"].as_str(), Some("user")); - assert!( - goal_context_message - .to_string() - .contains("Continue working toward the active thread goal.") - ); + assert!(goal_context_text.contains("Continue working toward the active thread goal.")); Ok(()) } @@ -8794,7 +8977,7 @@ async fn budget_limited_accounting_steers_active_turn_without_aborting() -> anyh .await?; let pending_input = sess.input_queue.get_pending_input(&sess.active_turn).await; - let [TurnInput::ResponseInputItem(ResponseInputItem::Message { role, content, .. })] = + let [TurnInput::ResponseItem(ResponseItem::Message { role, content, .. })] = pending_input.as_slice() else { panic!("expected one budget-limit steering message, got {pending_input:#?}"); @@ -8803,8 +8986,8 @@ async fn budget_limited_accounting_steers_active_turn_without_aborting() -> anyh let [ContentItem::InputText { text }] = content.as_slice() else { panic!("expected one text span in budget-limit steering message, got {content:#?}"); }; - assert!(text.starts_with("")); - assert!(text.trim_end().ends_with("")); + assert!(text.starts_with("")); + assert!(text.trim_end().ends_with("")); assert!(text.contains("budget_limited")); assert!(text.to_lowercase().contains("wrap up this turn soon")); assert!(sess.active_turn.lock().await.is_some()); @@ -9021,13 +9204,13 @@ async fn external_objective_change_steers_active_turn() -> anyhow::Result<()> { pending_input.iter().any(|item| { matches!( item, - TurnInput::ResponseInputItem(ResponseInputItem::Message { role, content, .. }) + TurnInput::ResponseItem(ResponseItem::Message { role, content, .. }) if role == "user" && content.iter().any(|content| matches!( content, ContentItem::InputText { text } - if text.starts_with("") - && text.trim_end().ends_with("") + if text.starts_with("") + && text.trim_end().ends_with("") && text.contains("The active thread goal objective was edited") && text.contains("Write a concise benchmark summary") )) @@ -9245,9 +9428,9 @@ async fn queue_only_mailbox_mail_waits_for_next_turn_after_answer_boundary() { assert_eq!( sess.input_queue.get_pending_input(&sess.active_turn).await, - vec![TurnInput::ResponseInputItem( + vec![TurnInput::ResponseItem(ResponseItem::from( communication.to_response_input_item() - )], + ))], ); } @@ -9320,6 +9503,7 @@ async fn steered_input_reopens_mailbox_delivery_for_current_turn() { }], /*additional_context*/ Default::default(), Some(&tc.sub_id), + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -9328,11 +9512,14 @@ async fn steered_input_reopens_mailbox_delivery_for_current_turn() { assert_eq!( sess.input_queue.get_pending_input(&sess.active_turn).await, vec![ - TurnInput::UserInput(vec![UserInput::Text { - text: "follow up".to_string(), - text_elements: Vec::new(), - }]), - TurnInput::ResponseInputItem(communication.to_response_input_item()), + TurnInput::UserInput { + content: vec![UserInput::Text { + text: "follow up".to_string(), + text_elements: Vec::new(), + }], + client_id: None + }, + TurnInput::ResponseItem(ResponseItem::from(communication.to_response_input_item())), ], ); } @@ -9370,6 +9557,7 @@ async fn stale_defer_mailbox_delivery_does_not_override_steered_input() { }], /*additional_context*/ Default::default(), Some(&tc.sub_id), + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await @@ -9382,11 +9570,14 @@ async fn stale_defer_mailbox_delivery_does_not_override_steered_input() { assert_eq!( sess.input_queue.get_pending_input(&sess.active_turn).await, vec![ - TurnInput::UserInput(vec![UserInput::Text { - text: "follow up".to_string(), - text_elements: Vec::new(), - }]), - TurnInput::ResponseInputItem(communication.to_response_input_item()), + TurnInput::UserInput { + content: vec![UserInput::Text { + text: "follow up".to_string(), + text_elements: Vec::new(), + }], + client_id: None + }, + TurnInput::ResponseItem(ResponseItem::from(communication.to_response_input_item())), ], ); } @@ -9441,19 +9632,22 @@ async fn tool_calls_reopen_mailbox_delivery_for_current_turn() { assert!(output.tool_future.is_some()); assert_eq!( sess.input_queue.get_pending_input(&sess.active_turn).await, - vec![TurnInput::ResponseInputItem( + vec![TurnInput::ResponseItem(ResponseItem::from( communication.to_response_input_item() - )], + ))], ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn abort_review_task_emits_exited_then_aborted_and_records_history() { let (sess, tc, rx) = make_session_and_context_with_rx().await; - let input = vec![TurnInput::UserInput(vec![UserInput::Text { - text: "start review".to_string(), - text_elements: Vec::new(), - }])]; + let input = vec![TurnInput::UserInput { + content: vec![UserInput::Text { + text: "start review".to_string(), + text_elements: Vec::new(), + }], + client_id: None, + }]; sess.spawn_task(Arc::clone(&tc), input, ReviewTask::new()) .await; @@ -9501,8 +9695,7 @@ async fn abort_review_task_emits_exited_then_aborted_and_records_history() { ); let history = sess.clone_history().await; - // The `` marker is silent in the event stream, so verify it is still - // recorded in history for the model. + // Verify the `` marker is still recorded in history for the model. assert!( history.raw_items().iter().any(|item| { let ResponseItem::Message { role, content, .. } = item else { diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index fe20b76e4d..8219c19019 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -145,7 +145,10 @@ pub(crate) async fn run_turn( // diffs/full reinjection + user input) and trigger compaction preemptively // when they would push the thread over the compaction threshold. if let Err(err) = run_pre_sampling_compact(&sess, &turn_context, &mut client_session).await { - if err.to_codex_protocol_error() == CodexErrorInfo::UsageLimitExceeded + let error = err.to_codex_protocol_error(); + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + .await; + if error == CodexErrorInfo::UsageLimitExceeded && let Err(err) = sess .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached { turn_context: turn_context.as_ref(), @@ -295,7 +298,10 @@ pub(crate) async fn run_turn( ) .await { - if err.to_codex_protocol_error() == CodexErrorInfo::UsageLimitExceeded + let error = err.to_codex_protocol_error(); + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + .await; + if error == CodexErrorInfo::UsageLimitExceeded && let Err(err) = sess .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached { turn_context: turn_context.as_ref(), @@ -374,17 +380,23 @@ pub(crate) async fn run_turn( } } + let error = CodexErrorInfo::BadRequest; + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + .await; let event = EventMsg::Error(ErrorEvent { message: "Invalid image in your last message. Please remove it and try again." .to_string(), - codex_error_info: Some(CodexErrorInfo::BadRequest), + codex_error_info: Some(error), }); sess.send_event(&turn_context, event).await; break; } Err(e) => { info!("Turn error: {e:#}"); - if e.to_codex_protocol_error() == CodexErrorInfo::UsageLimitExceeded + let error = e.to_codex_protocol_error(); + sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone()) + .await; + if error == CodexErrorInfo::UsageLimitExceeded && let Err(err) = sess .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached { turn_context: turn_context.as_ref(), @@ -417,7 +429,7 @@ async fn run_hooks_and_record_inputs( blocked_input = true; record_additional_contexts(sess, turn_context, hook_outcome.additional_contexts).await; } else { - if matches!(input_item, TurnInput::UserInput(items) if !items.is_empty()) { + if matches!(input_item, TurnInput::UserInput { content, .. } if !content.is_empty()) { accepted_user_input = true; } record_pending_input( @@ -445,8 +457,8 @@ async fn build_skills_and_plugins( let user_input = input .iter() .filter_map(|item| match item { - TurnInput::UserInput(content) => Some(content.as_slice()), - TurnInput::ResponseInputItem(_) => None, + TurnInput::UserInput { content, .. } => Some(content.as_slice()), + TurnInput::ResponseItem(_) => None, }) .flatten() .cloned() @@ -598,8 +610,8 @@ async fn track_turn_resolved_config_analytics( num_input_images: input .iter() .filter_map(|item| match item { - TurnInput::UserInput(content) => Some(content.as_slice()), - TurnInput::ResponseInputItem(_) => None, + TurnInput::UserInput { content, .. } => Some(content.as_slice()), + TurnInput::ResponseItem(_) => None, }) .flatten() .filter(|item| { diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index df1502274b..638bb91198 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -6,6 +6,7 @@ use codex_model_provider::SharedModelProvider; use codex_model_provider::create_model_provider; use codex_protocol::SessionId; use codex_protocol::models::AdditionalPermissionProfile; +use codex_protocol::openai_models::ToolMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile; @@ -55,6 +56,7 @@ pub struct TurnContext { pub config: Arc, pub(crate) auth_manager: Option>, pub(crate) model_info: ModelInfo, + pub(crate) tool_mode: ToolMode, pub(crate) session_telemetry: SessionTelemetry, pub(crate) provider: SharedModelProvider, pub(crate) reasoning_effort: Option, @@ -172,6 +174,15 @@ impl TurnContext { let model_info = models_manager .get_model_info(model.as_str(), &config.to_models_manager_config()) .await; + let tool_mode = model_info.tool_mode.unwrap_or_else(|| { + if config.features.enabled(Feature::CodeModeOnly) { + ToolMode::CodeModeOnly + } else if config.features.enabled(Feature::CodeMode) { + ToolMode::CodeMode + } else { + ToolMode::Direct + } + }); let truncation_policy = model_info.truncation_policy.into(); let supported_reasoning_levels = model_info .supported_reasoning_levels @@ -212,6 +223,7 @@ impl TurnContext { config: Arc::new(config), auth_manager: self.auth_manager.clone(), model_info: model_info.clone(), + tool_mode, session_telemetry: self .session_telemetry .clone() @@ -322,10 +334,12 @@ impl TurnContext { } pub(crate) fn to_turn_context_item(&self) -> TurnContextItem { + let workspace_roots = self.config.effective_workspace_roots(); TurnContextItem { turn_id: Some(self.sub_id.clone()), #[allow(deprecated)] cwd: self.cwd.to_path_buf(), + workspace_roots: (!workspace_roots.is_empty()).then_some(workspace_roots), current_date: self.current_date.clone(), timezone: self.timezone.clone(), approval_policy: self.approval_policy.value(), @@ -473,6 +487,15 @@ impl Session { ); let mut per_turn_config = per_turn_config; + let tool_mode = model_info.tool_mode.unwrap_or_else(|| { + if per_turn_config.features.enabled(Feature::CodeModeOnly) { + ToolMode::CodeModeOnly + } else if per_turn_config.features.enabled(Feature::CodeMode) { + ToolMode::CodeMode + } else { + ToolMode::Direct + } + }); per_turn_config.service_tier = get_service_tier( per_turn_config.service_tier, per_turn_config.features.enabled(Feature::FastMode), @@ -499,6 +522,7 @@ impl Session { config: per_turn_config.clone(), auth_manager: auth_manager_for_context, model_info: model_info.clone(), + tool_mode, session_telemetry: session_telemetry_for_context, provider: provider_for_context, reasoning_effort, diff --git a/codex-rs/core/src/stream_events_utils.rs b/codex-rs/core/src/stream_events_utils.rs index 1ee4b4b58f..bb1f5fba65 100644 --- a/codex-rs/core/src/stream_events_utils.rs +++ b/codex-rs/core/src/stream_events_utils.rs @@ -5,6 +5,7 @@ use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_extension_api::ExtensionData; use codex_protocol::config_types::ModeKind; +use codex_protocol::items::ImageGenerationItem; use codex_protocol::items::TurnItem; use codex_utils_stream_parser::strip_citations; use tokio_util::sync::CancellationToken; @@ -125,6 +126,68 @@ async fn save_image_generation_result( Ok(path) } +pub(crate) async fn persist_image_generation_item( + sess: &Session, + turn_context: &TurnContext, + image_item: &mut ImageGenerationItem, +) -> Option { + let session_id = sess.conversation_id.to_string(); + match save_image_generation_result( + &turn_context.config.codex_home, + &session_id, + &image_item.id, + &image_item.result, + ) + .await + { + Ok(path) => { + image_item.saved_path = Some(path.clone()); + Some(path) + } + Err(err) => { + let output_path = image_generation_artifact_path( + &turn_context.config.codex_home, + &session_id, + &image_item.id, + ); + let output_dir = output_path + .parent() + .unwrap_or_else(|| turn_context.config.codex_home.clone()); + tracing::warn!( + call_id = %image_item.id, + output_dir = %output_dir.display(), + "failed to save generated image: {err}" + ); + None + } + } +} + +pub(crate) async fn finalize_image_generation_item( + sess: &Session, + turn_context: &TurnContext, + image_item: &mut ImageGenerationItem, +) { + if persist_image_generation_item(sess, turn_context, image_item) + .await + .is_none() + { + return; + } + let session_id = sess.conversation_id.to_string(); + let image_output_path = + image_generation_artifact_path(&turn_context.config.codex_home, &session_id, ""); + let image_output_dir = image_output_path + .parent() + .unwrap_or_else(|| turn_context.config.codex_home.clone()); + let message: ResponseItem = ContextualUserFragment::into(ImageGenerationInstructions::new( + image_output_dir.display(), + image_output_path.display(), + )); + sess.record_conversation_items(turn_context, &[message]) + .await; +} + /// Persist a completed model response item and record any cited memory usage. pub(crate) async fn record_completed_response_item( sess: &Session, @@ -487,49 +550,7 @@ pub(crate) async fn handle_non_tool_response_item( } } if let TurnItem::ImageGeneration(image_item) = &mut turn_item { - let session_id = sess.conversation_id.to_string(); - match save_image_generation_result( - &turn_context.config.codex_home, - &session_id, - &image_item.id, - &image_item.result, - ) - .await - { - Ok(path) => { - image_item.saved_path = Some(path); - let image_output_path = image_generation_artifact_path( - &turn_context.config.codex_home, - &session_id, - "", - ); - let image_output_dir = image_output_path - .parent() - .unwrap_or_else(|| turn_context.config.codex_home.clone()); - let message: ResponseItem = - ContextualUserFragment::into(ImageGenerationInstructions::new( - image_output_dir.display(), - image_output_path.display(), - )); - sess.record_conversation_items(turn_context, &[message]) - .await; - } - Err(err) => { - let output_path = image_generation_artifact_path( - &turn_context.config.codex_home, - &session_id, - &image_item.id, - ); - let output_dir = output_path - .parent() - .unwrap_or_else(|| turn_context.config.codex_home.clone()); - tracing::warn!( - call_id = %image_item.id, - output_dir = %output_dir.display(), - "failed to save generated image: {err}" - ); - } - } + finalize_image_generation_item(sess, turn_context, image_item).await; } Some(turn_item) } diff --git a/codex-rs/core/src/tasks/lifecycle.rs b/codex-rs/core/src/tasks/lifecycle.rs index 8b934175cf..782cc8c7de 100644 --- a/codex-rs/core/src/tasks/lifecycle.rs +++ b/codex-rs/core/src/tasks/lifecycle.rs @@ -1,4 +1,5 @@ use codex_extension_api::ExtensionData; +use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; @@ -37,6 +38,23 @@ impl Session { } } + pub(crate) async fn emit_thread_idle_lifecycle_if_idle(&self) { + if self.active_turn.lock().await.is_some() + || self.input_queue.has_trigger_turn_mailbox_items().await + { + return; + } + + for contributor in self.services.extensions.thread_lifecycle_contributors() { + contributor + .on_thread_idle(codex_extension_api::ThreadIdleInput { + session_store: &self.services.session_extension_data, + thread_store: &self.services.thread_extension_data, + }) + .await; + } + } + pub(super) async fn emit_turn_abort_lifecycle( &self, reason: TurnAbortReason, @@ -53,4 +71,22 @@ impl Session { .await; } } + + pub(crate) async fn emit_turn_error_lifecycle( + &self, + turn_context: &TurnContext, + error: CodexErrorInfo, + ) { + for contributor in self.services.extensions.turn_lifecycle_contributors() { + contributor + .on_turn_error(codex_extension_api::TurnErrorInput { + turn_id: turn_context.sub_id.as_str(), + error: error.clone(), + session_store: &self.services.session_extension_data, + thread_store: &self.services.thread_extension_data, + turn_store: turn_context.extension_data.as_ref(), + }) + .await; + } + } } diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index aa161c1274..38a8a96276 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -44,7 +44,6 @@ use codex_otel::TURN_TOKEN_USAGE_METRIC; use codex_otel::TURN_TOOL_CALL_METRIC; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; @@ -347,11 +346,7 @@ impl Session { { warn!("failed to apply goal runtime turn-start event: {err}"); } - let queued_response_items = self - .input_queue - .take_queued_response_items_for_next_turn() - .await; - let mailbox_items = self.input_queue.get_pending_input(&self.active_turn).await; + let pending_items = self.input_queue.get_pending_input(&self.active_turn).await; let turn_state = { let mut active = self.active_turn.lock().await; let turn = active.get_or_insert_with(ActiveTurn::default); @@ -359,11 +354,6 @@ impl Session { Arc::clone(&turn.turn_state) }; turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start.clone(); - let mut pending_items = queued_response_items - .into_iter() - .map(TurnInput::ResponseInputItem) - .collect::>(); - pending_items.extend(mailbox_items); self.input_queue .extend_pending_input_for_turn_state(turn_state.as_ref(), pending_items) .await; @@ -452,8 +442,7 @@ impl Session { /// Starts a regular turn when the session is idle and pending work is waiting. /// - /// Pending work currently includes queued next-turn items and mailbox mail marked with - /// `trigger_turn`. + /// Pending work currently includes mailbox mail marked with `trigger_turn`. /// /// This helper generates a fresh sub-id for the synthetic turn before delegating to the /// explicit-sub-id variant. @@ -465,18 +454,13 @@ impl Session { /// Starts a regular turn with the provided sub-id when pending work should wake an idle /// session. /// - /// The turn is created only when there are queued next-turn items or mailbox mail marked with - /// `trigger_turn`, and only if the session is currently idle. + /// The turn is created only when there is mailbox mail marked with `trigger_turn`, and only + /// if the session is currently idle. pub(crate) async fn maybe_start_turn_for_pending_work_with_sub_id( self: &Arc, sub_id: String, ) { - if !self - .input_queue - .has_queued_response_items_for_next_turn() - .await - && !self.input_queue.has_trigger_turn_mailbox_items().await - { + if !self.input_queue.has_trigger_turn_mailbox_items().await { return; } @@ -809,6 +793,7 @@ impl Session { { warn!("failed to apply goal runtime maybe-continue event: {err}"); } + self.emit_thread_idle_lifecycle_if_idle().await; } async fn take_active_turn(&self) -> Option { @@ -859,10 +844,11 @@ impl Session { InterruptedTurnHistoryMarker::from_config(task.turn_context.config.as_ref()), ) { - self.record_into_history(std::slice::from_ref(&marker), task.turn_context.as_ref()) - .await; - self.persist_rollout_items(&[RolloutItem::ResponseItem(marker)]) - .await; + self.record_conversation_items( + task.turn_context.as_ref(), + std::slice::from_ref(&marker), + ) + .await; // Ensure the marker is durably visible before emitting TurnAborted: some clients // synchronously re-read the rollout on receipt of the abort event. if let Err(err) = self.flush_rollout().await { diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index ff7f38a7ea..3ed8677b3c 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -72,8 +72,8 @@ impl SessionTask for ReviewTask { let mut user_input = Vec::new(); for item in input { match item { - TurnInput::UserInput(mut content) => user_input.append(&mut content), - TurnInput::ResponseInputItem(_) => {} + TurnInput::UserInput { mut content, .. } => user_input.append(&mut content), + TurnInput::ResponseItem(_) => {} } } diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 396aecbeea..1ae72b1986 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -38,8 +38,6 @@ use super::SessionTask; use super::SessionTaskContext; use crate::session::session::Session; use codex_protocol::models::PermissionProfile; -use codex_protocol::models::ResponseInputItem; -use codex_protocol::models::ResponseItem; const USER_SHELL_TIMEOUT_MS: u64 = 60 * 60 * 1000; // 1 hour @@ -193,6 +191,7 @@ pub(crate) async fn execute_user_shell_command( capture_policy: ExecCapturePolicy::ShellTool, sandbox: SandboxType::None, windows_sandbox_policy_cwd: cwd.clone(), + windows_sandbox_workspace_roots: turn_context.config.effective_workspace_roots(), windows_sandbox_level: turn_context.windows_sandbox_level, windows_sandbox_private_desktop: turn_context .config @@ -361,30 +360,7 @@ async fn persist_user_shell_output( return; } - let response_input_item = match output_item { - ResponseItem::Message { - role, - content, - phase, - .. - } => ResponseInputItem::Message { - role, - content, - phase, - }, - _ => unreachable!("user shell command output record should always be a message"), - }; - - if let Err(items) = session - .inject_response_items(vec![response_input_item]) - .await - { - let response_items = items - .into_iter() - .map(ResponseItem::from) - .collect::>(); - session - .record_conversation_items(turn_context, &response_items) - .await; - } + session + .inject_no_new_turn(vec![output_item], Some(turn_context)) + .await; } diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index d209026b62..3eec8315b1 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -33,8 +33,6 @@ use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; -#[cfg(test)] -use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelPreset; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -1016,17 +1014,6 @@ impl ThreadManagerState { thread.submit(op).await } - #[cfg(test)] - /// Append a prebuilt message to a thread by ID outside the normal user-input path. - pub(crate) async fn append_message( - &self, - thread_id: ThreadId, - message: ResponseItem, - ) -> CodexResult { - let thread = self.get_thread(thread_id).await?; - thread.append_message(message).await - } - /// Remove a thread from the manager by ID, returning it when present. pub(crate) async fn remove_thread(&self, thread_id: &ThreadId) -> Option> { self.threads.write().await.remove(thread_id) diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index c79a6859d7..76880eeb9e 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -1124,6 +1124,7 @@ fn multi_agent_v2_interrupted_marker_uses_developer_input_message() { fn completed_legacy_event_history_is_not_mid_turn() { let completed_history = InitialHistory::Forked(vec![ RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".to_string(), images: None, text_elements: Vec::new(), @@ -1152,6 +1153,7 @@ fn mixed_response_and_legacy_user_event_history_is_mid_turn() { let mixed_history = InitialHistory::Forked(vec![ RolloutItem::ResponseItem(user_msg("hello")), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".to_string(), images: None, text_elements: Vec::new(), diff --git a/codex-rs/core/src/tools/code_mode/mod.rs b/codex-rs/core/src/tools/code_mode/mod.rs index 09d58ea8f3..ff005646c2 100644 --- a/codex-rs/core/src/tools/code_mode/mod.rs +++ b/codex-rs/core/src/tools/code_mode/mod.rs @@ -13,7 +13,7 @@ use codex_code_mode::CodeModeTurnHost; use codex_code_mode::RuntimeResponse; use codex_protocol::models::FunctionCallOutputContentItem; use codex_protocol::models::FunctionCallOutputPayload; -use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; use serde_json::Value as JsonValue; use tokio_util::sync::CancellationToken; @@ -30,7 +30,7 @@ use crate::tools::parallel::ToolCallRuntime; use crate::tools::router::ToolCall; use crate::tools::router::ToolCallSource; use crate::unified_exec::resolve_max_tokens; -use codex_features::Feature; +use codex_protocol::openai_models::ToolMode; use codex_tools::ToolName; use codex_utils_output_truncation::TruncationPolicy; use codex_utils_output_truncation::formatted_truncate_text_content_items_with_policy; @@ -91,7 +91,7 @@ impl CodeModeService { router: Arc, tracker: SharedTurnDiffTracker, ) -> Option { - if !turn.features.enabled(Feature::CodeMode) { + if !matches!(turn.tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly) { return None; } @@ -134,7 +134,7 @@ impl CodeModeTurnHost for CoreTurnHost { } self.exec .session - .inject_response_items(vec![ResponseInputItem::CustomToolCallOutput { + .inject_if_running(vec![ResponseItem::CustomToolCallOutput { call_id, name: Some(PUBLIC_TOOL_NAME.to_string()), output: FunctionCallOutputPayload::from_text(text), diff --git a/codex-rs/core/src/tools/code_mode/wait_spec.rs b/codex-rs/core/src/tools/code_mode/wait_spec.rs index d700ac53c2..72bb09084c 100644 --- a/codex-rs/core/src/tools/code_mode/wait_spec.rs +++ b/codex-rs/core/src/tools/code_mode/wait_spec.rs @@ -12,20 +12,19 @@ pub(crate) fn create_wait_tool() -> ToolSpec { ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for more output before yielding again." - .to_string(), + "Wait before yielding more output. Defaults to 10000 ms.".to_string(), )), ), ( "max_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of output tokens to return for this wait call.".to_string(), + "Output token budget for this wait call. Defaults to 10000 tokens.".to_string(), )), ), ( "terminate".to_string(), JsonSchema::boolean(Some( - "Whether to terminate the running exec cell.".to_string(), + "True stops the running exec cell; false or omitted waits for output.".to_string(), )), ), ]); @@ -77,20 +76,21 @@ mod tests { ( "max_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of output tokens to return for this wait call." + "Output token budget for this wait call. Defaults to 10000 tokens." .to_string(), )), ), ( "terminate".to_string(), JsonSchema::boolean(Some( - "Whether to terminate the running exec cell.".to_string(), + "True stops the running exec cell; false or omitted waits for output." + .to_string(), )), ), ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for more output before yielding again." + "Wait before yielding more output. Defaults to 10000 ms." .to_string(), )), ), diff --git a/codex-rs/core/src/tools/handlers/agent_jobs_spec.rs b/codex-rs/core/src/tools/handlers/agent_jobs_spec.rs index 67c756af7d..437549a929 100644 --- a/codex-rs/core/src/tools/handlers/agent_jobs_spec.rs +++ b/codex-rs/core/src/tools/handlers/agent_jobs_spec.rs @@ -4,6 +4,14 @@ use codex_tools::ToolSpec; use std::collections::BTreeMap; pub fn create_spawn_agents_on_csv_tool() -> ToolSpec { + let mut output_schema = JsonSchema::object( + BTreeMap::new(), + /*required*/ None, + /*additional_properties*/ None, + ); + output_schema.description = + Some("JSON Schema for each worker result. Omit to accept any result object.".to_string()); + let properties = BTreeMap::from([ ( "csv_path".to_string(), @@ -19,12 +27,15 @@ pub fn create_spawn_agents_on_csv_tool() -> ToolSpec { ( "id_column".to_string(), JsonSchema::string(Some( - "Optional column name to use as stable item id.".to_string(), + "CSV column to use as stable item id. Omit to use row numbers.".to_string(), )), ), ( "output_csv_path".to_string(), - JsonSchema::string(Some("Optional output CSV path for exported results.".to_string())), + JsonSchema::string(Some( + "Output CSV path for exported results. Omit to create one next to the input CSV." + .to_string(), + )), ), ( "max_concurrency".to_string(), @@ -36,20 +47,17 @@ pub fn create_spawn_agents_on_csv_tool() -> ToolSpec { ( "max_workers".to_string(), JsonSchema::number(Some( - "Alias for max_concurrency. Set to 1 to run sequentially.".to_string(), + "Alias for max_concurrency. Defaults to 16 and is capped by config.".to_string(), )), ), ( "max_runtime_seconds".to_string(), JsonSchema::number(Some( - "Maximum runtime per worker before it is failed. Defaults to 1800 seconds." + "Maximum runtime per worker before failure. Defaults to 1800 seconds; config may set a different default." .to_string(), )), ), - ( - "output_schema".to_string(), - JsonSchema::object(BTreeMap::new(), /*required*/ None, /*additional_properties*/ None), - ), + ("output_schema".to_string(), output_schema), ]); ToolSpec::Function(ResponsesApiTool { @@ -64,6 +72,13 @@ pub fn create_spawn_agents_on_csv_tool() -> ToolSpec { } pub fn create_report_agent_job_result_tool() -> ToolSpec { + let mut result_schema = JsonSchema::object( + BTreeMap::new(), + /*required*/ None, + /*additional_properties*/ None, + ); + result_schema.description = Some("Result object for this job item.".to_string()); + let properties = BTreeMap::from([ ( "job_id".to_string(), @@ -73,14 +88,11 @@ pub fn create_report_agent_job_result_tool() -> ToolSpec { "item_id".to_string(), JsonSchema::string(Some("Identifier of the job item.".to_string())), ), - ( - "result".to_string(), - JsonSchema::object(BTreeMap::new(), /*required*/ None, /*additional_properties*/ None), - ), + ("result".to_string(), result_schema), ( "stop".to_string(), JsonSchema::boolean(Some( - "Optional. When true, cancels the remaining job items after this result is recorded." + "True cancels remaining job items after this result is recorded; false or omitted continues the job." .to_string(), )), ), diff --git a/codex-rs/core/src/tools/handlers/agent_jobs_spec_tests.rs b/codex-rs/core/src/tools/handlers/agent_jobs_spec_tests.rs index 92caec4dbe..b087094095 100644 --- a/codex-rs/core/src/tools/handlers/agent_jobs_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/agent_jobs_spec_tests.rs @@ -3,6 +3,16 @@ use codex_tools::JsonSchema; use pretty_assertions::assert_eq; use std::collections::BTreeMap; +fn described_object(description: &str) -> JsonSchema { + let mut schema = JsonSchema::object( + BTreeMap::new(), + /*required*/ None, + /*additional_properties*/ None, + ); + schema.description = Some(description.to_string()); + schema +} + #[test] fn spawn_agents_on_csv_tool_requires_csv_and_instruction() { assert_eq!( @@ -30,13 +40,15 @@ fn spawn_agents_on_csv_tool_requires_csv_and_instruction() { ( "id_column".to_string(), JsonSchema::string(Some( - "Optional column name to use as stable item id.".to_string(), + "CSV column to use as stable item id. Omit to use row numbers." + .to_string(), )), ), ( "output_csv_path".to_string(), JsonSchema::string(Some( - "Optional output CSV path for exported results.".to_string(), + "Output CSV path for exported results. Omit to create one next to the input CSV." + .to_string(), )), ), ( @@ -49,22 +61,21 @@ fn spawn_agents_on_csv_tool_requires_csv_and_instruction() { ( "max_workers".to_string(), JsonSchema::number(Some( - "Alias for max_concurrency. Set to 1 to run sequentially.".to_string(), + "Alias for max_concurrency. Defaults to 16 and is capped by config." + .to_string(), )), ), ( "max_runtime_seconds".to_string(), JsonSchema::number(Some( - "Maximum runtime per worker before it is failed. Defaults to 1800 seconds." + "Maximum runtime per worker before failure. Defaults to 1800 seconds; config may set a different default." .to_string(), )), ), ( "output_schema".to_string(), - JsonSchema::object( - BTreeMap::new(), - /*required*/ None, - /*additional_properties*/ None, + described_object( + "JSON Schema for each worker result. Omit to accept any result object.", ), ), ]), Some(vec!["csv_path".to_string(), "instruction".to_string()]), Some(false.into())), @@ -95,16 +106,12 @@ fn report_agent_job_result_tool_requires_result_payload() { ), ( "result".to_string(), - JsonSchema::object( - BTreeMap::new(), - /*required*/ None, - /*additional_properties*/ None, - ), + described_object("Result object for this job item."), ), ( "stop".to_string(), JsonSchema::boolean(Some( - "Optional. When true, cancels the remaining job items after this result is recorded." + "True cancels remaining job items after this result is recorded; false or omitted continues the job." .to_string(), )), ), diff --git a/codex-rs/core/src/tools/handlers/extension_tools.rs b/codex-rs/core/src/tools/handlers/extension_tools.rs index 8c9f55c460..8a8854c147 100644 --- a/codex-rs/core/src/tools/handlers/extension_tools.rs +++ b/codex-rs/core/src/tools/handlers/extension_tools.rs @@ -1,11 +1,22 @@ use std::sync::Arc; +use std::sync::Weak; +use codex_protocol::items::TurnItem; use codex_tools::ConversationHistory; +use codex_tools::ExtensionTurnItem; +use codex_tools::ImageGenerationCompletionFuture; use codex_tools::ToolCall as ExtensionToolCall; use codex_tools::ToolName; use codex_tools::ToolSpec; +use codex_tools::TurnItemEmissionFuture; +use codex_tools::TurnItemEmitter; +use crate::context::ContextualUserFragment; +use crate::context::ImageGenerationInstructions; use crate::function_tool::FunctionCallError; +use crate::session::session::Session; +use crate::session::turn_context::TurnContext; +use crate::stream_events_utils::persist_image_generation_item; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; @@ -52,6 +63,83 @@ impl CoreToolRuntime for ExtensionToolAdapter { } } +struct CoreTurnItemEmitter { + session: Weak, + turn: Weak, +} + +fn extension_turn_item(item: ExtensionTurnItem) -> TurnItem { + match item { + ExtensionTurnItem::WebSearch(item) => TurnItem::WebSearch(item), + } +} + +impl TurnItemEmitter for CoreTurnItemEmitter { + fn emit_started<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> { + Box::pin(async move { + let (Some(session), Some(turn)) = (self.session.upgrade(), self.turn.upgrade()) else { + return; + }; + let item = extension_turn_item(item); + session.emit_turn_item_started(turn.as_ref(), &item).await; + }) + } + + fn emit_completed<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> { + Box::pin(async move { + let (Some(session), Some(turn)) = (self.session.upgrade(), self.turn.upgrade()) else { + return; + }; + let item = extension_turn_item(item); + session.emit_turn_item_completed(turn.as_ref(), item).await; + }) + } + + fn image_generation_completed<'a>( + &'a self, + call_id: String, + prompt: String, + result: String, + ) -> ImageGenerationCompletionFuture<'a> { + Box::pin(async move { + let (Some(session), Some(turn)) = (self.session.upgrade(), self.turn.upgrade()) else { + return None; + }; + let mut item = codex_protocol::items::ImageGenerationItem { + id: call_id, + status: "completed".to_string(), + revised_prompt: Some(prompt), + result, + saved_path: None, + }; + let output_hint = + persist_image_generation_item(session.as_ref(), turn.as_ref(), &mut item) + .await + .map(|saved_path| { + let output_dir = saved_path + .parent() + .unwrap_or_else(|| turn.config.codex_home.clone()); + ImageGenerationInstructions::new(output_dir.display(), saved_path.display()) + .body() + }); + let started_item = codex_protocol::items::ImageGenerationItem { + id: item.id.clone(), + status: "in_progress".to_string(), + revised_prompt: None, + result: String::new(), + saved_path: None, + }; + session + .emit_turn_item_started(turn.as_ref(), &TurnItem::ImageGeneration(started_item)) + .await; + session + .emit_turn_item_completed(turn.as_ref(), TurnItem::ImageGeneration(item)) + .await; + output_hint + }) + } +} + async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall { let conversation_history = ConversationHistory::new(invocation.session.clone_history().await.into_raw_items()); @@ -61,6 +149,10 @@ async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall { tool_name: invocation.tool_name.clone(), truncation_policy: invocation.turn.truncation_policy, conversation_history, + turn_item_emitter: Arc::new(CoreTurnItemEmitter { + session: Arc::downgrade(&invocation.session), + turn: Arc::downgrade(&invocation.turn), + }), payload: invocation.payload.clone(), } } @@ -69,8 +161,13 @@ async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall { mod tests { use std::sync::Arc; + use codex_protocol::items::TurnItem; + use codex_protocol::items::WebSearchItem; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; + use codex_protocol::models::WebSearchAction; + use codex_protocol::protocol::EventMsg; + use codex_tools::ExtensionTurnItem; use pretty_assertions::assert_eq; use serde_json::json; use tokio::sync::Mutex; @@ -147,6 +244,16 @@ mod tests { &self, call: codex_tools::ToolCall, ) -> Result, codex_tools::FunctionCallError> { + let item = ExtensionTurnItem::WebSearch(WebSearchItem { + id: call.call_id.clone(), + query: "rust trait object".to_string(), + action: WebSearchAction::Search { + query: Some("rust trait object".to_string()), + queries: None, + }, + }); + call.turn_item_emitter.emit_started(item.clone()).await; + call.turn_item_emitter.emit_completed(item).await; *self.captured_call.lock().await = Some(call); Ok(Box::new(codex_tools::JsonToolOutput::new( json!({ "ok": true }), @@ -191,12 +298,14 @@ mod tests { } #[tokio::test] - async fn passes_turn_fields_to_extension_call() { + async fn passes_turn_fields_and_scoped_turn_item_emitter_to_extension_call() { let captured_call = Arc::new(Mutex::new(None)); let handler = ExtensionToolAdapter::new(Arc::new(CapturingExtensionExecutor { captured_call: Arc::clone(&captured_call), })); - let (session, turn) = crate::session::tests::make_session_and_context().await; + let (session, turn, rx) = crate::session::tests::make_session_and_context_with_rx().await; + let weak_session = Arc::downgrade(&session); + let weak_turn = Arc::downgrade(&turn); let turn_id = turn.sub_id.clone(); let truncation_policy = turn.truncation_policy; let history_item = ResponseItem::Message { @@ -208,11 +317,16 @@ mod tests { phase: None, }; session - .record_into_history(std::slice::from_ref(&history_item), &turn) + .record_conversation_items(&turn, std::slice::from_ref(&history_item)) .await; + let raw_history_event = rx.recv().await.expect("history raw response item event"); + let EventMsg::RawResponseItem(raw_history_item) = raw_history_event.msg else { + panic!("expected raw response item event"); + }; + assert_eq!(raw_history_item.item, history_item); let invocation = ToolInvocation { - session: session.into(), - turn: turn.into(), + session, + turn, cancellation_token: tokio_util::sync::CancellationToken::new(), tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())), call_id: "call-extension".to_string(), @@ -228,6 +342,8 @@ mod tests { .expect("extension call should succeed"); let captured_call = captured_call.lock().await.clone().expect("captured call"); + assert!(weak_session.upgrade().is_none()); + assert!(weak_turn.upgrade().is_none()); assert_eq!(captured_call.turn_id, turn_id); assert_eq!(captured_call.call_id, "call-extension"); assert_eq!( @@ -245,5 +361,169 @@ mod tests { } payload => panic!("expected function payload, got {payload:?}"), } + + let started = rx.recv().await.expect("item started event"); + let EventMsg::ItemStarted(started) = started.msg else { + panic!("expected item started event"); + }; + let TurnItem::WebSearch(started_item) = started.item else { + panic!("expected web search item"); + }; + let begin = rx.recv().await.expect("legacy web search begin event"); + let EventMsg::WebSearchBegin(begin) = begin.msg else { + panic!("expected legacy web search begin event"); + }; + let completed = rx.recv().await.expect("item completed event"); + let EventMsg::ItemCompleted(completed) = completed.msg else { + panic!("expected item completed event"); + }; + let TurnItem::WebSearch(completed_item) = completed.item else { + panic!("expected web search item"); + }; + let end = rx.recv().await.expect("legacy web search end event"); + let EventMsg::WebSearchEnd(end) = end.msg else { + panic!("expected legacy web search end event"); + }; + + let expected = WebSearchItem { + id: "call-extension".to_string(), + query: "rust trait object".to_string(), + action: WebSearchAction::Search { + query: Some("rust trait object".to_string()), + queries: None, + }, + }; + assert_eq!(started_item, expected); + assert_eq!(completed_item, expected); + assert_eq!(begin.call_id, expected.id); + assert_eq!(end.call_id, expected.id); + assert_eq!(end.query, expected.query); + assert_eq!(end.action, expected.action); + } + + struct ImageGenerationExtensionExecutor { + output_hint: Arc>>, + } + + #[async_trait::async_trait] + impl codex_extension_api::ToolExecutor for ImageGenerationExtensionExecutor { + fn tool_name(&self) -> codex_tools::ToolName { + codex_tools::ToolName::namespaced("image_gen", "imagegen") + } + + fn spec(&self) -> codex_tools::ToolSpec { + codex_tools::ToolSpec::Function(codex_tools::ResponsesApiTool { + name: "imagegen".to_string(), + description: "Generates an image.".to_string(), + strict: false, + parameters: codex_tools::JsonSchema::default(), + output_schema: None, + defer_loading: None, + }) + } + + async fn handle( + &self, + call: codex_tools::ToolCall, + ) -> Result, codex_tools::FunctionCallError> { + let output_hint = call + .turn_item_emitter + .image_generation_completed( + call.call_id, + "A tiny blue square".to_string(), + "cG5n".to_string(), + ) + .await; + *self.output_hint.lock().await = output_hint; + Ok(Box::new(codex_tools::JsonToolOutput::new( + json!({ "ok": true }), + ))) + } + } + + #[tokio::test] + async fn image_generation_publication_is_finalized_by_core() { + let output_hint = Arc::new(Mutex::new(None)); + let handler = ExtensionToolAdapter::new(Arc::new(ImageGenerationExtensionExecutor { + output_hint: Arc::clone(&output_hint), + })); + let (session, turn, rx) = crate::session::tests::make_session_and_context_with_rx().await; + let expected_path = crate::stream_events_utils::image_generation_artifact_path( + &turn.config.codex_home, + &session.conversation_id.to_string(), + "call-image", + ); + let invocation = ToolInvocation { + session, + turn, + cancellation_token: tokio_util::sync::CancellationToken::new(), + tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())), + call_id: "call-image".to_string(), + tool_name: codex_tools::ToolName::namespaced("image_gen", "imagegen"), + source: ToolCallSource::Direct, + payload: ToolPayload::Function { + arguments: "{}".to_string(), + }, + }; + + crate::tools::registry::ToolExecutor::handle(&handler, invocation) + .await + .expect("extension call should succeed"); + + let started = rx.recv().await.expect("item started event"); + let EventMsg::ItemStarted(started) = started.msg else { + panic!("expected item started event"); + }; + let TurnItem::ImageGeneration(started_item) = started.item else { + panic!("expected image generation item"); + }; + let begin = rx.recv().await.expect("legacy image start event"); + assert!(matches!(begin.msg, EventMsg::ImageGenerationBegin(_))); + let completed = rx.recv().await.expect("item completed event"); + let EventMsg::ItemCompleted(completed) = completed.msg else { + panic!("expected item completed event"); + }; + let TurnItem::ImageGeneration(completed_item) = completed.item else { + panic!("expected image generation item"); + }; + let end = rx.recv().await.expect("legacy image end event"); + assert!(matches!(end.msg, EventMsg::ImageGenerationEnd(_))); + + assert_eq!( + started_item, + codex_protocol::items::ImageGenerationItem { + id: "call-image".to_string(), + status: "in_progress".to_string(), + revised_prompt: None, + result: String::new(), + saved_path: None, + } + ); + assert_eq!( + completed_item, + codex_protocol::items::ImageGenerationItem { + id: "call-image".to_string(), + status: "completed".to_string(), + revised_prompt: Some("A tiny blue square".to_string()), + result: "cG5n".to_string(), + saved_path: Some(expected_path.clone()), + } + ); + assert_eq!( + std::fs::read(&expected_path).expect("generated artifact should be saved"), + b"png" + ); + assert_eq!( + *output_hint.lock().await, + Some(format!( + "Generated images are saved to {} as {} by default.\n\ + If you need to use a generated image at another path, copy it and leave the original in place unless the user explicitly asks you to delete it.", + expected_path + .parent() + .expect("generated image path should have a parent") + .display(), + expected_path.display(), + )) + ); } } diff --git a/codex-rs/core/src/tools/handlers/goal_spec.rs b/codex-rs/core/src/tools/handlers/goal_spec.rs index a3ae8703ce..da8e23d305 100644 --- a/codex-rs/core/src/tools/handlers/goal_spec.rs +++ b/codex-rs/core/src/tools/handlers/goal_spec.rs @@ -37,7 +37,8 @@ pub fn create_create_goal_tool() -> ToolSpec { ( "token_budget".to_string(), JsonSchema::integer(Some( - "Optional positive token budget for the new active goal.".to_string(), + "Positive token budget for the new goal. Omit unless explicitly requested." + .to_string(), )), ), ]); diff --git a/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs b/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs index 28ccd66367..526fb990c3 100644 --- a/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs +++ b/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs @@ -8,14 +8,13 @@ pub fn create_list_mcp_resources_tool() -> ToolSpec { ( "server".to_string(), JsonSchema::string(Some( - "Optional MCP server name. When omitted, lists resources from every configured server." - .to_string(), + "MCP server name. Omit to list resources from every configured server.".to_string(), )), ), ( "cursor".to_string(), JsonSchema::string(Some( - "Opaque cursor returned by a previous list_mcp_resources call for the same server." + "Opaque cursor from a previous list_mcp_resources call; omit for the first page." .to_string(), )), ), @@ -36,14 +35,14 @@ pub fn create_list_mcp_resource_templates_tool() -> ToolSpec { ( "server".to_string(), JsonSchema::string(Some( - "Optional MCP server name. When omitted, lists resource templates from all configured servers." + "MCP server name. Omit to list resource templates from every configured server." .to_string(), )), ), ( "cursor".to_string(), JsonSchema::string(Some( - "Opaque cursor returned by a previous list_mcp_resource_templates call for the same server." + "Opaque cursor from a previous list_mcp_resource_templates call; omit for the first page." .to_string(), )), ), diff --git a/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs b/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs index 9af7172686..a50879d9df 100644 --- a/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs @@ -16,14 +16,14 @@ fn list_mcp_resources_tool_matches_expected_spec() { ( "server".to_string(), JsonSchema::string(Some( - "Optional MCP server name. When omitted, lists resources from every configured server." + "MCP server name. Omit to list resources from every configured server." .to_string(), ),), ), ( "cursor".to_string(), JsonSchema::string(Some( - "Opaque cursor returned by a previous list_mcp_resources call for the same server." + "Opaque cursor from a previous list_mcp_resources call; omit for the first page." .to_string(), ),), ), @@ -46,14 +46,14 @@ fn list_mcp_resource_templates_tool_matches_expected_spec() { ( "server".to_string(), JsonSchema::string(Some( - "Optional MCP server name. When omitted, lists resource templates from all configured servers." + "MCP server name. Omit to list resource templates from every configured server." .to_string(), ),), ), ( "cursor".to_string(), JsonSchema::string(Some( - "Opaque cursor returned by a previous list_mcp_resource_templates call for the same server." + "Opaque cursor from a previous list_mcp_resource_templates call; omit for the first page." .to_string(), ),), ), diff --git a/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs index de069854f1..bcfa5231b9 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents/close_agent.rs @@ -1,6 +1,7 @@ use super::*; use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v1; use crate::turn_timing::now_unix_timestamp_ms; +use codex_protocol::error::CodexErr; use codex_tools::ToolSpec; pub(crate) struct Handler; @@ -36,11 +37,9 @@ async fn handle_close_agent( let arguments = function_arguments(payload)?; let args: CloseAgentArgs = parse_arguments(&arguments)?; let agent_id = parse_agent_id_target(&args.target)?; - let receiver_agent = session - .services - .agent_control - .get_agent_metadata(agent_id) - .unwrap_or_default(); + let receiver_agent = session.services.agent_control.get_agent_metadata(agent_id); + let known_agent = receiver_agent.is_some(); + let receiver_agent = receiver_agent.unwrap_or_default(); session .send_event( &turn, @@ -60,6 +59,9 @@ async fn handle_close_agent( .await { Ok(mut status_rx) => status_rx.borrow_and_update().clone(), + Err(CodexErr::ThreadNotFound(_)) if known_agent => { + session.services.agent_control.get_status(agent_id).await + } Err(err) => { let status = session.services.agent_control.get_status(agent_id).await; session diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs index 8aad428411..22bc8d5d1a 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec.rs @@ -11,9 +11,11 @@ use std::collections::BTreeMap; pub const MULTI_AGENT_V1_NAMESPACE: &str = "multi_agent_v1"; const MULTI_AGENT_V1_NAMESPACE_DESCRIPTION: &str = "Tools for spawning and managing sub-agents."; -const SPAWN_AGENT_INHERITED_MODEL_GUIDANCE: &str = "Spawned agents inherit your current model by default. Omit `model` to use that preferred default; set `model` only when an explicit override is needed."; -const SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION: &str = "Optional model override for the new agent. Leave unset to inherit the same model as the parent, which is the preferred default. Only set this when the user explicitly asks for a different model or the task clearly requires one."; -const SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION: &str = "Optional service tier override for the new agent. Leave unset unless the user explicitly asks for one."; +const SPAWN_AGENT_INHERITED_MODEL_GUIDANCE: &str = "Spawned agents inherit your current model by default. If provided, `model` specifies the model to use for the spawned agent."; +const SPAWN_AGENT_MODEL_OVERRIDE_DESCRIPTION: &str = + "Model override for the new agent. Omit to inherit the parent model."; +const SPAWN_AGENT_SERVICE_TIER_OVERRIDE_DESCRIPTION: &str = + "Service tier override for the new agent. Omit unless explicitly requested."; const MAX_MODEL_OVERRIDES_IN_SPAWN_AGENT_DESCRIPTION: usize = 5; #[derive(Debug, Clone, Default)] @@ -125,7 +127,7 @@ pub fn create_send_input_tool_v1() -> ToolSpec { ( "interrupt".to_string(), JsonSchema::boolean(Some( - "When true, stop the agent's current task and handle this immediately. When false (default), queue this message." + "True interrupts the current task and handles this message immediately; false or omitted queues it." .to_string(), )), ), @@ -258,7 +260,7 @@ pub fn create_list_agents_tool() -> ToolSpec { let properties = BTreeMap::from([( "path_prefix".to_string(), JsonSchema::string(Some( - "Optional task-path prefix (not ending with trailing slash). Accepts the same relative or absolute task-path syntax." + "Task-path prefix filter without a trailing slash. Omit to list all live agents." .to_string(), )), )]); @@ -555,7 +557,7 @@ fn spawn_agent_common_properties_v1(agent_type_description: &str) -> BTreeMap BTreeMap BTreeMap JsonSchema ( "timeout_ms".to_string(), JsonSchema::number(Some(format!( - "Optional timeout in milliseconds. Defaults to {}, min {}, max {}. Prefer longer waits (minutes) to avoid busy polling.", + "Timeout in milliseconds. Defaults to {}, min {}, max {}. Prefer longer waits (minutes) to avoid busy polling.", options.default_timeout_ms, options.min_timeout_ms, options.max_timeout_ms, ))), ), @@ -824,7 +826,7 @@ fn wait_agent_tool_parameters_v2(options: WaitAgentTimeoutOptions) -> JsonSchema let properties = BTreeMap::from([( "timeout_ms".to_string(), JsonSchema::number(Some(format!( - "Optional timeout in milliseconds. Defaults to {}, min {}, max {}.", + "Timeout in milliseconds. Defaults to {}, min {}, max {}.", options.default_timeout_ms, options.min_timeout_ms, options.max_timeout_ms, ))), )]); diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs index d90cdc95e0..a29056a120 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs @@ -306,7 +306,7 @@ fn wait_agent_tool_v2_uses_timeout_only_summary_output() { properties .get("timeout_ms") .and_then(|schema| schema.description.as_deref()), - Some("Optional timeout in milliseconds. Defaults to 30000, min 10000, max 3600000.") + Some("Timeout in milliseconds. Defaults to 30000, min 10000, max 3600000.") ); assert_eq!(parameters.required.as_ref(), None); assert_eq!( @@ -338,9 +338,7 @@ fn list_agents_tool_includes_path_prefix_and_agent_fields() { properties .get("path_prefix") .and_then(|schema| schema.description.as_deref()), - Some( - "Optional task-path prefix (not ending with trailing slash). Accepts the same relative or absolute task-path syntax." - ) + Some("Task-path prefix filter without a trailing slash. Omit to list all live agents.") ); assert_eq!( output_schema.expect("list_agents output schema")["properties"]["agents"]["items"]["required"], diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 68b19adea9..164d5410e0 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -52,6 +52,7 @@ use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::TurnCompleteEvent; use codex_protocol::user_input::UserInput; +use codex_state::DirectionalThreadSpawnEdgeStatus; use core_test_support::TempDirExt; use pretty_assertions::assert_eq; use serde::Deserialize; @@ -3751,6 +3752,126 @@ async fn multi_agent_v2_close_agent_accepts_task_name_target() { ); } +#[tokio::test] +async fn multi_agent_v2_close_agent_reaps_stale_task_name_target() { + let (mut session, mut turn) = make_session_and_context().await; + let mut config = (*turn.config).clone(); + config.agent_max_threads = Some(1); + config + .features + .enable(Feature::MultiAgentV2) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow sqlite"); + let state_db = init_state_db(&config) + .await + .expect("sqlite state db should initialize"); + let manager = ThreadManager::with_models_provider_home_and_state_for_tests( + CodexAuth::from_api_key("dummy"), + config.model_provider.clone(), + config.codex_home.to_path_buf(), + Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()), + Some(state_db.clone()), + ); + let root = manager + .start_thread(config.clone()) + .await + .expect("root thread should start"); + session.services.agent_control = manager.agent_control(); + session.conversation_id = root.thread_id; + turn.config = Arc::new(config.clone()); + + let session = Arc::new(session); + let turn = Arc::new(turn); + SpawnAgentHandlerV2::default() + .handle(invocation( + session.clone(), + turn.clone(), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo", + "task_name": "worker" + })), + )) + .await + .expect("spawn_agent should succeed"); + + let agent_id = session + .services + .agent_control + .resolve_agent_reference(session.conversation_id, &turn.session_source, "worker") + .await + .expect("worker path should resolve"); + let stale_thread = manager + .remove_thread(&agent_id) + .await + .expect("worker thread should be loaded before removal"); + stale_thread + .submit(Op::Shutdown {}) + .await + .expect("removed worker thread should still accept shutdown"); + stale_thread.wait_until_terminated().await; + + let output = CloseAgentHandlerV2 + .handle(invocation( + session.clone(), + turn.clone(), + "close_agent", + function_payload(json!({"target": "worker"})), + )) + .await + .expect("close_agent should reap stale v2 task names"); + let (content, success) = expect_text_output(output); + let result: close_agent::CloseAgentResult = + serde_json::from_str(&content).expect("close_agent result should be json"); + assert_eq!(result.previous_status, AgentStatus::NotFound); + assert_eq!(success, Some(true)); + + let open_children = state_db + .list_thread_spawn_children_with_status( + root.thread_id, + DirectionalThreadSpawnEdgeStatus::Open, + ) + .await + .expect("open children should load"); + assert_eq!(open_children, Vec::::new()); + let closed_children = state_db + .list_thread_spawn_children_with_status( + root.thread_id, + DirectionalThreadSpawnEdgeStatus::Closed, + ) + .await + .expect("closed children should load"); + assert_eq!(closed_children, vec![agent_id]); + + SpawnAgentHandlerV2::default() + .handle(invocation( + session.clone(), + turn.clone(), + "spawn_agent", + function_payload(json!({ + "message": "inspect this repo again", + "task_name": "replacement" + })), + )) + .await + .expect("spawn_agent should succeed after stale close releases the slot"); + let replacement_id = session + .services + .agent_control + .resolve_agent_reference(session.conversation_id, &turn.session_source, "replacement") + .await + .expect("replacement path should resolve"); + let _ = session + .services + .agent_control + .shutdown_live_agent(replacement_id) + .await + .expect("replacement should shut down"); +} + #[tokio::test] async fn multi_agent_v2_close_agent_rejects_root_target_and_id() { let (mut session, mut turn) = make_session_and_context().await; diff --git a/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs b/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs index 088e531062..15502572a5 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_v2/close_agent.rs @@ -1,6 +1,7 @@ use super::*; use crate::tools::handlers::multi_agents_spec::create_close_agent_tool_v2; use crate::turn_timing::now_unix_timestamp_ms; +use codex_protocol::error::CodexErr; use codex_tools::ToolSpec; pub(crate) struct Handler; @@ -36,11 +37,9 @@ async fn handle_close_agent( let arguments = function_arguments(payload)?; let args: CloseAgentArgs = parse_arguments(&arguments)?; let agent_id = resolve_agent_target(&session, &turn, &args.target).await?; - let receiver_agent = session - .services - .agent_control - .get_agent_metadata(agent_id) - .unwrap_or_default(); + let receiver_agent = session.services.agent_control.get_agent_metadata(agent_id); + let known_agent = receiver_agent.is_some(); + let receiver_agent = receiver_agent.unwrap_or_default(); if receiver_agent .agent_path .as_ref() @@ -69,6 +68,9 @@ async fn handle_close_agent( .await { Ok(mut status_rx) => status_rx.borrow_and_update().clone(), + Err(CodexErr::ThreadNotFound(_)) if known_agent => { + session.services.agent_control.get_status(agent_id).await + } Err(err) => { let status = session.services.agent_control.get_status(agent_id).await; session diff --git a/codex-rs/core/src/tools/handlers/plan_spec.rs b/codex-rs/core/src/tools/handlers/plan_spec.rs index 263517b93a..d8ce95767b 100644 --- a/codex-rs/core/src/tools/handlers/plan_spec.rs +++ b/codex-rs/core/src/tools/handlers/plan_spec.rs @@ -1,21 +1,30 @@ use codex_tools::JsonSchema; use codex_tools::ResponsesApiTool; use codex_tools::ToolSpec; +use serde_json::json; use std::collections::BTreeMap; pub fn create_update_plan_tool() -> ToolSpec { let plan_item_properties = BTreeMap::from([ - ("step".to_string(), JsonSchema::string(/*description*/ None)), + ( + "step".to_string(), + JsonSchema::string(Some("Task step text.".to_string())), + ), ( "status".to_string(), - JsonSchema::string(Some("One of: pending, in_progress, completed".to_string())), + JsonSchema::string_enum( + vec![json!("pending"), json!("in_progress"), json!("completed")], + Some("Step status.".to_string()), + ), ), ]); let properties = BTreeMap::from([ ( "explanation".to_string(), - JsonSchema::string(/*description*/ None), + JsonSchema::string(Some( + "Optional explanation for this plan update.".to_string(), + )), ), ( "plan".to_string(), diff --git a/codex-rs/core/src/tools/handlers/shell_spec.rs b/codex-rs/core/src/tools/handlers/shell_spec.rs index 43b78e3afe..361f73bc04 100644 --- a/codex-rs/core/src/tools/handlers/shell_spec.rs +++ b/codex-rs/core/src/tools/handlers/shell_spec.rs @@ -28,7 +28,7 @@ pub(crate) fn create_exec_command_tool_with_environment_id( ( "workdir".to_string(), JsonSchema::string(Some( - "Optional working directory to run the command in; defaults to the turn cwd." + "Working directory for the command. Defaults to the turn cwd." .to_string(), )), ), @@ -41,20 +41,20 @@ pub(crate) fn create_exec_command_tool_with_environment_id( ( "tty".to_string(), JsonSchema::boolean(Some( - "Whether to allocate a TTY for the command. Defaults to false (plain pipes); set to true to open a PTY and access TTY process." + "True allocates a PTY for the command; false or omitted uses plain pipes." .to_string(), )), ), ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for output before yielding.".to_string(), + "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.".to_string(), )), ), ( "max_output_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of tokens to return. Excess output will be truncated.".to_string(), + "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.".to_string(), )), ), ]); @@ -62,7 +62,8 @@ pub(crate) fn create_exec_command_tool_with_environment_id( properties.insert( "login".to_string(), JsonSchema::boolean(Some( - "Whether to run the shell with -l/-i semantics. Defaults to true.".to_string(), + "True runs the shell with -l/-i semantics; false disables them. Defaults to true." + .to_string(), )), ); } @@ -70,7 +71,8 @@ pub(crate) fn create_exec_command_tool_with_environment_id( properties.insert( "environment_id".to_string(), JsonSchema::string(Some( - "Optional environment id from the block. If omitted, uses the primary environment.".to_string(), + "Environment id from . Omit to use the primary environment." + .to_string(), )), ); } @@ -111,19 +113,19 @@ pub fn create_write_stdin_tool() -> ToolSpec { ( "chars".to_string(), JsonSchema::string(Some( - "Bytes to write to stdin (may be empty to poll).".to_string(), + "Bytes to write to stdin. Defaults to empty, which polls without writing.".to_string(), )), ), ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for output before yielding.".to_string(), + "Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.".to_string(), )), ), ( "max_output_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of tokens to return. Excess output will be truncated.".to_string(), + "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.".to_string(), )), ), ]); @@ -149,19 +151,19 @@ pub fn create_shell_command_tool(options: CommandToolOptions) -> ToolSpec { ( "command".to_string(), JsonSchema::string(Some( - "The shell script to execute in the user's default shell".to_string(), + "Shell script to run in the user's default shell.".to_string(), )), ), ( "workdir".to_string(), JsonSchema::string(Some( - "The working directory to execute the command in".to_string(), + "Working directory for the command. Defaults to the turn cwd.".to_string(), )), ), ( "timeout_ms".to_string(), JsonSchema::number(Some( - "The timeout for the command in milliseconds".to_string(), + "Maximum command runtime. Defaults to 10000 ms.".to_string(), )), ), ]); @@ -169,7 +171,7 @@ pub fn create_shell_command_tool(options: CommandToolOptions) -> ToolSpec { properties.insert( "login".to_string(), JsonSchema::boolean(Some( - "Whether to run the shell with login shell semantics. Defaults to true." + "True runs with login shell semantics; false disables them. Defaults to true." .to_string(), )), ); @@ -281,92 +283,108 @@ fn unified_exec_output_schema() -> Value { fn create_approval_parameters( exec_permission_approvals_enabled: bool, ) -> BTreeMap { + let mut sandbox_permission_values = vec![json!("use_default")]; + if exec_permission_approvals_enabled { + sandbox_permission_values.push(json!("with_additional_permissions")); + } + sandbox_permission_values.push(json!("require_escalated")); + let sandbox_permissions_description = if exec_permission_approvals_enabled { + "Per-command sandbox override. Defaults to `use_default`; use `with_additional_permissions` with `additional_permissions`, or `require_escalated` for unsandboxed execution." + } else { + "Per-command sandbox override. Defaults to `use_default`; use `require_escalated` for unsandboxed execution." + }; + let mut properties = BTreeMap::from([ ( "sandbox_permissions".to_string(), - JsonSchema::string(Some( - if exec_permission_approvals_enabled { - "Sandbox permissions for the command. Use \"with_additional_permissions\" to request additional sandboxed filesystem or network permissions (preferred), or \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\"." - } else { - "Sandbox permissions for the command. Set to \"require_escalated\" to request running without sandbox restrictions; defaults to \"use_default\"." - } - .to_string(), - )), + JsonSchema::string_enum( + sandbox_permission_values, + Some(sandbox_permissions_description.to_string()), + ), ), ( "justification".to_string(), JsonSchema::string(Some( - r#"Only set if sandbox_permissions is \"require_escalated\". - Request approval from the user to run this command outside the sandbox. - Phrased as a simple question that summarizes the purpose of the - command as it relates to the task at hand - e.g. 'Do you want to - fetch and pull the latest version of this git branch?'"# - .to_string(), + "User-facing approval question for `require_escalated`; omit otherwise.".to_string(), )), ), ( "prefix_rule".to_string(), JsonSchema::array(JsonSchema::string(/*description*/ None), Some( - r#"Only specify when sandbox_permissions is `require_escalated`. - Suggest a prefix command pattern that will allow you to fulfill similar requests from the user in the future. - Should be a short but reasonable prefix, e.g. [\"git\", \"pull\"] or [\"uv\", \"run\"] or [\"pytest\"]."#.to_string(), + r#"Reusable approval prefix for `cmd`, only with `sandbox_permissions: "require_escalated"`; for example ["git", "pull"]."#.to_string(), )), ), ]); if exec_permission_approvals_enabled { - properties.insert( - "additional_permissions".to_string(), - permission_profile_schema(), + let mut additional_permissions = permission_profile_schema(); + additional_permissions.description = Some( + "Sandboxed filesystem or network access for this command; only with `sandbox_permissions: \"with_additional_permissions\"`." + .to_string(), ); + properties.insert("additional_permissions".to_string(), additional_permissions); } properties } fn permission_profile_schema() -> JsonSchema { - JsonSchema::object( + let mut schema = JsonSchema::object( BTreeMap::from([ ("network".to_string(), network_permissions_schema()), ("file_system".to_string(), file_system_permissions_schema()), ]), /*required*/ None, Some(false.into()), - ) + ); + schema.description = Some("Filesystem or network access request.".to_string()); + schema } fn network_permissions_schema() -> JsonSchema { - JsonSchema::object( + let mut schema = JsonSchema::object( BTreeMap::from([( "enabled".to_string(), - JsonSchema::boolean(Some("Set to true to request network access.".to_string())), + JsonSchema::boolean(Some( + "True requests network access; false or omitted requests none.".to_string(), + )), )]), /*required*/ None, Some(false.into()), - ) + ); + schema.description = Some("Network access request.".to_string()); + schema } fn file_system_permissions_schema() -> JsonSchema { - JsonSchema::object( + let mut schema = JsonSchema::object( BTreeMap::from([ ( "read".to_string(), JsonSchema::array( JsonSchema::string(/*description*/ None), - Some("Absolute paths to grant read access to.".to_string()), + Some( + "Absolute paths to grant read access; omit when none are needed." + .to_string(), + ), ), ), ( "write".to_string(), JsonSchema::array( JsonSchema::string(/*description*/ None), - Some("Absolute paths to grant write access to.".to_string()), + Some( + "Absolute paths to grant write access; omit when none are needed." + .to_string(), + ), ), ), ]), /*required*/ None, Some(false.into()), - ) + ); + schema.description = Some("Filesystem access request.".to_string()); + schema } fn windows_shell_guidance() -> &'static str { diff --git a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs index 4774815fb2..c11f34e927 100644 --- a/codex-rs/core/src/tools/handlers/shell_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/shell_spec_tests.rs @@ -31,7 +31,7 @@ fn exec_command_tool_matches_expected_spec() { ( "workdir".to_string(), JsonSchema::string(Some( - "Optional working directory to run the command in; defaults to the turn cwd." + "Working directory for the command. Defaults to the turn cwd." .to_string(), )), ), @@ -44,27 +44,26 @@ fn exec_command_tool_matches_expected_spec() { ( "tty".to_string(), JsonSchema::boolean(Some( - "Whether to allocate a TTY for the command. Defaults to false (plain pipes); set to true to open a PTY and access TTY process." + "True allocates a PTY for the command; false or omitted uses plain pipes." .to_string(), )), ), ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for output before yielding.".to_string(), + "Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.".to_string(), )), ), ( "max_output_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of tokens to return. Excess output will be truncated." - .to_string(), + "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.".to_string(), )), ), ( "login".to_string(), JsonSchema::boolean(Some( - "Whether to run the shell with -l/-i semantics. Defaults to true.".to_string(), + "True runs the shell with -l/-i semantics; false disables them. Defaults to true.".to_string(), )), ), ]); @@ -103,19 +102,19 @@ fn write_stdin_tool_matches_expected_spec() { ( "chars".to_string(), JsonSchema::string(Some( - "Bytes to write to stdin (may be empty to poll).".to_string(), + "Bytes to write to stdin. Defaults to empty, which polls without writing.".to_string(), )), ), ( "yield_time_ms".to_string(), JsonSchema::number(Some( - "How long to wait (in milliseconds) for output before yielding.".to_string(), + "Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.".to_string(), )), ), ( "max_output_tokens".to_string(), JsonSchema::number(Some( - "Maximum number of tokens to return. Excess output will be truncated.".to_string(), + "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.".to_string(), )), ), ]); @@ -201,25 +200,25 @@ Examples of valid command strings: ( "command".to_string(), JsonSchema::string(Some( - "The shell script to execute in the user's default shell".to_string(), + "Shell script to run in the user's default shell.".to_string(), )), ), ( "workdir".to_string(), JsonSchema::string(Some( - "The working directory to execute the command in".to_string(), + "Working directory for the command. Defaults to the turn cwd.".to_string(), )), ), ( "timeout_ms".to_string(), JsonSchema::number(Some( - "The timeout for the command in milliseconds".to_string(), + "Maximum command runtime. Defaults to 10000 ms.".to_string(), )), ), ( "login".to_string(), JsonSchema::boolean(Some( - "Whether to run the shell with login shell semantics. Defaults to true." + "True runs with login shell semantics; false disables them. Defaults to true." .to_string(), )), ), diff --git a/codex-rs/core/src/tools/handlers/test_sync_spec.rs b/codex-rs/core/src/tools/handlers/test_sync_spec.rs index 7d2b665713..4de8104034 100644 --- a/codex-rs/core/src/tools/handlers/test_sync_spec.rs +++ b/codex-rs/core/src/tools/handlers/test_sync_spec.rs @@ -20,7 +20,7 @@ pub fn create_test_sync_tool() -> ToolSpec { ( "timeout_ms".to_string(), JsonSchema::number(Some( - "Maximum time in milliseconds to wait at the barrier".to_string(), + "Maximum barrier wait in milliseconds. Defaults to 1000.".to_string(), )), ), ]); @@ -29,13 +29,13 @@ pub fn create_test_sync_tool() -> ToolSpec { ( "sleep_before_ms".to_string(), JsonSchema::number(Some( - "Optional delay in milliseconds before any other action".to_string(), + "Delay before any other action. Defaults to no delay.".to_string(), )), ), ( "sleep_after_ms".to_string(), JsonSchema::number(Some( - "Optional delay in milliseconds after completing the barrier".to_string(), + "Delay after completing the barrier. Defaults to no delay.".to_string(), )), ), ( diff --git a/codex-rs/core/src/tools/handlers/test_sync_spec_tests.rs b/codex-rs/core/src/tools/handlers/test_sync_spec_tests.rs index d6d47cfa9a..55f4a1a0a6 100644 --- a/codex-rs/core/src/tools/handlers/test_sync_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/test_sync_spec_tests.rs @@ -35,7 +35,7 @@ fn test_sync_tool_matches_expected_spec() { ( "timeout_ms".to_string(), JsonSchema::number(Some( - "Maximum time in milliseconds to wait at the barrier" + "Maximum barrier wait in milliseconds. Defaults to 1000." .to_string(), )), ), @@ -47,14 +47,14 @@ fn test_sync_tool_matches_expected_spec() { ( "sleep_after_ms".to_string(), JsonSchema::number(Some( - "Optional delay in milliseconds after completing the barrier" + "Delay after completing the barrier. Defaults to no delay." .to_string(), )), ), ( "sleep_before_ms".to_string(), JsonSchema::number(Some( - "Optional delay in milliseconds before any other action".to_string(), + "Delay before any other action. Defaults to no delay.".to_string(), )), ), ]), /*required*/ None, Some(false.into())), diff --git a/codex-rs/core/src/tools/handlers/tool_search_spec.rs b/codex-rs/core/src/tools/handlers/tool_search_spec.rs index d5a0a37897..2d17d131c7 100644 --- a/codex-rs/core/src/tools/handlers/tool_search_spec.rs +++ b/codex-rs/core/src/tools/handlers/tool_search_spec.rs @@ -16,7 +16,7 @@ pub(crate) fn create_tool_search_tool( ( "limit".to_string(), JsonSchema::number(Some(format!( - "Maximum number of tools to return (defaults to {default_limit})." + "Maximum number of tools to return. Defaults to {default_limit}." ))), ), ]); @@ -98,7 +98,7 @@ mod tests { ( "limit".to_string(), JsonSchema::number(Some( - "Maximum number of tools to return (defaults to 8)." + "Maximum number of tools to return. Defaults to 8." .to_string(), ),), ), diff --git a/codex-rs/core/src/tools/handlers/view_image_spec.rs b/codex-rs/core/src/tools/handlers/view_image_spec.rs index ed0b1021a5..5d2b7e0b15 100644 --- a/codex-rs/core/src/tools/handlers/view_image_spec.rs +++ b/codex-rs/core/src/tools/handlers/view_image_spec.rs @@ -15,7 +15,7 @@ pub struct ViewImageToolOptions { pub fn create_view_image_tool(options: ViewImageToolOptions) -> ToolSpec { let mut properties = BTreeMap::from([( "path".to_string(), - JsonSchema::string(Some("Local filesystem path to an image file".to_string())), + JsonSchema::string(Some("Local filesystem path to an image file.".to_string())), )]); if options.can_request_original_image_detail { properties.insert( @@ -23,7 +23,7 @@ pub fn create_view_image_tool(options: ViewImageToolOptions) -> ToolSpec { JsonSchema::string_enum( vec![json!("high"), json!("original")], Some( - "Optional detail override. Supported values are `high` and `original`; omit this field for default high resized behavior. Use `original` to preserve the file's original resolution instead of resizing to fit. This is important when high-fidelity image perception or precise localization is needed, especially for CUA agents.".to_string(), + "Image detail level. Defaults to `high`; use `original` to preserve exact resolution.".to_string(), ), ), ); @@ -32,7 +32,7 @@ pub fn create_view_image_tool(options: ViewImageToolOptions) -> ToolSpec { properties.insert( "environment_id".to_string(), JsonSchema::string(Some( - "Optional selected environment id to target. Omit this to use the primary environment." + "Environment id from . Omit to use the primary environment." .to_string(), )), ); diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index deb9ae596e..235f8c4e96 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -28,6 +28,7 @@ use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::ToolRuntime; use crate::tools::sandboxing::default_exec_approval_requirement; use crate::tools::sandboxing::sandbox_override_for_first_attempt; +use crate::tools::sandboxing::unsandboxed_execution_allowed; use codex_hooks::PermissionRequestDecision; use codex_otel::ToolDecisionSource; use codex_protocol::error::CodexErr; @@ -85,6 +86,7 @@ impl ToolOrchestrator { enforce_managed_network: attempt.enforce_managed_network, manager: attempt.manager, sandbox_cwd: attempt.sandbox_cwd, + workspace_roots: attempt.workspace_roots, codex_linux_sandbox_exe: attempt.codex_linux_sandbox_exe, use_legacy_landlock: attempt.use_legacy_landlock, windows_sandbox_level: attempt.windows_sandbox_level, @@ -236,12 +238,14 @@ impl ToolOrchestrator { let use_legacy_landlock = turn_ctx.features.use_legacy_landlock(); #[allow(deprecated)] let sandbox_cwd = tool.sandbox_cwd(req).unwrap_or(&turn_ctx.cwd); + let workspace_roots = turn_ctx.config.effective_workspace_roots(); let initial_attempt = SandboxAttempt { sandbox: initial_sandbox, permissions: &turn_ctx.permission_profile, enforce_managed_network: managed_network_active, manager: &self.sandbox, sandbox_cwd, + workspace_roots: workspace_roots.as_slice(), codex_linux_sandbox_exe: turn_ctx.codex_linux_sandbox_exe.as_ref(), use_legacy_landlock, windows_sandbox_level: turn_ctx.windows_sandbox_level, @@ -291,6 +295,8 @@ impl ToolOrchestrator { network_policy_decision, }))); } + let unsandboxed_allowed = + unsandboxed_execution_allowed(&file_system_sandbox_policy); // Under `Never` or `OnRequest`, do not retry without sandbox; // surface a concise sandbox denial that preserves the // original output. @@ -312,6 +318,12 @@ impl ToolOrchestrator { }))); } } + if !unsandboxed_allowed && network_approval_context.is_none() { + return Err(ToolError::Codex(CodexErr::Sandbox(SandboxErr::Denied { + output, + network_policy_decision, + }))); + } let retry_reason = if let Some(network_approval_context) = network_approval_context.as_ref() { format!( @@ -354,13 +366,30 @@ impl ToolOrchestrator { .await?; } - let escalated_attempt = SandboxAttempt { - sandbox: SandboxType::None, + let retry_sandbox = if unsandboxed_allowed { + SandboxType::None + } else { + self.sandbox.select_initial( + &file_system_sandbox_policy, + network_sandbox_policy, + tool.sandbox_preference(), + turn_ctx.windows_sandbox_level, + managed_network_active, + ) + }; + let retry_codex_linux_sandbox_exe = if unsandboxed_allowed { + None + } else { + turn_ctx.codex_linux_sandbox_exe.as_ref() + }; + let retry_attempt = SandboxAttempt { + sandbox: retry_sandbox, permissions: &turn_ctx.permission_profile, enforce_managed_network: managed_network_active, manager: &self.sandbox, sandbox_cwd, - codex_linux_sandbox_exe: None, + workspace_roots: workspace_roots.as_slice(), + codex_linux_sandbox_exe: retry_codex_linux_sandbox_exe, use_legacy_landlock, windows_sandbox_level: turn_ctx.windows_sandbox_level, windows_sandbox_private_desktop: turn_ctx @@ -371,14 +400,9 @@ impl ToolOrchestrator { }; // Second attempt. - let (retry_result, retry_deferred_network_approval) = Self::run_attempt( - tool, - req, - tool_ctx, - &escalated_attempt, - managed_network_active, - ) - .await; + let (retry_result, retry_deferred_network_approval) = + Self::run_attempt(tool, req, tool_ctx, &retry_attempt, managed_network_active) + .await; retry_result.map(|output| OrchestratorRunResult { output, deferred_network_approval: retry_deferred_network_approval, diff --git a/codex-rs/core/src/tools/router_tests.rs b/codex-rs/core/src/tools/router_tests.rs index 71ff7ca9e0..cece7fc171 100644 --- a/codex-rs/core/src/tools/router_tests.rs +++ b/codex-rs/core/src/tools/router_tests.rs @@ -332,7 +332,7 @@ async fn extension_tool_executors_are_model_visible_and_dispatchable() -> anyhow phase: None, }; session - .record_into_history(std::slice::from_ref(&history_item), &turn) + .record_conversation_items(&turn, std::slice::from_ref(&history_item)) .await; let router = ToolRouter::from_turn_context( diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index f4d8d461b2..0a741861fc 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -212,6 +212,7 @@ async fn file_system_sandbox_context_uses_active_attempt() { enforce_managed_network: false, manager: &manager, sandbox_cwd: &path, + workspace_roots: std::slice::from_ref(&path), codex_linux_sandbox_exe: None, use_legacy_landlock: true, windows_sandbox_level: WindowsSandboxLevel::RestrictedToken, @@ -265,6 +266,7 @@ async fn no_sandbox_attempt_has_no_file_system_context() { enforce_managed_network: false, manager: &manager, sandbox_cwd: &path, + workspace_roots: std::slice::from_ref(&path), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, diff --git a/codex-rs/core/src/tools/runtimes/mod.rs b/codex-rs/core/src/tools/runtimes/mod.rs index bba1c572ef..45e1754da9 100644 --- a/codex-rs/core/src/tools/runtimes/mod.rs +++ b/codex-rs/core/src/tools/runtimes/mod.rs @@ -22,6 +22,8 @@ use codex_sandboxing::SandboxCommand; use codex_sandboxing::SandboxType; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; +#[cfg(unix)] +use std::path::Path; pub(crate) mod apply_patch; pub(crate) mod shell; @@ -70,6 +72,44 @@ pub(crate) fn exec_env_for_sandbox_permissions( env } +#[cfg(unix)] +fn prepend_path_entry(env: &mut HashMap, path_entry: &str) -> String { + let updated_path = match env.get("PATH") { + Some(path) if !path.is_empty() => std::iter::once(path_entry) + .chain(path.split(':').filter(|entry| *entry != path_entry)) + .collect::>() + .join(":"), + _ => path_entry.to_string(), + }; + env.insert("PATH".to_string(), updated_path.clone()); + updated_path +} + +#[cfg(unix)] +pub(crate) fn prepend_zsh_fork_bin_to_path( + env: &mut HashMap, + shell_zsh_path: &Path, +) -> Option { + let zsh_bin_dir = shell_zsh_path + .parent() + .map(|path| path.to_string_lossy().to_string())?; + Some(prepend_path_entry(env, &zsh_bin_dir)) +} + +#[cfg(unix)] +pub(crate) fn apply_zsh_fork_path_prepend( + env: &mut HashMap, + explicit_env_overrides: &mut HashMap, + shell_zsh_path: &Path, +) { + let Some(updated_path) = prepend_zsh_fork_bin_to_path(env, shell_zsh_path) else { + return; + }; + // Snapshot wrapping restores explicit overrides after sourcing the shell + // snapshot, so capture this PATH override there as well. + explicit_env_overrides.insert("PATH".to_string(), updated_path); +} + pub(crate) fn disable_powershell_profile_for_elevated_windows_sandbox( command: &[String], shell_type: Option<&ShellType>, diff --git a/codex-rs/core/src/tools/runtimes/mod_tests.rs b/codex-rs/core/src/tools/runtimes/mod_tests.rs index fd10f22242..9a473cd25f 100644 --- a/codex-rs/core/src/tools/runtimes/mod_tests.rs +++ b/codex-rs/core/src/tools/runtimes/mod_tests.rs @@ -111,6 +111,7 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow:: enforce_managed_network: false, manager: &manager, sandbox_cwd: &cwd, + workspace_roots: std::slice::from_ref(&cwd), codex_linux_sandbox_exe: None, use_legacy_landlock: false, windows_sandbox_level: WindowsSandboxLevel::Disabled, @@ -143,6 +144,48 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow:: Ok(()) } +#[cfg(unix)] +#[test] +fn apply_zsh_fork_path_prepend_uses_shell_parent() { + let mut env = HashMap::from([("PATH".to_string(), "/usr/bin:/bin".to_string())]); + let mut explicit_env_overrides = HashMap::new(); + + apply_zsh_fork_path_prepend( + &mut env, + &mut explicit_env_overrides, + PathBuf::from("/package/codex-resources/zsh/bin/zsh").as_path(), + ); + + let expected = "/package/codex-resources/zsh/bin:/usr/bin:/bin"; + assert_eq!(env.get("PATH").map(String::as_str), Some(expected)); + assert_eq!( + explicit_env_overrides.get("PATH").map(String::as_str), + Some(expected) + ); +} + +#[cfg(unix)] +#[test] +fn apply_zsh_fork_path_prepend_moves_existing_shell_parent_to_front() { + let mut env = HashMap::from([( + "PATH".to_string(), + "/usr/bin:/package/codex-resources/zsh/bin:/bin:/package/codex-resources/zsh/bin" + .to_string(), + )]); + let mut explicit_env_overrides = HashMap::new(); + + apply_zsh_fork_path_prepend( + &mut env, + &mut explicit_env_overrides, + PathBuf::from("/package/codex-resources/zsh/bin/zsh").as_path(), + ); + + assert_eq!( + env.get("PATH").map(String::as_str), + Some("/package/codex-resources/zsh/bin:/usr/bin:/bin") + ); +} + #[test] fn explicit_escalation_keeps_user_proxy_env_without_codex_marker() { let env = HashMap::from([ @@ -818,6 +861,57 @@ fn maybe_wrap_shell_lc_with_snapshot_applies_explicit_path_override() { assert_eq!(String::from_utf8_lossy(&output.stdout), "/worktree/bin"); } +#[cfg(unix)] +#[test] +fn maybe_wrap_shell_lc_with_snapshot_preserves_zsh_fork_path_prepend() { + let dir = tempdir().expect("create temp dir"); + let snapshot_path = dir.path().join("snapshot.sh"); + std::fs::write( + &snapshot_path, + "# Snapshot file\nexport PATH='/snapshot/bin'\n", + ) + .expect("write snapshot"); + let session_shell = shell_with_snapshot( + ShellType::Bash, + "/bin/bash", + snapshot_path.abs(), + dir.path().abs(), + ); + let command = vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "printf '%s' \"$PATH\"".to_string(), + ]; + let zsh_path = dir + .path() + .join("codex-resources") + .join("zsh") + .join("bin") + .join("zsh"); + let zsh_bin_dir = zsh_path.parent().expect("zsh path should have parent"); + let mut env = HashMap::from([("PATH".to_string(), "/worktree/bin".to_string())]); + let mut explicit_env_overrides = HashMap::new(); + apply_zsh_fork_path_prepend(&mut env, &mut explicit_env_overrides, zsh_path.as_path()); + let rewritten = maybe_wrap_shell_lc_with_snapshot( + &command, + &session_shell, + &dir.path().abs(), + &explicit_env_overrides, + &env, + ); + let output = Command::new(&rewritten[0]) + .args(&rewritten[1..]) + .env("PATH", env.get("PATH").expect("PATH should be set")) + .output() + .expect("run rewritten command"); + + assert!(output.status.success(), "command failed: {output:?}"); + assert_eq!( + String::from_utf8_lossy(&output.stdout), + format!("{}:/worktree/bin", zsh_bin_dir.display()) + ); +} + #[test] fn maybe_wrap_shell_lc_with_snapshot_does_not_embed_override_values_in_argv() { let dir = tempdir().expect("create temp dir"); diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index df63f6cd47..0380f1840d 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -20,6 +20,8 @@ use crate::shell::ShellType; use crate::tools::flat_tool_name; use crate::tools::network_approval::NetworkApprovalMode; use crate::tools::network_approval::NetworkApprovalSpec; +#[cfg(unix)] +use crate::tools::runtimes::apply_zsh_fork_path_prepend; use crate::tools::runtimes::build_sandbox_command; use crate::tools::runtimes::disable_powershell_profile_for_elevated_windows_sandbox; use crate::tools::runtimes::exec_env_for_sandbox_permissions; @@ -34,6 +36,7 @@ use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::ToolRuntime; use crate::tools::sandboxing::managed_network_for_sandbox_permissions; +use crate::tools::sandboxing::sandbox_permissions_preserving_denied_reads; use crate::tools::sandboxing::with_cached_approval; use codex_network_proxy::NetworkProxy; use codex_protocol::exec_output::ExecToolCallOutput; @@ -205,8 +208,13 @@ impl ToolRuntime for ShellRuntime { req: &ShellRequest, ctx: &ToolCtx, ) -> Option { + let file_system_sandbox_policy = ctx.turn.file_system_sandbox_policy(); + let sandbox_permissions = sandbox_permissions_preserving_denied_reads( + req.sandbox_permissions, + &file_system_sandbox_policy, + ); let network = - managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions)?; + managed_network_for_sandbox_permissions(req.network.as_ref(), sandbox_permissions)?; Some(NetworkApprovalSpec { network: Some(network.clone()), mode: NetworkApprovalMode::Immediate, @@ -231,14 +239,31 @@ impl ToolRuntime for ShellRuntime { ctx: &ToolCtx, ) -> Result { let session_shell = ctx.session.user_shell(); + let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions(); + let sandbox_permissions = sandbox_permissions_preserving_denied_reads( + req.sandbox_permissions, + &file_system_sandbox_policy, + ); let managed_network = - managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions); - let env = exec_env_for_sandbox_permissions(&req.env, req.sandbox_permissions); + managed_network_for_sandbox_permissions(req.network.as_ref(), sandbox_permissions); + let env = exec_env_for_sandbox_permissions(&req.env, sandbox_permissions); + let explicit_env_overrides = req.explicit_env_overrides.clone(); + #[cfg(unix)] + let (env, explicit_env_overrides) = { + let mut env = env; + let mut explicit_env_overrides = explicit_env_overrides; + if self.backend == ShellRuntimeBackend::ShellCommandZshFork + && let Some(shell_zsh_path) = ctx.session.services.shell_zsh_path.as_deref() + { + apply_zsh_fork_path_prepend(&mut env, &mut explicit_env_overrides, shell_zsh_path); + } + (env, explicit_env_overrides) + }; let command = maybe_wrap_shell_lc_with_snapshot( &req.command, session_shell.as_ref(), &req.cwd, - &req.explicit_env_overrides, + &explicit_env_overrides, &env, ); let command = disable_powershell_profile_for_elevated_windows_sandbox( diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index fef8db5ca9..2017718f7d 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -16,11 +16,14 @@ use crate::sandboxing::SandboxPermissions; use crate::shell::ShellType; use crate::tools::runtimes::build_sandbox_command; use crate::tools::runtimes::exec_env_for_sandbox_permissions; +use crate::tools::runtimes::prepend_zsh_fork_bin_to_path; use crate::tools::sandboxing::PermissionRequestPayload; use crate::tools::sandboxing::SandboxAttempt; use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::managed_network_for_sandbox_permissions; +use crate::tools::sandboxing::sandbox_permissions_preserving_denied_reads; +use crate::tools::sandboxing::unsandboxed_execution_allowed; use codex_execpolicy::Decision; use codex_execpolicy::Evaluation; use codex_execpolicy::MatchOptions; @@ -116,7 +119,17 @@ pub(super) async fn try_run_zsh_fork( return Ok(None); } - let env = exec_env_for_sandbox_permissions(&req.env, req.sandbox_permissions); + let (attempt_file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions(); + let sandbox_permissions = sandbox_permissions_preserving_denied_reads( + req.sandbox_permissions, + &attempt_file_system_sandbox_policy, + ); + let req = &ShellRequest { + sandbox_permissions, + ..req.clone() + }; + let mut env = exec_env_for_sandbox_permissions(&req.env, req.sandbox_permissions); + prepend_zsh_fork_bin_to_path(&mut env, shell_zsh_path); let command = build_sandbox_command(command, &req.cwd, &env, req.additional_permissions.clone())?; let options = ExecOptions { @@ -140,6 +153,7 @@ pub(super) async fn try_run_zsh_fork( capture_policy: _capture_policy, sandbox, windows_sandbox_policy_cwd: sandbox_policy_cwd, + windows_sandbox_workspace_roots, windows_sandbox_level, windows_sandbox_private_desktop: _windows_sandbox_private_desktop, permission_profile, @@ -168,6 +182,7 @@ pub(super) async fn try_run_zsh_fork( windows_sandbox_level, arg0, sandbox_policy_cwd, + windows_sandbox_workspace_roots, codex_linux_sandbox_exe: ctx.turn.codex_linux_sandbox_exe.clone(), use_legacy_landlock: ctx.turn.features.use_legacy_landlock(), }; @@ -269,6 +284,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( windows_sandbox_level: exec_request.windows_sandbox_level, arg0: exec_request.arg0.clone(), sandbox_policy_cwd: exec_request.windows_sandbox_policy_cwd.clone(), + windows_sandbox_workspace_roots: exec_request.windows_sandbox_workspace_roots.clone(), codex_linux_sandbox_exe: ctx.turn.codex_linux_sandbox_exe.clone(), use_legacy_landlock: ctx.turn.features.use_legacy_landlock(), }; @@ -367,11 +383,18 @@ impl CoreShellActionProvider { fn shell_request_escalation_execution( sandbox_permissions: SandboxPermissions, permission_profile: &PermissionProfile, + file_system_sandbox_policy: &FileSystemSandboxPolicy, additional_permissions: Option<&AdditionalPermissionProfile>, ) -> EscalationExecution { match sandbox_permissions { SandboxPermissions::UseDefault => EscalationExecution::TurnDefault, - SandboxPermissions::RequireEscalated => EscalationExecution::Unsandboxed, + SandboxPermissions::RequireEscalated => { + if unsandboxed_execution_allowed(file_system_sandbox_policy) { + EscalationExecution::Unsandboxed + } else { + EscalationExecution::TurnDefault + } + } SandboxPermissions::WithAdditionalPermissions => additional_permissions .map(|_| { // Shell request additional permissions were already normalized and @@ -611,8 +634,10 @@ impl EscalationPolicy for CoreShellActionProvider { // fallback function. let decision_driven_by_policy = Self::decision_driven_by_policy(&evaluation.matched_rules, evaluation.decision); - let needs_escalation = - self.sandbox_permissions.requires_escalated_permissions() || decision_driven_by_policy; + let unsandboxed_allowed = unsandboxed_execution_allowed(&self.file_system_sandbox_policy); + let needs_escalation = unsandboxed_allowed + && (self.sandbox_permissions.requires_escalated_permissions() + || decision_driven_by_policy); let decision_source = if decision_driven_by_policy { DecisionSource::PrefixRule @@ -620,10 +645,12 @@ impl EscalationPolicy for CoreShellActionProvider { DecisionSource::UnmatchedCommandFallback }; let escalation_execution = match decision_source { - DecisionSource::PrefixRule => EscalationExecution::Unsandboxed, + DecisionSource::PrefixRule if unsandboxed_allowed => EscalationExecution::Unsandboxed, + DecisionSource::PrefixRule => EscalationExecution::TurnDefault, DecisionSource::UnmatchedCommandFallback => Self::shell_request_escalation_execution( self.sandbox_permissions, &self.permission_profile, + &self.file_system_sandbox_policy, self.prompt_permissions.as_ref(), ), }; @@ -753,6 +780,7 @@ struct CoreShellCommandExecutor { windows_sandbox_level: WindowsSandboxLevel, arg0: Option, sandbox_policy_cwd: AbsolutePathBuf, + windows_sandbox_workspace_roots: Vec, codex_linux_sandbox_exe: Option, use_legacy_landlock: bool, } @@ -795,6 +823,7 @@ impl ShellCommandExecutor for CoreShellCommandExecutor { capture_policy: ExecCapturePolicy::ShellTool, sandbox: self.sandbox, windows_sandbox_policy_cwd: self.sandbox_policy_cwd.clone(), + windows_sandbox_workspace_roots: self.windows_sandbox_workspace_roots.clone(), windows_sandbox_level: self.windows_sandbox_level, windows_sandbox_private_desktop: false, permission_profile: self.permission_profile.clone(), @@ -932,6 +961,7 @@ impl CoreShellCommandExecutor { exec_request, options, self.sandbox_policy_cwd.clone(), + self.windows_sandbox_workspace_roots.clone(), ); if let Some(network) = exec_request.network.as_ref() { network.apply_to_env(&mut exec_request.env); diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs index 43d8e46952..6e7a1ced54 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs @@ -66,6 +66,23 @@ fn read_only_file_system_sandbox_policy() -> FileSystemSandboxPolicy { }]) } +fn denied_read_file_system_sandbox_policy() -> FileSystemSandboxPolicy { + FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: "**/*.env".to_string(), + }, + access: FileSystemAccessMode::Deny, + }, + ]) +} + fn test_sandbox_cwd() -> AbsolutePathBuf { AbsolutePathBuf::try_from(host_absolute_path(&["workspace"])).unwrap() } @@ -289,11 +306,13 @@ fn shell_request_escalation_execution_is_explicit() { &file_system_sandbox_policy, network_sandbox_policy, ); + let read_only_file_system_policy = read_only_file_system_sandbox_policy(); assert_eq!( CoreShellActionProvider::shell_request_escalation_execution( crate::sandboxing::SandboxPermissions::UseDefault, &permission_profile, + &file_system_sandbox_policy, /*additional_permissions*/ None, ), EscalationExecution::TurnDefault, @@ -302,14 +321,25 @@ fn shell_request_escalation_execution_is_explicit() { CoreShellActionProvider::shell_request_escalation_execution( crate::sandboxing::SandboxPermissions::RequireEscalated, &permission_profile, + &read_only_file_system_policy, /*additional_permissions*/ None, ), EscalationExecution::Unsandboxed, ); + assert_eq!( + CoreShellActionProvider::shell_request_escalation_execution( + crate::sandboxing::SandboxPermissions::RequireEscalated, + &permission_profile, + &file_system_sandbox_policy, + /*additional_permissions*/ None, + ), + EscalationExecution::TurnDefault, + ); assert_eq!( CoreShellActionProvider::shell_request_escalation_execution( crate::sandboxing::SandboxPermissions::WithAdditionalPermissions, &permission_profile, + &file_system_sandbox_policy, Some(&requested_permissions), ), EscalationExecution::Permissions(EscalationPermissions::ResolvedPermissionProfile( @@ -614,6 +644,102 @@ host_executable(name = "git", paths = ["{git_path_literal}"]) )); } +#[tokio::test(flavor = "current_thread")] +async fn denied_reads_keep_prefix_rule_allow_inside_sandbox() -> anyhow::Result<()> { + let cat_path = host_absolute_path(&["usr", "bin", "cat"]); + let cat_path_literal = starlark_string(&cat_path); + let policy_src = format!( + r#" +prefix_rule(pattern = ["{cat_path_literal}"], decision = "allow") +"# + ); + let mut parser = PolicyParser::new(); + parser.parse("test.rules", &policy_src).unwrap(); + let policy = parser.build(); + + let (session, turn_context) = make_session_and_context().await; + let file_system_sandbox_policy = denied_read_file_system_sandbox_policy(); + let permission_profile = PermissionProfile::from_runtime_permissions( + &file_system_sandbox_policy, + NetworkSandboxPolicy::Restricted, + ); + let workdir = test_sandbox_cwd(); + let provider = CoreShellActionProvider { + policy: Arc::new(RwLock::new(policy)), + session: Arc::new(session), + turn: Arc::new(turn_context), + call_id: "deny-read-prefix-allow".to_string(), + tool_name: GuardianCommandSource::Shell, + approval_policy: AskForApproval::OnRequest, + permission_profile, + file_system_sandbox_policy, + sandbox_policy_cwd: workdir.clone(), + sandbox_permissions: SandboxPermissions::UseDefault, + approval_sandbox_permissions: SandboxPermissions::UseDefault, + prompt_permissions: None, + stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), + }; + + let action = codex_shell_escalation::EscalationPolicy::determine_action( + &provider, + &AbsolutePathBuf::try_from(cat_path).unwrap(), + &["cat".to_string(), "/tmp/visible.txt".to_string()], + &workdir, + ) + .await?; + + assert_eq!(action, codex_shell_escalation::EscalationDecision::Run); + Ok(()) +} + +#[tokio::test(flavor = "current_thread")] +async fn denied_reads_keep_granular_sandbox_rejection_for_escalation() -> anyhow::Result<()> { + let (session, turn_context) = make_session_and_context().await; + let file_system_sandbox_policy = denied_read_file_system_sandbox_policy(); + let permission_profile = PermissionProfile::from_runtime_permissions( + &file_system_sandbox_policy, + NetworkSandboxPolicy::Restricted, + ); + let workdir = test_sandbox_cwd(); + let provider = CoreShellActionProvider { + policy: Arc::new(RwLock::new(PolicyParser::new().build())), + session: Arc::new(session), + turn: Arc::new(turn_context), + call_id: "deny-read-granular-sandbox-reject".to_string(), + tool_name: GuardianCommandSource::Shell, + approval_policy: AskForApproval::Granular(GranularApprovalConfig { + sandbox_approval: false, + rules: true, + skill_approval: true, + request_permissions: true, + mcp_elicitations: true, + }), + permission_profile, + file_system_sandbox_policy, + sandbox_policy_cwd: workdir.clone(), + sandbox_permissions: SandboxPermissions::RequireEscalated, + approval_sandbox_permissions: SandboxPermissions::RequireEscalated, + prompt_permissions: None, + stopwatch: codex_shell_escalation::Stopwatch::new(Duration::from_secs(1)), + }; + + let action = codex_shell_escalation::EscalationPolicy::determine_action( + &provider, + &AbsolutePathBuf::try_from(host_absolute_path(&["usr", "bin", "printf"])).unwrap(), + &["printf".to_string(), "hello".to_string()], + &workdir, + ) + .await?; + + assert_eq!( + action, + codex_shell_escalation::EscalationDecision::Deny { + reason: Some("Execution forbidden by policy".to_string()) + } + ); + Ok(()) +} + #[test] fn intercepted_exec_policy_treats_preapproved_additional_permissions_as_default() { let policy = PolicyParser::new().build(); diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index c613f198e0..e49c925728 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -17,6 +17,8 @@ use crate::shell::ShellType; use crate::tools::flat_tool_name; use crate::tools::network_approval::NetworkApprovalMode; use crate::tools::network_approval::NetworkApprovalSpec; +#[cfg(unix)] +use crate::tools::runtimes::apply_zsh_fork_path_prepend; use crate::tools::runtimes::build_sandbox_command; use crate::tools::runtimes::disable_powershell_profile_for_elevated_windows_sandbox; use crate::tools::runtimes::exec_env_for_sandbox_permissions; @@ -32,6 +34,7 @@ use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::ToolRuntime; use crate::tools::sandboxing::managed_network_for_sandbox_permissions; +use crate::tools::sandboxing::sandbox_permissions_preserving_denied_reads; use crate::tools::sandboxing::with_cached_approval; use crate::unified_exec::NoopSpawnLifecycle; use crate::unified_exec::UnifiedExecError; @@ -228,8 +231,13 @@ impl<'a> ToolRuntime for UnifiedExecRunt req: &UnifiedExecRequest, ctx: &ToolCtx, ) -> Option { + let file_system_sandbox_policy = ctx.turn.file_system_sandbox_policy(); + let sandbox_permissions = sandbox_permissions_preserving_denied_reads( + req.sandbox_permissions, + &file_system_sandbox_policy, + ); let network = - managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions)?; + managed_network_for_sandbox_permissions(req.network.as_ref(), sandbox_permissions)?; Some(NetworkApprovalSpec { network: Some(network.clone()), mode: NetworkApprovalMode::Deferred, @@ -255,12 +263,34 @@ impl<'a> ToolRuntime for UnifiedExecRunt ) -> Result { let base_command = &req.command; let session_shell = ctx.session.user_shell(); + let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions(); + let sandbox_permissions = sandbox_permissions_preserving_denied_reads( + req.sandbox_permissions, + &file_system_sandbox_policy, + ); + let req = &UnifiedExecRequest { + sandbox_permissions, + ..req.clone() + }; let managed_network = managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions); let mut env = exec_env_for_sandbox_permissions(&req.env, req.sandbox_permissions); if let Some(network) = managed_network { network.apply_to_env(&mut env); } + let explicit_env_overrides = req.explicit_env_overrides.clone(); + #[cfg(unix)] + let explicit_env_overrides = { + let mut explicit_env_overrides = explicit_env_overrides; + if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode { + apply_zsh_fork_path_prepend( + &mut env, + &mut explicit_env_overrides, + zsh_fork_config.shell_zsh_path.as_path(), + ); + } + explicit_env_overrides + }; let environment_is_remote = req.environment.is_remote(); let command = if environment_is_remote { base_command.to_vec() @@ -269,7 +299,7 @@ impl<'a> ToolRuntime for UnifiedExecRunt base_command, session_shell.as_ref(), &req.cwd, - &req.explicit_env_overrides, + &explicit_env_overrides, &env, ) }; diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 1ca589a5f9..598d8855af 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -248,6 +248,13 @@ pub(crate) fn sandbox_override_for_first_attempt( exec_approval_requirement: &ExecApprovalRequirement, file_system_sandbox_policy: &FileSystemSandboxPolicy, ) -> SandboxOverride { + // Deny-read restrictions are part of the active permission policy. Running + // without a filesystem sandbox would discard them, even if the command was + // otherwise approved by rules or explicit escalation. + if !unsandboxed_execution_allowed(file_system_sandbox_policy) { + return SandboxOverride::NoOverride; + } + // ExecPolicy `Allow` can intentionally imply full trust (Skip + bypass_sandbox=true), // which supersedes `with_additional_permissions` sandboxed execution hints. if matches!( @@ -260,12 +267,6 @@ pub(crate) fn sandbox_override_for_first_attempt( return SandboxOverride::BypassSandboxFirstAttempt; } - // Deny-read restrictions suppress explicit escalation because that path - // would otherwise discard the filesystem policy entirely. - if file_system_sandbox_policy.has_denied_read_restrictions() { - return SandboxOverride::NoOverride; - } - if sandbox_permissions.requires_escalated_permissions() { SandboxOverride::BypassSandboxFirstAttempt } else { @@ -273,6 +274,34 @@ pub(crate) fn sandbox_override_for_first_attempt( } } +/// Returns true when the active filesystem policy can be represented by +/// running without a filesystem sandbox. +/// +/// Denied reads only exist inside the sandbox. If a policy contains any +/// denied-read paths, bypassing the sandbox would silently grant those reads, +/// so escalation must keep the command sandboxed with the denied reads intact. +pub(crate) fn unsandboxed_execution_allowed( + file_system_sandbox_policy: &FileSystemSandboxPolicy, +) -> bool { + !file_system_sandbox_policy.has_denied_read_restrictions() +} + +pub(crate) fn sandbox_permissions_preserving_denied_reads( + sandbox_permissions: SandboxPermissions, + file_system_sandbox_policy: &FileSystemSandboxPolicy, +) -> SandboxPermissions { + if sandbox_permissions.requires_escalated_permissions() + && !unsandboxed_execution_allowed(file_system_sandbox_policy) + { + // `RequireEscalated` normally asks the executor to bypass the sandbox. + // When denied reads are active, that would drop the only mechanism that + // enforces them, so fall back to the default sandboxed attempt instead. + SandboxPermissions::UseDefault + } else { + sandbox_permissions + } +} + pub(crate) fn managed_network_for_sandbox_permissions( network: Option<&NetworkProxy>, sandbox_permissions: SandboxPermissions, @@ -383,6 +412,7 @@ pub(crate) struct SandboxAttempt<'a> { pub enforce_managed_network: bool, pub(crate) manager: &'a SandboxManager, pub(crate) sandbox_cwd: &'a AbsolutePathBuf, + pub(crate) workspace_roots: &'a [AbsolutePathBuf], pub codex_linux_sandbox_exe: Option<&'a std::path::PathBuf>, pub use_legacy_landlock: bool, pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel, @@ -422,6 +452,7 @@ impl<'a> SandboxAttempt<'a> { request, options, windows_sandbox_policy_cwd, + self.workspace_roots.to_vec(), ) }) } diff --git a/codex-rs/core/src/tools/sandboxing_tests.rs b/codex-rs/core/src/tools/sandboxing_tests.rs index f2e4c4cd64..21719e281f 100644 --- a/codex-rs/core/src/tools/sandboxing_tests.rs +++ b/codex-rs/core/src/tools/sandboxing_tests.rs @@ -138,7 +138,7 @@ fn guardian_bypasses_sandbox_for_explicit_escalation_on_first_attempt() { } #[test] -fn deny_read_blocks_explicit_escalation_but_preserves_policy_bypass() { +fn deny_read_blocks_explicit_escalation_and_policy_bypass() { let file_system_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::GlobPattern { pattern: "**/*.env".to_string(), @@ -158,6 +158,28 @@ fn deny_read_blocks_explicit_escalation_but_preserves_policy_bypass() { SandboxOverride::NoOverride, "explicit escalation would drop deny-read filesystem policy, so keep the first attempt sandboxed", ); + assert!(!unsandboxed_execution_allowed(&file_system_policy)); + assert_eq!( + sandbox_permissions_preserving_denied_reads( + SandboxPermissions::RequireEscalated, + &file_system_policy, + ), + SandboxPermissions::UseDefault, + ); + assert_eq!( + sandbox_permissions_preserving_denied_reads( + SandboxPermissions::WithAdditionalPermissions, + &file_system_policy, + ), + SandboxPermissions::WithAdditionalPermissions, + ); + assert_eq!( + sandbox_permissions_preserving_denied_reads( + SandboxPermissions::RequireEscalated, + &FileSystemSandboxPolicy::default(), + ), + SandboxPermissions::RequireEscalated, + ); assert_eq!( sandbox_override_for_first_attempt( SandboxPermissions::WithAdditionalPermissions, @@ -167,7 +189,7 @@ fn deny_read_blocks_explicit_escalation_but_preserves_policy_bypass() { }, &file_system_policy, ), - SandboxOverride::BypassSandboxFirstAttempt, - "exec-policy allow rules intentionally bypass sandbox even when deny-read entries exist", + SandboxOverride::NoOverride, + "exec-policy allow rules would drop deny-read filesystem policy, so keep the first attempt sandboxed", ); } diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 2610bee95c..9aaccbbd0f 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -60,6 +60,7 @@ use codex_mcp::ToolInfo; use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; +use codex_protocol::openai_models::ToolMode; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_tools::DiscoverableTool; @@ -85,6 +86,8 @@ use std::sync::Arc; use tracing::warn; const MULTI_AGENT_V2_NAMESPACE_DESCRIPTION: &str = "Tools for spawning and managing sub-agents."; +const IMAGE_GEN_NAMESPACE: &str = "image_gen"; +const IMAGEGEN_TOOL_NAME: &str = "imagegen"; type PlannedRuntime = Arc; @@ -228,8 +231,10 @@ fn spec_for_model_request( exposure: ToolExposure, spec: ToolSpec, ) -> ToolSpec { - if code_mode_enabled(turn_context) - && exposure != ToolExposure::DirectModelOnly + if matches!( + turn_context.tool_mode, + ToolMode::CodeMode | ToolMode::CodeModeOnly + ) && exposure != ToolExposure::DirectModelOnly && codex_code_mode::is_code_mode_nested_tool(spec.name()) { codex_tools::augment_tool_spec_for_code_mode(spec) @@ -257,7 +262,9 @@ fn hosted_model_tool_specs(context: &CoreToolPlanContext<'_>) -> Vec { }) { specs.push(web_search_tool); } - if image_generation_tool_enabled(turn_context) { + if image_generation_tool_enabled(turn_context) + && !standalone_image_generation_available(turn_context, context.extension_tool_executors) + { specs.push(create_image_generation_tool("png")); } specs @@ -278,14 +285,6 @@ fn namespace_tools_enabled(turn_context: &TurnContext) -> bool { turn_context.provider.capabilities().namespace_tools } -fn code_mode_enabled(turn_context: &TurnContext) -> bool { - turn_context.features.get().enabled(Feature::CodeMode) -} - -fn code_mode_only_enabled(turn_context: &TurnContext) -> bool { - code_mode_enabled(turn_context) && turn_context.features.get().enabled(Feature::CodeModeOnly) -} - fn multi_agent_v2_enabled(turn_context: &TurnContext) -> bool { turn_context.features.get().enabled(Feature::MultiAgentV2) } @@ -316,21 +315,41 @@ fn agent_jobs_worker_tools_enabled(turn_context: &TurnContext) -> bool { } fn image_generation_tool_enabled(turn_context: &TurnContext) -> bool { + image_generation_runtime_enabled(turn_context) + && turn_context + .features + .get() + .enabled(Feature::ImageGeneration) +} + +fn image_generation_runtime_enabled(turn_context: &TurnContext) -> bool { turn_context .auth_manager .as_deref() .is_some_and(AuthManager::current_auth_uses_codex_backend) && turn_context.provider.capabilities().image_generation - && turn_context - .features - .get() - .enabled(Feature::ImageGeneration) && turn_context .model_info .input_modalities .contains(&InputModality::Image) } +fn standalone_image_generation_model_visible(turn_context: &TurnContext) -> bool { + image_generation_runtime_enabled(turn_context) + && turn_context.features.get().enabled(Feature::ImageGenExt) + && namespace_tools_enabled(turn_context) +} + +fn standalone_image_generation_available( + turn_context: &TurnContext, + extension_tools: &[Arc>], +) -> bool { + standalone_image_generation_model_visible(turn_context) + && extension_tools.iter().any(|executor| { + executor.tool_name() == ToolName::namespaced(IMAGE_GEN_NAMESPACE, IMAGEGEN_TOOL_NAME) + }) +} + fn wait_agent_timeout_options(turn_context: &TurnContext) -> WaitAgentTimeoutOptions { if multi_agent_v2_enabled(turn_context) { return WaitAgentTimeoutOptions { @@ -374,7 +393,7 @@ fn is_hidden_by_code_mode_only( tool_name: &ToolName, exposure: ToolExposure, ) -> bool { - code_mode_only_enabled(turn_context) + turn_context.tool_mode == ToolMode::CodeModeOnly && exposure != ToolExposure::DirectModelOnly && codex_code_mode::is_code_mode_nested_tool(&codex_tools::code_mode_name_for_tool_name( tool_name, @@ -386,7 +405,10 @@ fn build_code_mode_executors( executors: &[Arc], deferred_tools_available: bool, ) -> Vec> { - if !code_mode_enabled(turn_context) { + if !matches!( + turn_context.tool_mode, + ToolMode::CodeMode | ToolMode::CodeModeOnly + ) { return vec![]; } @@ -420,7 +442,7 @@ fn build_code_mode_executors( create_code_mode_tool( &enabled_tools, &namespace_descriptions, - code_mode_only_enabled(turn_context), + turn_context.tool_mode == ToolMode::CodeModeOnly, deferred_tools_available, ), code_mode_nested_tool_specs, @@ -823,7 +845,10 @@ fn append_extension_tool_executors( .iter() .map(|executor| executor.tool_name()) .collect::>(); - if code_mode_enabled(turn_context) { + if matches!( + turn_context.tool_mode, + ToolMode::CodeMode | ToolMode::CodeModeOnly + ) { reserved_tool_names.insert(ToolName::plain(codex_code_mode::PUBLIC_TOOL_NAME)); reserved_tool_names.insert(ToolName::plain(codex_code_mode::WAIT_TOOL_NAME)); } @@ -839,6 +864,11 @@ fn append_extension_tool_executors( for executor in executors.iter().cloned() { let tool_name = executor.tool_name(); + if tool_name == ToolName::namespaced(IMAGE_GEN_NAMESPACE, IMAGEGEN_TOOL_NAME) + && !standalone_image_generation_model_visible(turn_context) + { + continue; + } if !reserved_tool_names.insert(tool_name.clone()) { warn!("Skipping extension tool `{tool_name}`: tool already registered"); continue; diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs index 94587803b8..e059b5f4af 100644 --- a/codex-rs/core/src/tools/spec_plan_tests.rs +++ b/codex-rs/core/src/tools/spec_plan_tests.rs @@ -13,6 +13,7 @@ use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::openai_models::ApplyPatchToolType; use codex_protocol::openai_models::ConfigShellToolType; use codex_protocol::openai_models::InputModality; +use codex_protocol::openai_models::ToolMode; use codex_protocol::openai_models::WebSearchToolType; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; @@ -215,6 +216,15 @@ fn set_feature(turn: &mut TurnContext, feature: Feature, enabled: bool) { .expect("test feature should be disableable in config"); } turn.config = Arc::new(config); + turn.tool_mode = turn.model_info.tool_mode.unwrap_or_else(|| { + if turn.config.features.enabled(Feature::CodeModeOnly) { + ToolMode::CodeModeOnly + } else if turn.config.features.enabled(Feature::CodeMode) { + ToolMode::CodeMode + } else { + ToolMode::Direct + } + }); } fn set_features(turn: &mut TurnContext, features: &[Feature]) { @@ -797,6 +807,20 @@ async fn multi_agent_feature_selects_one_agent_tool_family() { ); } +#[tokio::test] +async fn tool_mode_selector_overrides_feature_flags() { + let direct = probe(|turn| { + set_features(turn, &[Feature::CodeMode, Feature::CodeModeOnly]); + turn.model_info.tool_mode = Some(ToolMode::Direct); + turn.tool_mode = ToolMode::Direct; + }) + .await; + direct.assert_visible_lacks(&[ + codex_code_mode::PUBLIC_TOOL_NAME, + codex_code_mode::WAIT_TOOL_NAME, + ]); +} + #[tokio::test] async fn v1_multi_agent_tools_defer_when_tool_search_available() { let plan = probe(|turn| { @@ -960,6 +984,16 @@ async fn hosted_tools_follow_provider_auth_model_and_config_gates() { .await; image_generation.assert_visible_contains(&["image_generation"]); + let extension_flag_without_imagegen_tool = probe(|turn| { + use_chatgpt_auth(turn); + set_feature(turn, Feature::ImageGeneration, /*enabled*/ true); + set_feature(turn, Feature::ImageGenExt, /*enabled*/ true); + turn.model_info.input_modalities = vec![InputModality::Image]; + }) + .await; + extension_flag_without_imagegen_tool.assert_visible_contains(&["image_generation"]); + extension_flag_without_imagegen_tool.assert_visible_lacks(&["image_gen"]); + let live_web_search = probe(|turn| { set_web_search_mode(turn, WebSearchMode::Live); turn.model_info.web_search_tool_type = WebSearchToolType::TextAndImage; diff --git a/codex-rs/core/src/unified_exec/mod_tests.rs b/codex-rs/core/src/unified_exec/mod_tests.rs index d416be2e33..9f24314da2 100644 --- a/codex-rs/core/src/unified_exec/mod_tests.rs +++ b/codex-rs/core/src/unified_exec/mod_tests.rs @@ -67,6 +67,7 @@ fn test_exec_request( ExecExpiration::DefaultTimeout, ExecCapturePolicy::ShellTool, SandboxType::None, + turn.config.effective_workspace_roots(), turn.windows_sandbox_level, windows_sandbox_private_desktop, permission_profile, diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 08cd92ba53..83c750ebc4 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -897,7 +897,7 @@ impl UnifiedExecProcessManager { codex_protocol::config_types::WindowsSandboxLevel::Elevated => { codex_windows_sandbox::spawn_windows_sandbox_session_elevated_for_permission_profile( &request.permission_profile, - request.windows_sandbox_policy_cwd.as_path(), + request.windows_sandbox_workspace_roots.as_slice(), codex_home.as_ref(), request.command.clone(), request.cwd.as_path(), @@ -918,7 +918,7 @@ impl UnifiedExecProcessManager { | codex_protocol::config_types::WindowsSandboxLevel::Disabled => { codex_windows_sandbox::spawn_windows_sandbox_session_legacy( &request.permission_profile, - request.windows_sandbox_policy_cwd.as_path(), + request.windows_sandbox_workspace_roots.as_slice(), codex_home.as_ref(), request.command.clone(), request.cwd.as_path(), diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index cd83ce7a9c..4d0597a844 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -100,7 +100,8 @@ fn exec_server_params_use_env_policy_overlay_contract() { expiration: crate::exec::ExecExpiration::DefaultTimeout, capture_policy: crate::exec::ExecCapturePolicy::ShellTool, sandbox: codex_sandboxing::SandboxType::None, - windows_sandbox_policy_cwd: cwd, + windows_sandbox_policy_cwd: cwd.clone(), + windows_sandbox_workspace_roots: vec![cwd], windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled, windows_sandbox_private_desktop: false, permission_profile, diff --git a/codex-rs/core/src/windows_sandbox.rs b/codex-rs/core/src/windows_sandbox.rs index b2ac8bf1f0..a1ff5dda09 100644 --- a/codex-rs/core/src/windows_sandbox.rs +++ b/codex-rs/core/src/windows_sandbox.rs @@ -9,6 +9,7 @@ use codex_login::default_client::originator; use codex_otel::sanitize_metric_tag_value; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::BTreeMap; use std::collections::HashMap; use std::path::Path; @@ -146,15 +147,15 @@ pub fn elevated_setup_failure_metric_name(_err: &anyhow::Error) -> &'static str #[cfg(target_os = "windows")] pub fn run_elevated_setup( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, ) -> anyhow::Result<()> { let permissions = - codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( permission_profile, - permission_profile_cwd, + workspace_roots, )?; codex_windows_sandbox::run_elevated_setup( codex_windows_sandbox::SandboxSetupRequest { @@ -168,10 +169,15 @@ pub fn run_elevated_setup( ) } +#[cfg(target_os = "windows")] +pub fn run_elevated_provisioning_setup(codex_home: &Path, real_user: &str) -> anyhow::Result<()> { + codex_windows_sandbox::run_elevated_provisioning_setup(codex_home, real_user) +} + #[cfg(not(target_os = "windows"))] pub fn run_elevated_setup( _permission_profile: &PermissionProfile, - _permission_profile_cwd: &Path, + _workspace_roots: &[AbsolutePathBuf], _command_cwd: &Path, _env_map: &HashMap, _codex_home: &Path, @@ -179,17 +185,22 @@ pub fn run_elevated_setup( anyhow::bail!("elevated Windows sandbox setup is only supported on Windows") } +#[cfg(not(target_os = "windows"))] +pub fn run_elevated_provisioning_setup(_codex_home: &Path, _real_user: &str) -> anyhow::Result<()> { + anyhow::bail!("elevated Windows sandbox setup is only supported on Windows") +} + #[cfg(target_os = "windows")] pub fn run_legacy_setup_preflight( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, ) -> anyhow::Result<()> { codex_windows_sandbox::run_windows_sandbox_legacy_preflight( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, command_cwd, env_map, @@ -199,7 +210,7 @@ pub fn run_legacy_setup_preflight( #[cfg(target_os = "windows")] pub fn run_setup_refresh_with_extra_read_roots( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, @@ -207,7 +218,7 @@ pub fn run_setup_refresh_with_extra_read_roots( ) -> anyhow::Result<()> { codex_windows_sandbox::run_setup_refresh_with_extra_read_roots( permission_profile, - permission_profile_cwd, + workspace_roots, command_cwd, env_map, codex_home, @@ -219,7 +230,7 @@ pub fn run_setup_refresh_with_extra_read_roots( #[cfg(not(target_os = "windows"))] pub fn run_legacy_setup_preflight( _permission_profile: &PermissionProfile, - _permission_profile_cwd: &Path, + _workspace_roots: &[AbsolutePathBuf], _command_cwd: &Path, _env_map: &HashMap, _codex_home: &Path, @@ -230,7 +241,7 @@ pub fn run_legacy_setup_preflight( #[cfg(not(target_os = "windows"))] pub fn run_setup_refresh_with_extra_read_roots( _permission_profile: &PermissionProfile, - _permission_profile_cwd: &Path, + _workspace_roots: &[AbsolutePathBuf], _command_cwd: &Path, _env_map: &HashMap, _codex_home: &Path, @@ -249,7 +260,7 @@ pub enum WindowsSandboxSetupMode { pub struct WindowsSandboxSetupRequest { pub mode: WindowsSandboxSetupMode, pub permission_profile: PermissionProfile, - pub permission_profile_cwd: PathBuf, + pub workspace_roots: Vec, pub command_cwd: PathBuf, pub env_map: HashMap, pub codex_home: PathBuf, @@ -287,7 +298,7 @@ async fn run_windows_sandbox_setup_and_persist( ) -> anyhow::Result<()> { let mode = request.mode; let permission_profile = request.permission_profile; - let permission_profile_cwd = request.permission_profile_cwd; + let workspace_roots = request.workspace_roots; let command_cwd = request.command_cwd; let env_map = request.env_map; let codex_home = request.codex_home; @@ -299,7 +310,7 @@ async fn run_windows_sandbox_setup_and_persist( if !sandbox_setup_is_complete(setup_codex_home.as_path()) { run_elevated_setup( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &env_map, setup_codex_home.as_path(), @@ -309,7 +320,7 @@ async fn run_windows_sandbox_setup_and_persist( WindowsSandboxSetupMode::Unelevated => { run_legacy_setup_preflight( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &env_map, setup_codex_home.as_path(), diff --git a/codex-rs/core/src/windows_sandbox_read_grants.rs b/codex-rs/core/src/windows_sandbox_read_grants.rs index a9561372ce..af87b6e6bc 100644 --- a/codex-rs/core/src/windows_sandbox_read_grants.rs +++ b/codex-rs/core/src/windows_sandbox_read_grants.rs @@ -1,13 +1,14 @@ use crate::windows_sandbox::run_setup_refresh_with_extra_read_roots; use anyhow::Result; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; pub fn grant_read_root_non_elevated( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, @@ -26,7 +27,7 @@ pub fn grant_read_root_non_elevated( let canonical_root = dunce::canonicalize(read_root)?; run_setup_refresh_with_extra_read_roots( permission_profile, - permission_profile_cwd, + workspace_roots, command_cwd, env_map, codex_home, diff --git a/codex-rs/core/src/windows_sandbox_read_grants_tests.rs b/codex-rs/core/src/windows_sandbox_read_grants_tests.rs index 93cbcddfe3..cc714f38c5 100644 --- a/codex-rs/core/src/windows_sandbox_read_grants_tests.rs +++ b/codex-rs/core/src/windows_sandbox_read_grants_tests.rs @@ -1,19 +1,21 @@ use super::grant_read_root_non_elevated; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::path::Path; use tempfile::TempDir; -fn permission_profile() -> PermissionProfile { - PermissionProfile::workspace_write() +fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] } #[test] fn rejects_relative_path() { let tmp = TempDir::new().expect("tempdir"); + let workspace_roots = workspace_roots_for(tmp.path()); let err = grant_read_root_non_elevated( - &permission_profile(), - tmp.path(), + &PermissionProfile::workspace_write(), + workspace_roots.as_slice(), tmp.path(), &HashMap::new(), tmp.path(), @@ -27,9 +29,10 @@ fn rejects_relative_path() { fn rejects_missing_path() { let tmp = TempDir::new().expect("tempdir"); let missing = tmp.path().join("does-not-exist"); + let workspace_roots = workspace_roots_for(tmp.path()); let err = grant_read_root_non_elevated( - &permission_profile(), - tmp.path(), + &PermissionProfile::workspace_write(), + workspace_roots.as_slice(), tmp.path(), &HashMap::new(), tmp.path(), @@ -44,9 +47,10 @@ fn rejects_file_path() { let tmp = TempDir::new().expect("tempdir"); let file_path = tmp.path().join("file.txt"); std::fs::write(&file_path, "hello").expect("write file"); + let workspace_roots = workspace_roots_for(tmp.path()); let err = grant_read_root_non_elevated( - &permission_profile(), - tmp.path(), + &PermissionProfile::workspace_write(), + workspace_roots.as_slice(), tmp.path(), &HashMap::new(), tmp.path(), diff --git a/codex-rs/core/tests/common/apps_test_server.rs b/codex-rs/core/tests/common/apps_test_server.rs index 2f2875867b..7f7873e30b 100644 --- a/codex-rs/core/tests/common/apps_test_server.rs +++ b/codex-rs/core/tests/common/apps_test_server.rs @@ -27,12 +27,15 @@ const SERVER_NAME: &str = "codex-apps-test"; const SERVER_VERSION: &str = "1.0.0"; const SEARCHABLE_TOOL_COUNT: usize = 100; const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event"; +const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action"; pub const CALENDAR_EXTRACT_TEXT_TOOL_NAME: &str = "calendar_extract_text"; const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events"; pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__codex_apps__calendar__create_event"; +pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__codex_apps__calendar__app_only_action"; pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__codex_apps__calendar__list_events"; pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__codex_apps__calendar__extract_text"; pub const SEARCH_CALENDAR_NAMESPACE: &str = "mcp__codex_apps__calendar"; +pub const SEARCH_CALENDAR_APP_ONLY_TOOL: &str = "_app_only_action"; pub const SEARCH_CALENDAR_CREATE_TOOL: &str = "_create_event"; pub const SEARCH_CALENDAR_EXTRACT_TEXT_TOOL: &str = "_extract_text"; pub const SEARCH_CALENDAR_LIST_TOOL: &str = "_list_events"; @@ -49,6 +52,12 @@ pub struct AppsTestServer { pub chatgpt_base_url: String, } +#[derive(Clone, Copy)] +pub enum AppsTestToolLoading { + Direct, + Searchable, +} + impl AppsTestServer { pub async fn mount(server: &MockServer) -> Result { Self::mount_with_connector_name(server, CONNECTOR_NAME).await @@ -62,6 +71,7 @@ impl AppsTestServer { CONNECTOR_NAME.to_string(), CONNECTOR_DESCRIPTION.to_string(), /*searchable*/ true, + /*include_app_only_tool*/ false, ) .await; Ok(Self { @@ -80,6 +90,26 @@ impl AppsTestServer { connector_name.to_string(), CONNECTOR_DESCRIPTION.to_string(), /*searchable*/ false, + /*include_app_only_tool*/ false, + ) + .await; + Ok(Self { + chatgpt_base_url: server.uri(), + }) + } + + pub async fn mount_with_app_only_tool( + server: &MockServer, + tool_loading: AppsTestToolLoading, + ) -> Result { + mount_oauth_metadata(server).await; + mount_connectors_directory(server).await; + mount_streamable_http_json_rpc( + server, + CONNECTOR_NAME.to_string(), + CONNECTOR_DESCRIPTION.to_string(), + matches!(tool_loading, AppsTestToolLoading::Searchable), + /*include_app_only_tool*/ true, ) .await; Ok(Self { @@ -136,7 +166,7 @@ fn apps_tool_call_id(body: &Value) -> Option<&str> { .as_str() } -async fn recorded_apps_tool_calls(server: &MockServer) -> Vec { +pub async fn recorded_apps_tool_calls(server: &MockServer) -> Vec { server .received_requests() .await @@ -233,6 +263,7 @@ async fn mount_streamable_http_json_rpc( connector_name: String, connector_description: String, searchable: bool, + include_app_only_tool: bool, ) { Mock::given(method("POST")) .and(path_regex("^/api/codex/apps/?$")) @@ -240,6 +271,7 @@ async fn mount_streamable_http_json_rpc( connector_name, connector_description, searchable, + include_app_only_tool, }) .mount(server) .await; @@ -249,6 +281,7 @@ struct CodexAppsJsonRpcResponder { connector_name: String, connector_description: String, searchable: bool, + include_app_only_tool: bool, } impl Respond for CodexAppsJsonRpcResponder { @@ -419,6 +452,29 @@ impl Respond for CodexAppsJsonRpcResponder { })); } } + if self.include_app_only_tool + && let Some(tools) = response + .pointer_mut("/result/tools") + .and_then(Value::as_array_mut) + { + tools.push(json!({ + "name": CALENDAR_APP_ONLY_TOOL_NAME, + "description": "Open a calendar app-only action.", + "inputSchema": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "_meta": { + "connector_id": CONNECTOR_ID, + "connector_name": self.connector_name.clone(), + "connector_description": self.connector_description.clone(), + "ui": { + "visibility": ["app"] + } + } + })); + } ResponseTemplate::new(200).set_body_json(response) } "tools/call" => { diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 194fb2ae0a..3d7fd21228 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -248,6 +248,39 @@ where wait_for_event_with_timeout(codex, predicate, Duration::from_secs(1)).await } +/// Waits for a configured MCP server to finish startup and requires it to be ready. +pub async fn wait_for_mcp_server(codex: &CodexThread, server_name: &str) -> anyhow::Result<()> { + use codex_protocol::protocol::EventMsg; + + // Wait for the startup summary regardless of outcome, then interpret the + // requested server's ready, failed, or cancelled entry below. + let summary = loop { + let event = codex + .next_event() + .await + .expect("stream ended unexpectedly while waiting for MCP startup"); + if let EventMsg::McpStartupComplete(summary) = event.msg { + break summary; + } + }; + if let Some(failure) = summary + .failed + .iter() + .find(|failure| failure.server == server_name) + { + let error = &failure.error; + anyhow::bail!("MCP server {server_name} failed to start: {error}"); + } + if summary.cancelled.iter().any(|server| server == server_name) { + anyhow::bail!("MCP server {server_name} startup was cancelled"); + } + assert!( + summary.ready.iter().any(|server| server == server_name), + "expected MCP server {server_name} to be ready; startup summary: {summary:?}" + ); + Ok(()) +} + pub async fn submit_thread_settings( codex: &CodexThread, thread_settings: codex_protocol::protocol::ThreadSettingsOverrides, diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index e16a4a14a2..a91196a0b9 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -10,6 +10,12 @@ use codex_features::Feature; use codex_protocol::approvals::NetworkApprovalProtocol; use codex_protocol::approvals::NetworkPolicyAmendment; use codex_protocol::approvals::NetworkPolicyRuleAction; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; @@ -46,6 +52,8 @@ use serde_json::Value; use serde_json::json; use std::env; use std::fs; +#[cfg(unix)] +use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -2528,6 +2536,166 @@ async fn spawned_subagent_execpolicy_amendment_propagates_to_parent_session() -> Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg(unix)] +async fn env_zsh_script_spawned_by_python_can_request_escalation_under_zsh_fork() -> Result<()> { + skip_if_no_network!(Ok(())); + + let Some(runtime) = zsh_fork_runtime("zsh-fork env zsh nested escalation test")? else { + return Ok(()); + }; + + let approval_policy = AskForApproval::OnRequest; + let permission_profile = restrictive_workspace_write_profile(); + let outside_dir = tempfile::tempdir_in(std::env::current_dir()?)?; + let outside_path = outside_dir.path().join("zsh-fork-env-zsh-escalated.txt"); + let outside_path_arg = shlex::try_join([outside_path.to_string_lossy().as_ref()])?; + let rules = r#"prefix_rule(pattern=["touch"], decision="prompt")"#.to_string(); + + let server = start_mock_server().await; + let outside_path_for_hook = outside_path.clone(); + let test = build_zsh_fork_test( + &server, + runtime, + approval_policy, + permission_profile.clone(), + move |home| { + let _ = fs::remove_file(&outside_path_for_hook); + let rules_dir = home.join("rules"); + fs::create_dir_all(&rules_dir).unwrap(); + fs::write(rules_dir.join("default.rules"), &rules).unwrap(); + }, + ) + .await?; + + let script_path = test.cwd.path().join("runs-under-env-zsh"); + fs::write( + &script_path, + format!( + "#!/usr/bin/env zsh\ntouch {outside_path_arg}\nprint -r -- nested-env-zsh-complete\n" + ), + )?; + let mut script_permissions = fs::metadata(&script_path)?.permissions(); + script_permissions.set_mode(0o755); + fs::set_permissions(&script_path, script_permissions)?; + + let script_literal = serde_json::to_string(script_path.to_string_lossy().as_ref())?; + let python_script = format!( + "import subprocess; subprocess.run([{script_literal}], check=True, close_fds=False)" + ); + let command = shlex::try_join(["python3", "-c", python_script.as_str()])?; + + let call_id = "zsh-fork-env-zsh-nested-escalation"; + let event = shell_event( + call_id, + &command, + /*timeout_ms*/ 30_000, + SandboxPermissions::UseDefault, + )?; + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-zsh-fork-env-zsh-1"), + event, + ev_completed("resp-zsh-fork-env-zsh-1"), + ]), + ) + .await; + let results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-zsh-fork-env-zsh-1", "done"), + ev_completed("resp-zsh-fork-env-zsh-2"), + ]), + ) + .await; + + let session_model = test.session_configured.model.clone(); + let (sandbox_policy, permission_profile) = + turn_permission_fields(permission_profile, test.cwd.path()); + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "run nested env zsh script through python".into(), + text_elements: Vec::new(), + }], + environments: None, + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: codex_protocol::protocol::ThreadSettingsOverrides { + cwd: Some(test.cwd.path().to_path_buf()), + approval_policy: Some(approval_policy), + approvals_reviewer: Some(ApprovalsReviewer::User), + sandbox_policy: Some(sandbox_policy), + permission_profile, + collaboration_mode: Some(codex_protocol::config_types::CollaborationMode { + mode: codex_protocol::config_types::ModeKind::Default, + settings: codex_protocol::config_types::Settings { + model: session_model, + reasoning_effort: None, + developer_instructions: None, + }, + }), + ..Default::default() + }, + }) + .await?; + + let approval_event = wait_for_event_with_timeout( + &test.codex, + |event| { + matches!( + event, + EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_) + ) + }, + Duration::from_secs(10), + ) + .await; + let EventMsg::ExecApprovalRequest(approval) = approval_event else { + panic!("expected nested zsh script to request approval before completion"); + }; + assert!( + approval.command.iter().any(|arg| arg.ends_with("/touch")) + && approval + .command + .iter() + .any(|arg| arg == outside_path.to_string_lossy().as_ref()), + "expected approval for nested touch command, got: {:?}", + approval.command + ); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::Approved, + }) + .await?; + + wait_for_completion(&test).await; + + let result = parse_result(&results.single_request().function_call_output(call_id)); + assert_eq!( + result.exit_code.unwrap_or(0), + 0, + "nested env zsh script should complete successfully: {}", + result.stdout + ); + assert!( + result.stdout.contains("nested-env-zsh-complete"), + "nested script did not report completion: {}", + result.stdout + ); + assert!( + outside_path.exists(), + "approved nested touch should create the out-of-workspace file" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[cfg(unix)] async fn matched_prefix_rule_runs_unsandboxed_under_zsh_fork() -> Result<()> { @@ -3082,6 +3250,212 @@ allow_local_binding = true Ok(()) } +#[cfg(not(target_os = "windows"))] +#[tokio::test(flavor = "current_thread")] +async fn network_approval_retry_keeps_deny_read_sandbox_for_escalated_command() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let home = Arc::new(TempDir::new()?); + fs::write( + home.path().join("config.toml"), + r#"default_permissions = "workspace" + +[permissions.workspace.filesystem] +":minimal" = "read" + +[permissions.workspace.network] +enabled = true +mode = "limited" +allow_local_binding = true +"#, + )?; + let approval_policy = AskForApproval::OnRequest; + let sandbox_policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + network_access: true, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + let mut builder = test_codex() + .with_home(home) + .with_cloud_requirements(managed_network_requirements_loader()) + .with_config(move |config| { + config.permissions.approval_policy = Constrained::allow_any(approval_policy); + }); + let test = builder.build(&server).await?; + assert!( + test.config.managed_network_requirements_enabled(), + "expected managed network requirements to be enabled" + ); + assert!( + test.config.permissions.network.is_some(), + "expected managed network proxy config to be present" + ); + test.session_configured + .network_proxy + .as_ref() + .expect("expected runtime managed network proxy addresses"); + + let mut file_system_sandbox_policy = + FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd( + &sandbox_policy, + test.config.cwd.as_path(), + ); + file_system_sandbox_policy + .entries + .push(FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: format!("{}/**/*.env", test.config.cwd.as_path().display()), + }, + access: FileSystemAccessMode::Deny, + }); + assert!( + file_system_sandbox_policy.has_denied_read_restrictions(), + "test must exercise a permission profile with denied reads" + ); + let permission_profile = PermissionProfile::from_runtime_permissions( + &file_system_sandbox_policy, + NetworkSandboxPolicy::Restricted, + ); + + let call_id = "deny-read-network-retry"; + let fetch_command = r#"python3 -c "import urllib.request; opener = urllib.request.build_opener(urllib.request.ProxyHandler()); print('OK:' + opener.open('http://codex-network-test.invalid', timeout=30).read().decode(errors='replace'))""# + .to_string(); + let event = shell_event( + call_id, + &fetch_command, + /*timeout_ms*/ 30_000, + SandboxPermissions::RequireEscalated, + )?; + + let _ = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-deny-read-network-1"), + event, + ev_completed("resp-deny-read-network-1"), + ]), + ) + .await; + let results = mount_sse_once( + &server, + sse(vec![ + ev_assistant_message("msg-deny-read-network-1", "done"), + ev_completed("resp-deny-read-network-2"), + ]), + ) + .await; + + let (turn_sandbox_policy, turn_permission_profile) = + turn_permission_fields(permission_profile, test.config.cwd.as_path()); + let session_model = test.session_configured.model.clone(); + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "deny-read network retry".into(), + text_elements: Vec::new(), + }], + environments: None, + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: codex_protocol::protocol::ThreadSettingsOverrides { + cwd: Some(test.config.cwd.to_path_buf()), + approval_policy: Some(approval_policy), + approvals_reviewer: Some(ApprovalsReviewer::User), + sandbox_policy: Some(turn_sandbox_policy), + permission_profile: turn_permission_profile, + collaboration_mode: Some(codex_protocol::config_types::CollaborationMode { + mode: codex_protocol::config_types::ModeKind::Default, + settings: codex_protocol::config_types::Settings { + model: session_model, + reasoning_effort: None, + developer_instructions: None, + }, + }), + ..Default::default() + }, + }) + .await?; + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + let mut command_approval_count = 0; + let approval = loop { + let remaining = deadline + .checked_duration_since(std::time::Instant::now()) + .expect("timed out waiting for network approval request"); + let event = wait_for_event_with_timeout( + &test.codex, + |event| { + matches!( + event, + EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_) + ) + }, + remaining, + ) + .await; + match event { + EventMsg::ExecApprovalRequest(approval) => { + if approval.command.first().map(std::string::String::as_str) + == Some("network-access") + { + break approval; + } + command_approval_count += 1; + assert_eq!( + command_approval_count, 1, + "expected only the outer explicit escalation approval" + ); + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::Approved, + }) + .await?; + } + EventMsg::TurnComplete(_) => { + panic!("expected network approval request before completion"); + } + other => panic!("unexpected event: {other:?}"), + } + }; + assert_eq!(command_approval_count, 1); + let network_context = approval + .network_approval_context + .clone() + .expect("expected network approval context"); + assert_eq!(network_context.protocol, NetworkApprovalProtocol::Http); + let allow_network_amendment = approval + .proposed_network_policy_amendments + .clone() + .expect("expected proposed network policy amendments") + .into_iter() + .find(|amendment| amendment.action == NetworkPolicyRuleAction::Allow) + .expect("expected allow network policy amendment"); + + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: None, + decision: ReviewDecision::NetworkPolicyAmendment { + network_policy_amendment: allow_network_amendment, + }, + }) + .await?; + wait_for_completion(&test).await; + + let output = parse_result(&results.single_request().function_call_output(call_id)); + assert!( + output.exit_code.is_some(), + "expected the approved retry to report command output" + ); + + Ok(()) +} + #[tokio::test(flavor = "current_thread")] async fn network_approval_flow_survives_danger_full_access_session_start() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/code_mode.rs b/codex-rs/core/tests/suite/code_mode.rs index 90daf21963..9881869313 100644 --- a/codex-rs/core/tests/suite/code_mode.rs +++ b/codex-rs/core/tests/suite/code_mode.rs @@ -18,6 +18,10 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::apps_test_server::AppsTestToolLoading; +use core_test_support::apps_test_server::DIRECT_CALENDAR_APP_ONLY_TOOL; +use core_test_support::apps_test_server::recorded_apps_tool_calls; +use core_test_support::apps_test_server::search_capable_apps_builder; use core_test_support::assert_regex_match; use core_test_support::responses; use core_test_support::responses::ResponseMock; @@ -34,6 +38,7 @@ use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; +use core_test_support::wait_for_mcp_server; use pretty_assertions::assert_eq; use serde_json::Value; use std::collections::HashMap; @@ -279,6 +284,7 @@ async fn run_code_mode_turn_with_rmcp_config( .expect("test mcp servers should accept any configuration"); }); let test = builder.build(server).await?; + wait_for_mcp_server(&test.codex, "rmcp").await?; responses::mount_sse_once( server, @@ -495,6 +501,92 @@ if (!tool) { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn app_only_tools_are_not_visible_or_runnable_by_code_mode_model() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = responses::start_mock_server().await; + let apps_server = + AppsTestServer::mount_with_app_only_tool(&server, AppsTestToolLoading::Searchable).await?; + let code = format!( + r#" +const visibleTool = ALL_TOOLS.find(({{ name }}) => name === {visible_tool_name:?}); +const tool = ALL_TOOLS.find(({{ name }}) => name === {tool_name:?}); +let error = null; +try {{ + await tools[{tool_name:?}]({{}}); +}} catch (caught) {{ + error = String(caught); +}} +text(JSON.stringify({{ + visibleListed: visibleTool !== undefined, + listed: tool !== undefined, + callable: typeof tools[{tool_name:?}] === "function", + error, +}})); +"#, + visible_tool_name = "mcp__codex_apps__calendar_timezone_option_99", + tool_name = DIRECT_CALENDAR_APP_ONLY_TOOL, + ); + + responses::mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_custom_tool_call("call-1", "exec", &code), + 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; + + let mut builder = search_capable_apps_builder(apps_server.chatgpt_base_url.clone()) + .with_config(|config| { + config + .features + .enable(Feature::CodeMode) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::CodeModeOnly) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + test.submit_turn("try to call the app-only calendar tool through exec") + .await?; + + let req = second_mock.single_request(); + let (output, success) = custom_tool_output_body_and_success(&req, "call-1"); + assert_ne!( + success, + Some(false), + "code mode visibility check should complete successfully: {output}" + ); + let parsed: Value = serde_json::from_str(&output)?; + assert_eq!(parsed["visibleListed"], true); + assert_eq!(parsed["listed"], false); + assert_eq!(parsed["callable"], false); + assert!( + parsed["error"] + .as_str() + .is_some_and(|error| error.contains("is not a function")), + "app-only code mode call should fail before MCP dispatch: {parsed:?}" + ); + assert!( + recorded_apps_tool_calls(&server).await.is_empty(), + "app-only code mode call should not reach the MCP server" + ); + + Ok(()) +} + #[cfg_attr(windows, ignore = "no exec_command on Windows")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn code_mode_only_can_call_nested_tools() -> Result<()> { diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index 923d223e13..d3ee658719 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -53,6 +53,7 @@ where params, &PermissionProfile::read_only(), &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/core/tests/suite/hooks_mcp.rs b/codex-rs/core/tests/suite/hooks_mcp.rs index 940db7cf4c..00f1546a7c 100644 --- a/codex-rs/core/tests/suite/hooks_mcp.rs +++ b/codex-rs/core/tests/suite/hooks_mcp.rs @@ -22,6 +22,7 @@ use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::stdio_server_bin; use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_mcp_server; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; @@ -284,6 +285,7 @@ async fn pre_tool_use_blocks_mcp_tool_before_execution( }) .build(&server) .await?; + wait_for_mcp_server(&test.codex, RMCP_SERVER).await?; test.submit_turn("call the rmcp echo tool with the MCP pre hook") .await?; @@ -375,6 +377,7 @@ async fn pre_tool_use_rewrites_mcp_tool_before_execution() -> Result<()> { }) .build(&server) .await?; + wait_for_mcp_server(&test.codex, RMCP_SERVER).await?; test.submit_turn("call the rmcp echo tool with the MCP pre hook rewrite") .await?; @@ -471,6 +474,7 @@ async fn post_tool_use_records_mcp_tool_payload_and_context( }) .build(&server) .await?; + wait_for_mcp_server(&test.codex, RMCP_SERVER).await?; test.submit_turn("call the rmcp echo tool with the MCP post hook") .await?; diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index f4ab6c1d6d..51a5bea57f 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -63,6 +63,7 @@ mod json_result; mod live_cli; mod mcp_turn_metadata; mod model_overrides; +mod model_runtime_selectors; mod model_switching; mod model_visible_layout; mod models_cache_ttl; diff --git a/codex-rs/core/tests/suite/model_runtime_selectors.rs b/codex-rs/core/tests/suite/model_runtime_selectors.rs new file mode 100644 index 0000000000..b6f2ea3c7d --- /dev/null +++ b/codex-rs/core/tests/suite/model_runtime_selectors.rs @@ -0,0 +1,173 @@ +use anyhow::Result; +use codex_core::config::Config; +use codex_features::Feature; +use codex_login::CodexAuth; +use codex_models_manager::manager::RefreshStrategy; +use codex_models_manager::manager::SharedModelsManager; +use codex_models_manager::model_info::model_info_from_slug; +use codex_protocol::openai_models::ModelInfo; +use codex_protocol::openai_models::ModelPreset; +use codex_protocol::openai_models::ModelVisibility; +use codex_protocol::openai_models::ModelsResponse; +use codex_protocol::openai_models::ToolMode; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ThreadSettingsOverrides; +use codex_protocol::user_input::UserInput; +use core_test_support::responses; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_models_once; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::sse; +use core_test_support::skip_if_no_network; +use core_test_support::submit_thread_settings; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event; +use pretty_assertions::assert_eq; +use serde_json::Value; +use tokio::time::Duration; +use tokio::time::Instant; +use tokio::time::sleep; + +fn remote_model(slug: &str) -> ModelInfo { + ModelInfo { + visibility: ModelVisibility::List, + used_fallback_model_metadata: false, + ..model_info_from_slug(slug) + } +} + +fn tool_names(body: &Value) -> Vec { + body.get("tools") + .and_then(Value::as_array) + .map(|tools| { + tools + .iter() + .filter_map(|tool| { + tool.get("name") + .or_else(|| tool.get("type")) + .and_then(Value::as_str) + .map(str::to_string) + }) + .collect() + }) + .unwrap_or_default() +} + +async fn wait_for_model_available(manager: &SharedModelsManager, slug: &str) -> ModelPreset { + let deadline = Instant::now() + Duration::from_secs(2); + loop { + if let Some(model) = manager + .list_models(RefreshStrategy::Online) + .await + .iter() + .find(|model| model.model == slug) + .cloned() + { + return model; + } + if Instant::now() >= deadline { + panic!("timed out waiting for the remote model {slug} to appear"); + } + sleep(Duration::from_millis(25)).await; + } +} + +async fn response_body_for_remote_model( + remote_model: ModelInfo, + configure: impl FnOnce(&mut Config) + Send + 'static, +) -> Result { + let server = responses::start_mock_server().await; + let model_slug = remote_model.slug.clone(); + let models_mock = mount_models_once( + &server, + ModelsResponse { + models: vec![remote_model], + }, + ) + .await; + let response_mock = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-1"), + ]), + ) + .await; + + let mut builder = test_codex() + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(configure); + let test = builder.build(&server).await?; + let models_manager = test.thread_manager.get_models_manager(); + let available_model = wait_for_model_available(&models_manager, &model_slug).await; + assert_eq!(available_model.model, model_slug); + assert_eq!(models_mock.requests().len(), 1); + + submit_thread_settings( + &test.codex, + ThreadSettingsOverrides { + model: Some(model_slug), + ..Default::default() + }, + ) + .await?; + test.codex + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: "list tools".into(), + text_elements: Vec::new(), + }], + environments: None, + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + Ok(response_mock.single_request().body_json()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_tool_mode_selector_overrides_feature_flags() -> Result<()> { + skip_if_no_network!(Ok(())); + + let mut direct_model = remote_model("test-tool-mode-direct"); + direct_model.tool_mode = Some(ToolMode::Direct); + let direct_body = response_body_for_remote_model(direct_model, |config| { + config + .features + .enable(Feature::CodeModeOnly) + .expect("test config should allow feature update"); + }) + .await?; + let direct_tools = tool_names(&direct_body); + assert!( + direct_tools + .iter() + .all(|name| name != codex_code_mode::PUBLIC_TOOL_NAME + && name != codex_code_mode::WAIT_TOOL_NAME), + "direct mode should override enabled code mode flags: {direct_tools:?}" + ); + + let mut code_mode_only_model = remote_model("test-tool-mode-code-mode-only"); + code_mode_only_model.tool_mode = Some(ToolMode::CodeModeOnly); + let code_mode_only_body = response_body_for_remote_model(code_mode_only_model, |_| {}).await?; + assert_eq!( + tool_names(&code_mode_only_body), + vec![ + codex_code_mode::PUBLIC_TOOL_NAME.to_string(), + codex_code_mode::WAIT_TOOL_NAME.to_string(), + ] + ); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index 3c4dd40b32..90bb741f05 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -112,6 +112,7 @@ fn test_model_info( input_modalities, used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), @@ -929,6 +930,7 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index fcd90cbaea..76ebb4529c 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -370,5 +370,6 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, } } diff --git a/codex-rs/core/tests/suite/pending_input.rs b/codex-rs/core/tests/suite/pending_input.rs index c8eec9bc8e..96b89caec8 100644 --- a/codex-rs/core/tests/suite/pending_input.rs +++ b/codex-rs/core/tests/suite/pending_input.rs @@ -152,6 +152,7 @@ async fn steer_user_input(codex: &CodexThread, text: &str) { }], /*additional_context*/ Default::default(), /*expected_turn_id*/ None, + /*client_user_message_id*/ None, /*responsesapi_client_metadata*/ None, ) .await diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index 06781dc11d..4cb8b63a09 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -592,6 +592,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, }; let _models_mock = mount_models_once( @@ -702,6 +703,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, }; let _models_mock = mount_models_once( diff --git a/codex-rs/core/tests/suite/personality_migration.rs b/codex-rs/core/tests/suite/personality_migration.rs index 7c9183f8d9..9cee89d761 100644 --- a/codex-rs/core/tests/suite/personality_migration.rs +++ b/codex-rs/core/tests/suite/personality_migration.rs @@ -84,6 +84,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R let user_event = RolloutLine { timestamp: TEST_TIMESTAMP.to_string(), item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index b89b611a83..d7d7c7e8f5 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -6,7 +6,6 @@ use std::time::Duration; use std::time::Instant; use anyhow::Result; -use anyhow::bail; use codex_features::Feature; use codex_login::CodexAuth; use codex_protocol::protocol::EventMsg; @@ -21,7 +20,7 @@ use core_test_support::skip_if_no_network; use core_test_support::stdio_server_bin; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; -use core_test_support::wait_for_event_with_timeout; +use core_test_support::wait_for_mcp_server; use tempfile::TempDir; use wiremock::MockServer; @@ -140,45 +139,6 @@ async fn build_apps_enabled_plugin_test_codex( .codex) } -async fn wait_for_sample_mcp_ready(codex: &codex_core::CodexThread) -> Result<()> { - let startup_event = wait_for_event_with_timeout( - codex, - |ev| match ev { - EventMsg::McpStartupComplete(summary) => { - summary.ready.iter().any(|server| server == "sample") - || summary - .failed - .iter() - .any(|failure| failure.server == "sample") - || summary.cancelled.iter().any(|server| server == "sample") - } - _ => false, - }, - Duration::from_secs(70), - ) - .await; - let EventMsg::McpStartupComplete(startup) = startup_event else { - unreachable!("event guard guarantees McpStartupComplete"); - }; - if let Some(failure) = startup - .failed - .iter() - .find(|failure| failure.server == "sample") - { - let error = &failure.error; - bail!("plugin MCP server failed to start: {error}"); - } - if startup.cancelled.iter().any(|server| server == "sample") { - bail!("plugin MCP server startup was cancelled"); - } - assert!( - startup.ready.iter().any(|server| server == "sample"), - "expected plugin MCP server to be ready; startup summary: {startup:?}" - ); - - Ok(()) -} - fn tool_names(body: &serde_json::Value) -> Vec { body.get("tools") .and_then(serde_json::Value::as_array) @@ -296,7 +256,7 @@ async fn explicit_plugin_mentions_inject_plugin_guidance() -> Result<()> { let codex = build_apps_enabled_plugin_test_codex(&server, codex_home, apps_server.chatgpt_base_url) .await?; - wait_for_sample_mcp_ready(&codex).await?; + wait_for_mcp_server(&codex, "sample").await?; codex .submit(Op::UserInput { diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 836761961a..343a49ec7f 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -46,10 +46,7 @@ fn text_user_input_parts(texts: Vec) -> serde_json::Value { } fn assert_default_env_context(text: &str, cwd: &str) { - assert!( - text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG), - "expected environment context fragment: {text}" - ); + assert_env_context_fragment(text); assert!( text.contains(&format!("{cwd}")), "expected cwd in environment context: {text}" @@ -58,6 +55,13 @@ fn assert_default_env_context(text: &str, cwd: &str) { text.contains(&format!("{}", default_user_shell().name())), "expected shell in environment context: {text}" ); +} + +fn assert_env_context_fragment(text: &str) { + assert!( + text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG), + "expected environment context fragment: {text}" + ); assert!( text.contains("") && text.contains(""), "expected current_date in environment context: {text}" @@ -502,8 +506,24 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an expected_permissions_msg_2, expected_permissions_msg, "expected updated permissions message after override" ); + let expected_env_msg_2 = body2["input"][body1_input.len() + 1].clone(); + assert_eq!(expected_env_msg_2["role"].as_str(), Some("user")); + let env_text = expected_env_msg_2["content"][0]["text"] + .as_str() + .expect("environment context text"); + assert_env_context_fragment(env_text); + assert!( + env_text.contains("") + && env_text.contains("") + && env_text.contains(&format!( + "{}", + writable.abs().display() + )), + "expected workspace-write filesystem profile in environment context: {env_text}" + ); let mut expected_body2 = body1_input.to_vec(); expected_body2.push(expected_permissions_msg_2); + expected_body2.push(expected_env_msg_2); expected_body2.push(expected_user_message_2); assert_eq!(body2["input"], serde_json::Value::Array(expected_body2)); @@ -1086,12 +1106,25 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu }), "expected model switch section after model override: {expected_settings_update_msg:?}" ); + let expected_env_update_msg = body2["input"][body1_input.len() + 1].clone(); + assert_eq!(expected_env_update_msg["role"].as_str(), Some("user")); + let expected_env_update_text = expected_env_update_msg["content"][0]["text"] + .as_str() + .expect("environment context text"); + assert_env_context_fragment(expected_env_update_text); + assert!( + expected_env_update_text.contains( + "", + ), + "expected disabled filesystem profile in environment context: {expected_env_update_text}" + ); let expected_user_message_2 = text_user_input("hello 2".to_string()); let expected_input_2 = serde_json::Value::Array(vec![ expected_permissions_msg, expected_contextual_user_msg_1, expected_user_message_1, expected_settings_update_msg, + expected_env_update_msg, expected_user_message_2, ]); assert_eq!(body2["input"], expected_input_2); diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index b7b16f9c29..82db097f39 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -477,6 +477,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), @@ -726,6 +727,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), @@ -1209,6 +1211,7 @@ fn test_remote_model_with_policy( input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 51242ede2a..9cb2980725 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -28,6 +28,7 @@ fn resume_history( let turn_ctx = TurnContextItem { turn_id: Some(turn_id.clone()), cwd: config.cwd.to_path_buf(), + workspace_roots: None, current_date: None, timezone: None, approval_policy: config.permissions.approval_policy.value(), @@ -56,6 +57,7 @@ fn resume_history( collaboration_mode_kind: ModeKind::Default, })), RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "seed".to_string(), images: None, local_images: vec![], diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 2c86cb393c..0d669e5dd7 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -55,7 +55,7 @@ use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; -use core_test_support::wait_for_event_with_timeout; +use core_test_support::wait_for_mcp_server; use reqwest::Client; use reqwest::StatusCode; use serde_json::Value; @@ -268,44 +268,6 @@ fn copy_binary_to_remote_env( Ok(remote_path) } -async fn wait_for_mcp_server(fixture: &TestCodex, server_name: &str) -> anyhow::Result<()> { - let startup_event = wait_for_event_with_timeout( - &fixture.codex, - |ev| match ev { - EventMsg::McpStartupComplete(summary) => { - summary.ready.iter().any(|server| server == server_name) - || summary - .failed - .iter() - .any(|failure| failure.server == server_name) - || summary.cancelled.iter().any(|server| server == server_name) - } - _ => false, - }, - Duration::from_secs(70), - ) - .await; - let EventMsg::McpStartupComplete(summary) = startup_event else { - unreachable!("event guard guarantees McpStartupComplete"); - }; - if let Some(failure) = summary - .failed - .iter() - .find(|failure| failure.server == server_name) - { - let error = &failure.error; - anyhow::bail!("MCP server {server_name} failed to start: {error}"); - } - if summary.cancelled.iter().any(|server| server == server_name) { - anyhow::bail!("MCP server {server_name} startup was cancelled"); - } - ensure!( - summary.ready.iter().any(|server| server == server_name), - "expected MCP server {server_name} to be ready; startup summary: {summary:?}" - ); - Ok(()) -} - struct TestMcpServerOptions { environment_id: String, supports_parallel_tool_calls: bool, @@ -517,6 +479,8 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + fixture .codex .submit(read_only_user_turn(&fixture, "call the rmcp echo tool")) @@ -640,6 +604,7 @@ async fn stdio_server_uses_configured_cwd_before_runtime_fallback() -> anyhow::R }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; let expected_cwd = expected_cwd .lock() @@ -702,6 +667,7 @@ async fn local_stdio_server_uses_runtime_fallback_cwd_when_config_omits_cwd() -> }) .build(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; let expected_cwd = expected_cwd .lock() @@ -760,7 +726,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()> .build_with_remote_env(&server) .await?; - wait_for_mcp_server(&fixture, server_name).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .submit_turn_with_permission_profile( @@ -857,6 +823,8 @@ async fn stdio_mcp_parallel_tool_calls_default_false_runs_serially() -> anyhow:: }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + fixture .codex // Keep this baseline on the mutable sync tool so read-only hints do not @@ -991,6 +959,8 @@ async fn stdio_mcp_read_only_tool_calls_run_concurrently_without_server_opt_in() }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + fixture .codex .submit(read_only_user_turn( @@ -1073,6 +1043,8 @@ async fn stdio_mcp_parallel_tool_calls_opt_in_runs_concurrently() -> anyhow::Res }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + fixture .codex // Exercise the server opt-in with the mutable sync tool rather than the @@ -1157,7 +1129,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { }) .build_with_remote_env(&server) .await?; - wait_for_mcp_server(&fixture, server_name).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .codex @@ -1290,7 +1262,7 @@ async fn stdio_image_responses_preserve_original_detail_metadata() -> anyhow::Re }) .build_with_remote_env(&server) .await?; - wait_for_mcp_server(&fixture, server_name).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .codex @@ -1377,6 +1349,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re input_modalities: vec![InputModality::Text], used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, }], }, ) @@ -1426,6 +1399,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .thread_manager @@ -1528,6 +1502,8 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + fixture .codex .submit(read_only_user_turn(&fixture, "call the rmcp echo tool")) @@ -1646,6 +1622,7 @@ async fn stdio_server_propagates_explicit_local_env_var_source() -> anyhow::Resu }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .codex @@ -1738,6 +1715,7 @@ async fn remote_stdio_env_var_source_does_not_copy_local_env() -> anyhow::Result }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .codex @@ -1921,6 +1899,8 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { }) .build_with_remote_env(&server) .await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; + // Phase 4: submit the user turn that should trigger the MCP tool call. fixture .codex @@ -2109,7 +2089,7 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> { .await?; // Phase 5: wait for MCP startup before the turn is submitted, which keeps // failures tied to server startup/discovery. - wait_for_mcp_server(&fixture, server_name).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; // Phase 6: submit the user turn that should invoke the OAuth-backed tool. fixture diff --git a/codex-rs/core/tests/suite/search_tool.rs b/codex-rs/core/tests/suite/search_tool.rs index e9ffeb62ef..42b1b6bb3f 100644 --- a/codex-rs/core/tests/suite/search_tool.rs +++ b/codex-rs/core/tests/suite/search_tool.rs @@ -17,16 +17,20 @@ use codex_protocol::protocol::McpInvocation; use codex_protocol::protocol::Op; use codex_protocol::user_input::UserInput; use core_test_support::apps_test_server::AppsTestServer; +use core_test_support::apps_test_server::AppsTestToolLoading; use core_test_support::apps_test_server::CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI; use core_test_support::apps_test_server::CALENDAR_CREATE_EVENT_RESOURCE_URI; use core_test_support::apps_test_server::DIRECT_CALENDAR_CREATE_EVENT_TOOL as CALENDAR_CREATE_TOOL; use core_test_support::apps_test_server::DIRECT_CALENDAR_LIST_EVENTS_TOOL as CALENDAR_LIST_TOOL; +use core_test_support::apps_test_server::SEARCH_CALENDAR_APP_ONLY_TOOL; use core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL; use core_test_support::apps_test_server::SEARCH_CALENDAR_LIST_TOOL; use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE; +use core_test_support::apps_test_server::apps_enabled_builder; use core_test_support::apps_test_server::configure_search_capable_apps; use core_test_support::apps_test_server::configure_search_capable_model; use core_test_support::apps_test_server::recorded_apps_tool_call_by_call_id; +use core_test_support::apps_test_server::recorded_apps_tool_calls; use core_test_support::apps_test_server::search_capable_apps_builder as configured_builder; use core_test_support::responses::ResponsesRequest; use core_test_support::responses::ev_assistant_message; @@ -43,6 +47,7 @@ use core_test_support::skip_if_no_network; use core_test_support::stdio_server_bin; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; +use core_test_support::wait_for_mcp_server; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; @@ -159,7 +164,7 @@ async fn search_tool_enabled_by_default_adds_tool_search() -> Result<()> { "type": "object", "properties": { "query": {"type": "string", "description": "Search query for deferred tools."}, - "limit": {"type": "number", "description": "Maximum number of tools to return (defaults to 8)."}, + "limit": {"type": "number", "description": "Maximum number of tools to return. Defaults to 8."}, }, "required": ["query"], "additionalProperties": false, @@ -216,6 +221,80 @@ async fn always_defer_feature_hides_small_app_tool_sets() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn app_only_tools_are_not_visible_or_runnable_by_direct_model_calls() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let apps_server = + AppsTestServer::mount_with_app_only_tool(&server, AppsTestToolLoading::Direct).await?; + let call_id = "app-only-direct-call"; + let mock = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + ev_function_call_with_namespace( + call_id, + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_APP_ONLY_TOOL, + "{}", + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url.clone()); + let test = builder.build(&server).await?; + test.submit_turn_with_approval_and_permission_profile( + "Try to call the app-only calendar tool.", + AskForApproval::Never, + PermissionProfile::Disabled, + ) + .await?; + + let requests = mock.requests(); + assert!( + namespace_child_tool( + &requests[0].body_json(), + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_CREATE_TOOL + ) + .is_some(), + "visible tool from the app-only tool's connector should be declared" + ); + assert!( + namespace_child_tool( + &requests[0].body_json(), + SEARCH_CALENDAR_NAMESPACE, + SEARCH_CALENDAR_APP_ONLY_TOOL + ) + .is_none(), + "app-only tool should not be declared to a direct model" + ); + assert!( + requests[1] + .function_call_output(call_id) + .get("output") + .and_then(Value::as_str) + .is_some_and(|output| output.contains("unsupported call")), + "forced app-only direct call should not dispatch" + ); + assert!( + recorded_apps_tool_calls(&server).await.is_empty(), + "forced app-only direct call should not reach the MCP server" + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn app_search_sources_are_hidden_for_api_key_auth() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1036,6 +1115,7 @@ async fn tool_search_indexes_only_enabled_non_app_mcp_tools() -> Result<()> { .expect("test mcp servers should accept any configuration"); }); let test = builder.build(&server).await?; + wait_for_mcp_server(&test.codex, "rmcp").await?; test.submit_turn_with_approval_and_permission_profile( "Find the rmcp echo and image tools.", @@ -1165,6 +1245,7 @@ async fn tool_search_surfaced_mcp_tool_errors_are_returned_to_model() -> Result< .expect("test mcp servers should accept any configuration"); }); let test = builder.build(&server).await?; + wait_for_mcp_server(&test.codex, "rmcp").await?; test.codex .submit(Op::UserInput { @@ -1313,6 +1394,7 @@ async fn tool_search_uses_non_app_mcp_server_instructions_as_namespace_descripti .expect("test mcp servers should accept any configuration"); }); let test = builder.build(&server).await?; + wait_for_mcp_server(&test.codex, "rmcp").await?; test.submit_turn_with_approval_and_permission_profile( "Find the rmcp echo tool.", diff --git a/codex-rs/core/tests/suite/spawn_agent_description.rs b/codex-rs/core/tests/suite/spawn_agent_description.rs index fbeb90fba5..f9be02349c 100644 --- a/codex-rs/core/tests/suite/spawn_agent_description.rs +++ b/codex-rs/core/tests/suite/spawn_agent_description.rs @@ -60,6 +60,7 @@ fn test_model_info( input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers, @@ -183,7 +184,7 @@ async fn spawn_agent_description_lists_visible_models_and_reasoning_efforts() -> ); assert!( description.contains( - "Spawned agents inherit your current model by default. Omit `model` to use that preferred default; set `model` only when an explicit override is needed." + "Spawned agents inherit your current model by default. If provided, `model` specifies the model to use for the spawned agent." ), "expected inherited-model guidance in spawn_agent description: {description:?}" ); diff --git a/codex-rs/core/tests/suite/sqlite_state.rs b/codex-rs/core/tests/suite/sqlite_state.rs index 99b7fb0ec6..4d9c89638e 100644 --- a/codex-rs/core/tests/suite/sqlite_state.rs +++ b/codex-rs/core/tests/suite/sqlite_state.rs @@ -29,6 +29,7 @@ use core_test_support::test_codex::test_codex; use core_test_support::test_codex::turn_permission_fields; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; +use core_test_support::wait_for_mcp_server; use pretty_assertions::assert_eq; use serde_json::json; use std::collections::HashMap; @@ -93,6 +94,104 @@ async fn new_thread_is_recorded_in_state_db() -> Result<()> { Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn resume_restores_dynamic_tools_from_rollout_with_sqlite_enabled() -> Result<()> { + let server = start_mock_server().await; + let mock = mount_sse_sequence( + &server, + vec![ + responses::sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]), + responses::sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]), + ], + ) + .await; + + let dynamic_tool = DynamicToolSpec { + namespace: None, + name: "resume_lookup".to_string(), + description: "Look up a value after resume.".to_string(), + input_schema: json!({ + "type": "object", + "properties": { "query": { "type": "string" } }, + "required": ["query"], + "additionalProperties": false, + }), + defer_loading: false, + }; + let mut builder = test_codex().with_config(|config| { + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); + }); + let base_test = builder.build(&server).await?; + let started = base_test + .thread_manager + .start_thread_with_tools( + base_test.config.clone(), + vec![dynamic_tool.clone()], + /*persist_extended_history*/ false, + ) + .await?; + let rollout_path = started + .session_configured + .rollout_path + .clone() + .expect("rollout path"); + + started + .thread + .submit(Op::UserInput { + environments: None, + items: vec![UserInput::Text { + text: "persist this thread".to_string(), + text_elements: Vec::new(), + }], + final_output_json_schema: None, + responsesapi_client_metadata: None, + additional_context: Default::default(), + thread_settings: Default::default(), + }) + .await?; + wait_for_event(&started.thread, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + let mut resume_builder = test_codex().with_config(|config| { + config + .features + .enable(Feature::Sqlite) + .expect("test config should allow feature update"); + }); + let resumed = resume_builder + .resume(&server, base_test.home.clone(), rollout_path) + .await?; + resumed.submit_turn("use the restored tool").await?; + + let requests = mock.requests(); + assert_eq!(requests.len(), 2); + let resumed_body = requests[1].body_json(); + let tools = resumed_body + .get("tools") + .and_then(serde_json::Value::as_array) + .expect("resumed request tools"); + let restored_tool = tools + .iter() + .find(|tool| tool.get("name") == Some(&json!(dynamic_tool.name.as_str()))) + .expect("dynamic tool should be restored from rollout metadata"); + assert_eq!( + restored_tool.get("description"), + Some(&json!(dynamic_tool.description.as_str())) + ); + assert_eq!( + restored_tool.get("parameters"), + Some(&dynamic_tool.input_schema) + ); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn backfill_scans_existing_rollouts() -> Result<()> { let server = start_mock_server().await; @@ -102,32 +201,6 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { let rollout_rel_path = format!("sessions/2026/01/27/rollout-2026-01-27T12-00-00-{uuid}.jsonl"); let rollout_rel_path_for_hook = rollout_rel_path.clone(); - let dynamic_tools = vec![ - DynamicToolSpec { - namespace: Some("codex_app".to_string()), - name: "geo_lookup".to_string(), - description: "lookup a city".to_string(), - input_schema: json!({ - "type": "object", - "required": ["city"], - "properties": { "city": { "type": "string" } } - }), - defer_loading: true, - }, - DynamicToolSpec { - namespace: None, - name: "weather_lookup".to_string(), - description: "lookup weather".to_string(), - input_schema: json!({ - "type": "object", - "required": ["zip"], - "properties": { "zip": { "type": "string" } } - }), - defer_loading: false, - }, - ]; - let dynamic_tools_for_hook = dynamic_tools.clone(); - let mut builder = test_codex() .with_pre_build_hook(move |codex_home| { let rollout_path = codex_home.join(&rollout_rel_path_for_hook); @@ -150,7 +223,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { agent_role: None, model_provider: None, base_instructions: None, - dynamic_tools: Some(dynamic_tools_for_hook), + dynamic_tools: None, memory_mode: None, }, git: None, @@ -164,6 +237,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { RolloutLine { timestamp: "2026-01-27T12:00:01Z".to_string(), item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello from backfill".to_string(), images: None, local_images: Vec::new(), @@ -217,17 +291,6 @@ async fn backfill_scans_existing_rollouts() -> Result<()> { assert_eq!(metadata.model_provider, default_provider); assert!(metadata.first_user_message.is_some()); - let mut stored_tools = None; - for _ in 0..40 { - stored_tools = db.get_dynamic_tools(thread_id).await?; - if stored_tools.is_some() { - break; - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - let stored_tools = stored_tools.expect("dynamic tools should be stored"); - assert_eq!(stored_tools, dynamic_tools); - Ok(()) } @@ -398,6 +461,7 @@ async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result< .expect("test mcp servers should accept any configuration"); }); let test = builder.build(&server).await?; + wait_for_mcp_server(&test.codex, server_name).await?; let db = test.codex.state_db().expect("state db enabled"); let thread_id = test.session_configured.thread_id; let cwd = test.cwd_path().to_path_buf(); diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index fe078977ff..db90b663e0 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -23,6 +23,7 @@ use core_test_support::skip_if_no_network; use core_test_support::stdio_server_bin; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; +use core_test_support::wait_for_mcp_server; use serde_json::Value; use serde_json::json; use std::collections::HashMap; @@ -410,6 +411,7 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> config.tool_output_token_limit = Some(500); }); let fixture = builder.build(&server).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .submit_turn_with_permission_profile( @@ -509,6 +511,7 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { .expect("test mcp servers should accept any configuration"); }); let fixture = builder.build(&server).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; let session_model = fixture.session_configured.model.clone(); let permission_profile = PermissionProfile::read_only(); let sandbox_policy = permission_profile.to_legacy_sandbox_policy(fixture.cwd.path())?; @@ -798,6 +801,7 @@ async fn mcp_tool_call_output_not_truncated_with_custom_limit() -> Result<()> { .expect("test mcp servers should accept any configuration"); }); let fixture = builder.build(&server).await?; + wait_for_mcp_server(&fixture.codex, server_name).await?; fixture .submit_turn_with_permission_profile( diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index e6320ba1a7..6062228de0 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -1355,6 +1355,7 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an input_modalities: vec![InputModality::Text], used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), diff --git a/codex-rs/core/tests/suite/windows_sandbox.rs b/codex-rs/core/tests/suite/windows_sandbox.rs index 7b91a4f3cd..120381e67a 100644 --- a/codex-rs/core/tests/suite/windows_sandbox.rs +++ b/codex-rs/core/tests/suite/windows_sandbox.rs @@ -180,6 +180,7 @@ async fn windows_restricted_token_rejects_exact_and_glob_deny_read_policy() -> a }, &permission_profile, &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, @@ -264,6 +265,7 @@ async fn windows_elevated_enforces_exact_and_glob_deny_read_policy() -> anyhow:: }, &permission_profile, &cwd, + std::slice::from_ref(&cwd), &None, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/debug-client/Cargo.toml b/codex-rs/debug-client/Cargo.toml deleted file mode 100644 index 14dcb5600a..0000000000 --- a/codex-rs/debug-client/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "codex-debug-client" -version.workspace = true -edition.workspace = true -license.workspace = true - -[lints] -workspace = true - -[dependencies] -anyhow.workspace = true -clap = { workspace = true, features = ["derive"] } -codex-app-server-protocol.workspace = true -serde.workspace = true -serde_json.workspace = true - -[dev-dependencies] -pretty_assertions.workspace = true diff --git a/codex-rs/debug-client/README.md b/codex-rs/debug-client/README.md deleted file mode 100644 index 447ed12360..0000000000 --- a/codex-rs/debug-client/README.md +++ /dev/null @@ -1,60 +0,0 @@ -WARNING: this code is mainly generated by Codex and should not be used in production - -# codex-debug-client - -A tiny interactive client for `codex app-server` (protocol v2 only). It prints -all JSON-RPC lines from the server and lets you send new turns as you type. - -## Usage - -Start the app-server client (it will spawn `codex app-server` itself): - -``` -cargo run -p codex-debug-client -- \ - --codex-bin codex \ - --approval-policy on-request \ - --output-file /tmp/app-server-server-json.jsonl -``` - -You can resume a specific thread: - -``` -cargo run -p codex-debug-client -- --thread-id thr_123 -``` - -### CLI flags - -- `--codex-bin `: path to the `codex` binary (default: `codex`). -- `-c, --config key=value`: pass through `--config` overrides to `codex`. -- `--thread-id `: resume a thread instead of starting a new one. -- `--approval-policy `: `untrusted`, `on-failure` (deprecated), `on-request`, `never`. -- `--auto-approve`: auto-approve command/file-change approvals (default: decline). -- `--final-only`: only show completed assistant messages and tool items. -- `--output-file `: write raw server JSONL to this file instead of stdout. -- `--model `: optional model override for thread start/resume. -- `--model-provider `: optional provider override. -- `--cwd `: optional working directory override. - -## Interactive commands - -Type a line to send it as a new turn. Commands are prefixed with `:`: - -- `:help` show help -- `:new` start a new thread -- `:resume ` resume a thread -- `:use ` switch active thread without resuming -- `:refresh-thread` list available threads -- `:quit` exit - -The prompt shows the active thread id. Client messages (help, errors, approvals) -print to stderr; raw server JSON prints to stdout so you can pipe/record it -unless `--final-only` is set. Pass `--output-file ` to record raw server -JSONL to a file instead of stdout. - -## Notes - -- The client performs the required initialize/initialized handshake. -- It prints every server notification and response line as it arrives. -- Approvals for `item/commandExecution/requestApproval` and - `item/fileChange/requestApproval` are auto-responded to with decline unless - `--auto-approve` is set. diff --git a/codex-rs/debug-client/src/client.rs b/codex-rs/debug-client/src/client.rs deleted file mode 100644 index 90bccf1daa..0000000000 --- a/codex-rs/debug-client/src/client.rs +++ /dev/null @@ -1,414 +0,0 @@ -#![allow(clippy::expect_used)] -use std::io::BufRead; -use std::io::BufReader; -use std::io::Write; -use std::process::Child; -use std::process::ChildStdin; -use std::process::ChildStdout; -use std::process::Command; -use std::process::Stdio; -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::atomic::AtomicI64; -use std::sync::atomic::Ordering; -use std::sync::mpsc::Sender; - -use anyhow::Context; -use anyhow::Result; -use codex_app_server_protocol::AskForApproval; -use codex_app_server_protocol::ClientInfo; -use codex_app_server_protocol::ClientNotification; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::CommandExecutionApprovalDecision; -use codex_app_server_protocol::FileChangeApprovalDecision; -use codex_app_server_protocol::InitializeCapabilities; -use codex_app_server_protocol::JSONRPCMessage; -use codex_app_server_protocol::JSONRPCRequest; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ThreadListParams; -use codex_app_server_protocol::ThreadResumeParams; -use codex_app_server_protocol::ThreadResumeResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_app_server_protocol::TurnStartParams; -use codex_app_server_protocol::UserInput; -use serde::Serialize; - -use crate::output::Output; -use crate::reader::start_reader; -use crate::state::PendingRequest; -use crate::state::ReaderEvent; -use crate::state::State; - -pub struct AppServerClient { - child: Child, - stdin: Arc>>, - stdout: Option>, - next_request_id: AtomicI64, - state: Arc>, - output: Output, - filtered_output: bool, -} - -impl AppServerClient { - pub fn spawn( - codex_bin: &str, - config_overrides: &[String], - output: Output, - filtered_output: bool, - ) -> Result { - let mut cmd = Command::new(codex_bin); - for override_kv in config_overrides { - cmd.arg("--config").arg(override_kv); - } - - let mut child = cmd - .arg("app-server") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .spawn() - .with_context(|| format!("failed to start `{codex_bin}` app-server"))?; - - let stdin = child - .stdin - .take() - .context("codex app-server stdin unavailable")?; - let stdout = child - .stdout - .take() - .context("codex app-server stdout unavailable")?; - - Ok(Self { - child, - stdin: Arc::new(Mutex::new(Some(stdin))), - stdout: Some(BufReader::new(stdout)), - next_request_id: AtomicI64::new(1), - state: Arc::new(Mutex::new(State::default())), - output, - filtered_output, - }) - } - - pub fn initialize(&mut self) -> Result<()> { - let request_id = self.next_request_id(); - let request = ClientRequest::Initialize { - request_id: request_id.clone(), - params: codex_app_server_protocol::InitializeParams { - client_info: ClientInfo { - name: "debug-client".to_string(), - title: Some("Debug Client".to_string()), - version: env!("CARGO_PKG_VERSION").to_string(), - }, - capabilities: Some(InitializeCapabilities { - experimental_api: true, - request_attestation: false, - opt_out_notification_methods: None, - }), - }, - }; - - self.send(&request)?; - let response = self.read_until_response(&request_id)?; - let _parsed: codex_app_server_protocol::InitializeResponse = - serde_json::from_value(response.result).context("decode initialize response")?; - let initialized = ClientNotification::Initialized; - self.send(&initialized)?; - Ok(()) - } - - pub fn start_thread(&mut self, params: ThreadStartParams) -> Result { - let request_id = self.next_request_id(); - let request = ClientRequest::ThreadStart { - request_id: request_id.clone(), - params, - }; - self.send(&request)?; - let response = self.read_until_response(&request_id)?; - let parsed: ThreadStartResponse = - serde_json::from_value(response.result).context("decode thread/start response")?; - let thread_id = parsed.thread.id; - self.set_thread_id(thread_id.clone()); - Ok(thread_id) - } - - pub fn resume_thread(&mut self, params: ThreadResumeParams) -> Result { - let request_id = self.next_request_id(); - let request = ClientRequest::ThreadResume { - request_id: request_id.clone(), - params, - }; - self.send(&request)?; - let response = self.read_until_response(&request_id)?; - let parsed: ThreadResumeResponse = - serde_json::from_value(response.result).context("decode thread/resume response")?; - let thread_id = parsed.thread.id; - self.set_thread_id(thread_id.clone()); - Ok(thread_id) - } - - pub fn request_thread_start(&self, params: ThreadStartParams) -> Result { - let request_id = self.next_request_id(); - self.track_pending(request_id.clone(), PendingRequest::Start); - let request = ClientRequest::ThreadStart { - request_id: request_id.clone(), - params, - }; - self.send(&request)?; - Ok(request_id) - } - - pub fn request_thread_resume(&self, params: ThreadResumeParams) -> Result { - let request_id = self.next_request_id(); - self.track_pending(request_id.clone(), PendingRequest::Resume); - let request = ClientRequest::ThreadResume { - request_id: request_id.clone(), - params, - }; - self.send(&request)?; - Ok(request_id) - } - - pub fn request_thread_list(&self, cursor: Option) -> Result { - let request_id = self.next_request_id(); - self.track_pending(request_id.clone(), PendingRequest::List); - let request = ClientRequest::ThreadList { - request_id: request_id.clone(), - params: ThreadListParams { - cursor, - limit: None, - sort_key: None, - sort_direction: None, - model_providers: None, - source_kinds: None, - archived: None, - cwd: None, - use_state_db_only: false, - search_term: None, - }, - }; - self.send(&request)?; - Ok(request_id) - } - - pub fn send_turn(&self, thread_id: &str, text: String) -> Result { - let request_id = self.next_request_id(); - let request = ClientRequest::TurnStart { - request_id: request_id.clone(), - params: TurnStartParams { - thread_id: thread_id.to_string(), - input: vec![UserInput::Text { - text, - // Debug client sends plain text with no UI markup spans. - text_elements: Vec::new(), - }], - ..Default::default() - }, - }; - self.send(&request)?; - Ok(request_id) - } - - pub fn start_reader( - &mut self, - events: Sender, - auto_approve: bool, - filtered_output: bool, - ) -> Result<()> { - let stdout = self.stdout.take().context("reader already started")?; - start_reader( - stdout, - Arc::clone(&self.stdin), - Arc::clone(&self.state), - events, - self.output.clone(), - auto_approve, - filtered_output, - ); - Ok(()) - } - - pub fn thread_id(&self) -> Option { - let state = self.state.lock().expect("state lock poisoned"); - state.thread_id.clone() - } - - pub fn set_thread_id(&self, thread_id: String) { - let mut state = self.state.lock().expect("state lock poisoned"); - state.thread_id = Some(thread_id); - self.remember_thread_locked(&mut state); - } - - pub fn use_thread(&self, thread_id: String) -> bool { - let mut state = self.state.lock().expect("state lock poisoned"); - let known = state.known_threads.iter().any(|id| id == &thread_id); - state.thread_id = Some(thread_id); - self.remember_thread_locked(&mut state); - known - } - - pub fn shutdown(&mut self) { - if let Ok(mut stdin) = self.stdin.lock() { - let _ = stdin.take(); - } - let _ = self.child.wait(); - } - - fn track_pending(&self, request_id: RequestId, kind: PendingRequest) { - let mut state = self.state.lock().expect("state lock poisoned"); - state.pending.insert(request_id, kind); - } - - fn remember_thread_locked(&self, state: &mut State) { - if let Some(thread_id) = state.thread_id.as_ref() - && !state.known_threads.iter().any(|id| id == thread_id) - { - state.known_threads.push(thread_id.clone()); - } - } - - fn next_request_id(&self) -> RequestId { - let id = self.next_request_id.fetch_add(1, Ordering::SeqCst); - RequestId::Integer(id) - } - - fn send(&self, value: &T) -> Result<()> { - let json = serde_json::to_string(value).context("serialize message")?; - let mut line = json; - line.push('\n'); - let mut stdin = self.stdin.lock().expect("stdin lock poisoned"); - let Some(stdin) = stdin.as_mut() else { - anyhow::bail!("stdin already closed"); - }; - stdin.write_all(line.as_bytes()).context("write message")?; - stdin.flush().context("flush message")?; - Ok(()) - } - - fn read_until_response(&mut self, request_id: &RequestId) -> Result { - let stdin = Arc::clone(&self.stdin); - let output = self.output.clone(); - let reader = self.stdout.as_mut().context("stdout missing")?; - let mut buffer = String::new(); - - loop { - buffer.clear(); - let bytes = reader - .read_line(&mut buffer) - .context("read server output")?; - if bytes == 0 { - anyhow::bail!("server closed stdout while awaiting response {request_id:?}"); - } - - let line = buffer.trim_end_matches(['\n', '\r']); - if !line.is_empty() { - let _ = output.server_json_line(line, self.filtered_output); - } - - let message = match serde_json::from_str::(line) { - Ok(message) => message, - Err(_) => continue, - }; - - match message { - JSONRPCMessage::Response(response) if &response.id == request_id => { - return Ok(response); - } - JSONRPCMessage::Request(request) => { - let _ = handle_server_request(request, &stdin); - } - _ => {} - } - } - } -} - -fn handle_server_request( - request: JSONRPCRequest, - stdin: &Arc>>, -) -> Result<()> { - let Ok(server_request) = codex_app_server_protocol::ServerRequest::try_from(request) else { - return Ok(()); - }; - - match server_request { - codex_app_server_protocol::ServerRequest::CommandExecutionRequestApproval { - request_id, - .. - } => { - let response = codex_app_server_protocol::CommandExecutionRequestApprovalResponse { - decision: CommandExecutionApprovalDecision::Decline, - }; - send_jsonrpc_response(stdin, request_id, response) - } - codex_app_server_protocol::ServerRequest::FileChangeRequestApproval { - request_id, .. - } => { - let response = codex_app_server_protocol::FileChangeRequestApprovalResponse { - decision: FileChangeApprovalDecision::Decline, - }; - send_jsonrpc_response(stdin, request_id, response) - } - _ => Ok(()), - } -} - -fn send_jsonrpc_response( - stdin: &Arc>>, - request_id: RequestId, - response: T, -) -> Result<()> { - let result = serde_json::to_value(response).context("serialize response")?; - let message = JSONRPCMessage::Response(JSONRPCResponse { - id: request_id, - result, - }); - send_with_stdin(stdin, &message) -} - -fn send_with_stdin(stdin: &Arc>>, value: &T) -> Result<()> { - let json = serde_json::to_string(value).context("serialize message")?; - let mut line = json; - line.push('\n'); - let mut stdin = stdin.lock().expect("stdin lock poisoned"); - let Some(stdin) = stdin.as_mut() else { - anyhow::bail!("stdin already closed"); - }; - stdin.write_all(line.as_bytes()).context("write message")?; - stdin.flush().context("flush message")?; - Ok(()) -} - -pub fn build_thread_start_params( - approval_policy: AskForApproval, - model: Option, - model_provider: Option, - cwd: Option, -) -> ThreadStartParams { - ThreadStartParams { - model, - model_provider, - cwd, - approval_policy: Some(approval_policy), - experimental_raw_events: false, - ..Default::default() - } -} - -pub fn build_thread_resume_params( - thread_id: String, - approval_policy: AskForApproval, - model: Option, - model_provider: Option, - cwd: Option, -) -> ThreadResumeParams { - ThreadResumeParams { - thread_id, - model, - model_provider, - cwd, - approval_policy: Some(approval_policy), - ..Default::default() - } -} diff --git a/codex-rs/debug-client/src/commands.rs b/codex-rs/debug-client/src/commands.rs deleted file mode 100644 index 447f09a54d..0000000000 --- a/codex-rs/debug-client/src/commands.rs +++ /dev/null @@ -1,156 +0,0 @@ -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum InputAction { - Message(String), - Command(UserCommand), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum UserCommand { - Help, - Quit, - NewThread, - Resume(String), - Use(String), - RefreshThread, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ParseError { - EmptyCommand, - MissingArgument { name: &'static str }, - UnknownCommand { command: String }, -} - -impl ParseError { - pub fn message(&self) -> String { - match self { - Self::EmptyCommand => "empty command after ':'".to_string(), - Self::MissingArgument { name } => { - format!("missing required argument: {name}") - } - Self::UnknownCommand { command } => format!("unknown command: {command}"), - } - } -} - -pub fn parse_input(line: &str) -> Result, ParseError> { - let trimmed = line.trim(); - if trimmed.is_empty() { - return Ok(None); - } - - let Some(command_line) = trimmed.strip_prefix(':') else { - return Ok(Some(InputAction::Message(trimmed.to_string()))); - }; - - let mut parts = command_line.split_whitespace(); - let Some(command) = parts.next() else { - return Err(ParseError::EmptyCommand); - }; - - match command { - "help" | "h" => Ok(Some(InputAction::Command(UserCommand::Help))), - "quit" | "q" | "exit" => Ok(Some(InputAction::Command(UserCommand::Quit))), - "new" => Ok(Some(InputAction::Command(UserCommand::NewThread))), - "resume" => { - let thread_id = parts - .next() - .ok_or(ParseError::MissingArgument { name: "thread-id" })?; - Ok(Some(InputAction::Command(UserCommand::Resume( - thread_id.to_string(), - )))) - } - "use" => { - let thread_id = parts - .next() - .ok_or(ParseError::MissingArgument { name: "thread-id" })?; - Ok(Some(InputAction::Command(UserCommand::Use( - thread_id.to_string(), - )))) - } - "refresh-thread" => Ok(Some(InputAction::Command(UserCommand::RefreshThread))), - _ => Err(ParseError::UnknownCommand { - command: command.to_string(), - }), - } -} - -#[cfg(test)] -mod tests { - use pretty_assertions::assert_eq; - - use super::InputAction; - use super::ParseError; - use super::UserCommand; - use super::parse_input; - - #[test] - fn parses_message() { - let result = parse_input("hello there").unwrap(); - assert_eq!( - result, - Some(InputAction::Message("hello there".to_string())) - ); - } - - #[test] - fn parses_help_command() { - let result = parse_input(":help").unwrap(); - assert_eq!(result, Some(InputAction::Command(UserCommand::Help))); - } - - #[test] - fn parses_new_thread() { - let result = parse_input(":new").unwrap(); - assert_eq!(result, Some(InputAction::Command(UserCommand::NewThread))); - } - - #[test] - fn parses_resume() { - let result = parse_input(":resume thr_123").unwrap(); - assert_eq!( - result, - Some(InputAction::Command(UserCommand::Resume( - "thr_123".to_string() - ))) - ); - } - - #[test] - fn parses_use() { - let result = parse_input(":use thr_456").unwrap(); - assert_eq!( - result, - Some(InputAction::Command(UserCommand::Use( - "thr_456".to_string() - ))) - ); - } - - #[test] - fn parses_refresh_thread() { - let result = parse_input(":refresh-thread").unwrap(); - assert_eq!( - result, - Some(InputAction::Command(UserCommand::RefreshThread)) - ); - } - - #[test] - fn rejects_missing_resume_arg() { - let result = parse_input(":resume"); - assert_eq!( - result, - Err(ParseError::MissingArgument { name: "thread-id" }) - ); - } - - #[test] - fn rejects_missing_use_arg() { - let result = parse_input(":use"); - assert_eq!( - result, - Err(ParseError::MissingArgument { name: "thread-id" }) - ); - } -} diff --git a/codex-rs/debug-client/src/main.rs b/codex-rs/debug-client/src/main.rs deleted file mode 100644 index a09d9d04f5..0000000000 --- a/codex-rs/debug-client/src/main.rs +++ /dev/null @@ -1,310 +0,0 @@ -mod client; -mod commands; -mod output; -mod reader; -mod state; - -use std::fs::File; -use std::io; -use std::io::BufRead; -use std::path::PathBuf; -use std::sync::mpsc; - -use anyhow::Context; -use anyhow::Result; -use clap::ArgAction; -use clap::Parser; -use codex_app_server_protocol::AskForApproval; - -use crate::client::AppServerClient; -use crate::client::build_thread_resume_params; -use crate::client::build_thread_start_params; -use crate::commands::InputAction; -use crate::commands::UserCommand; -use crate::commands::parse_input; -use crate::output::Output; -use crate::state::ReaderEvent; - -#[derive(Parser)] -#[command(author = "Codex", version, about = "Minimal app-server client")] -struct Cli { - /// Path to the `codex` CLI binary. - #[arg(long, default_value = "codex")] - codex_bin: String, - - /// Forwarded to the `codex` CLI as `--config key=value`. Repeatable. - #[arg(short = 'c', long = "config", value_name = "key=value", action = ArgAction::Append)] - config_overrides: Vec, - - /// Resume an existing thread instead of starting a new one. - #[arg(long)] - thread_id: Option, - - /// Set the approval policy for the thread. - #[arg(long, default_value = "on-request")] - approval_policy: String, - - /// Auto-approve command/file-change approvals. - #[arg(long, default_value_t = false)] - auto_approve: bool, - - /// Only show final assistant messages and tool calls. - #[arg(long, default_value_t = false)] - final_only: bool, - - /// Write raw server JSONL to this file instead of stdout. - #[arg(long, value_name = "PATH")] - output_file: Option, - - /// Optional model override when starting/resuming a thread. - #[arg(long)] - model: Option, - - /// Optional model provider override when starting/resuming a thread. - #[arg(long)] - model_provider: Option, - - /// Optional working directory override when starting/resuming a thread. - #[arg(long)] - cwd: Option, -} - -fn main() -> Result<()> { - let cli = Cli::parse(); - let jsonl_file = cli - .output_file - .as_ref() - .map(File::create) - .transpose() - .with_context(|| { - let Some(path) = cli.output_file.as_ref() else { - return "open output file".to_string(); - }; - format!("open output file {}", path.display()) - })?; - let output = Output::new(jsonl_file); - let approval_policy = parse_approval_policy(&cli.approval_policy)?; - - let mut client = AppServerClient::spawn( - &cli.codex_bin, - &cli.config_overrides, - output.clone(), - cli.final_only, - )?; - client.initialize()?; - - let thread_id = if let Some(thread_id) = cli.thread_id.as_ref() { - client.resume_thread(build_thread_resume_params( - thread_id.clone(), - approval_policy, - cli.model.clone(), - cli.model_provider.clone(), - cli.cwd.clone(), - ))? - } else { - client.start_thread(build_thread_start_params( - approval_policy, - cli.model.clone(), - cli.model_provider.clone(), - cli.cwd.clone(), - ))? - }; - - output - .client_line(&format!("connected to thread {thread_id}")) - .ok(); - output.set_prompt(&thread_id); - - let (event_tx, event_rx) = mpsc::channel(); - client.start_reader(event_tx, cli.auto_approve, cli.final_only)?; - - print_help(&output); - - let stdin = io::stdin(); - let mut lines = stdin.lock().lines(); - - loop { - drain_events(&event_rx, &output); - let prompt_thread = client - .thread_id() - .unwrap_or_else(|| "no-thread".to_string()); - output.prompt(&prompt_thread).ok(); - - let Some(line) = lines.next() else { - break; - }; - let line = line.context("read stdin")?; - - match parse_input(&line) { - Ok(None) => continue, - Ok(Some(InputAction::Message(message))) => { - let Some(active_thread) = client.thread_id() else { - output - .client_line("no active thread; use :new or :resume ") - .ok(); - continue; - }; - if let Err(err) = client.send_turn(&active_thread, message) { - output - .client_line(&format!("failed to send turn: {err}")) - .ok(); - } - } - Ok(Some(InputAction::Command(command))) => { - if !handle_command(command, &client, &output, approval_policy, &cli) { - break; - } - } - Err(err) => { - output.client_line(&err.message()).ok(); - } - } - } - - client.shutdown(); - Ok(()) -} - -fn handle_command( - command: UserCommand, - client: &AppServerClient, - output: &Output, - approval_policy: AskForApproval, - cli: &Cli, -) -> bool { - match command { - UserCommand::Help => { - print_help(output); - true - } - UserCommand::Quit => false, - UserCommand::NewThread => { - match client.request_thread_start(build_thread_start_params( - approval_policy, - cli.model.clone(), - cli.model_provider.clone(), - cli.cwd.clone(), - )) { - Ok(request_id) => { - output - .client_line(&format!("requested new thread ({request_id:?})")) - .ok(); - } - Err(err) => { - output - .client_line(&format!("failed to start thread: {err}")) - .ok(); - } - } - true - } - UserCommand::Resume(thread_id) => { - match client.request_thread_resume(build_thread_resume_params( - thread_id, - approval_policy, - cli.model.clone(), - cli.model_provider.clone(), - cli.cwd.clone(), - )) { - Ok(request_id) => { - output - .client_line(&format!("requested thread resume ({request_id:?})")) - .ok(); - } - Err(err) => { - output - .client_line(&format!("failed to resume thread: {err}")) - .ok(); - } - } - true - } - UserCommand::Use(thread_id) => { - let known = client.use_thread(thread_id.clone()); - output.set_prompt(&thread_id); - if known { - output - .client_line(&format!("switched active thread to {thread_id}")) - .ok(); - } else { - output - .client_line(&format!( - "switched active thread to {thread_id} (unknown; use :resume to load)" - )) - .ok(); - } - true - } - UserCommand::RefreshThread => { - match client.request_thread_list(/*cursor*/ None) { - Ok(request_id) => { - output - .client_line(&format!("requested thread list ({request_id:?})")) - .ok(); - } - Err(err) => { - output - .client_line(&format!("failed to list threads: {err}")) - .ok(); - } - } - true - } - } -} - -fn parse_approval_policy(value: &str) -> Result { - match value { - "untrusted" | "unless-trusted" | "unlessTrusted" => Ok(AskForApproval::UnlessTrusted), - "on-failure" | "onFailure" => Ok(AskForApproval::OnFailure), - "on-request" | "onRequest" => Ok(AskForApproval::OnRequest), - "never" => Ok(AskForApproval::Never), - _ => anyhow::bail!( - "unknown approval policy: {value}. Expected one of: untrusted, on-failure, on-request, never" - ), - } -} - -fn drain_events(event_rx: &mpsc::Receiver, output: &Output) { - while let Ok(event) = event_rx.try_recv() { - match event { - ReaderEvent::ThreadReady { thread_id } => { - output - .client_line(&format!("active thread is now {thread_id}")) - .ok(); - output.set_prompt(&thread_id); - } - ReaderEvent::ThreadList { - thread_ids, - next_cursor, - } => { - if thread_ids.is_empty() { - output.client_line("threads: (none)").ok(); - } else { - output.client_line("threads:").ok(); - for thread_id in thread_ids { - output.client_line(&format!(" {thread_id}")).ok(); - } - } - if let Some(next_cursor) = next_cursor { - output - .client_line(&format!( - "more threads available, next cursor: {next_cursor}" - )) - .ok(); - } - } - } - } -} - -fn print_help(output: &Output) { - let _ = output.client_line("commands:"); - let _ = output.client_line(" :help show this help"); - let _ = output.client_line(" :new start a new thread"); - let _ = output.client_line(" :resume resume an existing thread"); - let _ = output.client_line(" :use switch the active thread"); - let _ = output.client_line(" :refresh-thread list available threads"); - let _ = output.client_line(" :quit exit"); - let _ = output.client_line("type a message to send it as a new turn"); -} diff --git a/codex-rs/debug-client/src/output.rs b/codex-rs/debug-client/src/output.rs deleted file mode 100644 index f164a3ade8..0000000000 --- a/codex-rs/debug-client/src/output.rs +++ /dev/null @@ -1,175 +0,0 @@ -#![allow(clippy::expect_used)] -use std::fs::File; -use std::io; -use std::io::IsTerminal; -use std::io::Write; -use std::sync::Arc; -use std::sync::Mutex; - -#[derive(Clone, Copy, Debug)] -pub enum LabelColor { - Assistant, - Tool, - ToolMeta, - Thread, -} - -#[derive(Debug, Default)] -struct PromptState { - thread_id: Option, - visible: bool, -} - -#[derive(Clone, Debug)] -pub struct Output { - lock: Arc>, - prompt: Arc>, - color: bool, - jsonl_file: Option>>, -} - -impl Output { - pub fn new(jsonl_file: Option) -> Self { - let no_color = std::env::var_os("NO_COLOR").is_some(); - let color = !no_color && io::stdout().is_terminal() && io::stderr().is_terminal(); - Self { - lock: Arc::new(Mutex::new(())), - prompt: Arc::new(Mutex::new(PromptState::default())), - color, - jsonl_file: jsonl_file.map(|file| Arc::new(Mutex::new(file))), - } - } - - pub fn server_json_line(&self, line: &str, filtered_output: bool) -> io::Result<()> { - let _guard = self.lock.lock().expect("output lock poisoned"); - - if let Some(file) = self.jsonl_file.as_ref() { - let mut file = file.lock().expect("jsonl file lock poisoned"); - writeln!(file, "{line}")?; - file.flush()?; - } - - if self.jsonl_file.is_none() && !filtered_output { - self.clear_prompt_line_locked()?; - let mut stdout = io::stdout(); - writeln!(stdout, "{line}")?; - stdout.flush()?; - self.redraw_prompt_locked()?; - } - - Ok(()) - } - - pub fn server_line(&self, line: &str) -> io::Result<()> { - let _guard = self.lock.lock().expect("output lock poisoned"); - self.clear_prompt_line_locked()?; - let mut stdout = io::stdout(); - writeln!(stdout, "{line}")?; - stdout.flush()?; - self.redraw_prompt_locked() - } - - pub fn client_line(&self, line: &str) -> io::Result<()> { - let _guard = self.lock.lock().expect("output lock poisoned"); - self.clear_prompt_line_locked()?; - let mut stderr = io::stderr(); - writeln!(stderr, "{line}")?; - stderr.flush() - } - - pub fn prompt(&self, thread_id: &str) -> io::Result<()> { - let _guard = self.lock.lock().expect("output lock poisoned"); - self.set_prompt_locked(thread_id); - self.write_prompt_locked() - } - - pub fn set_prompt(&self, thread_id: &str) { - let _guard = self.lock.lock().expect("output lock poisoned"); - self.set_prompt_locked(thread_id); - } - - pub fn format_label(&self, label: &str, color: LabelColor) -> String { - if !self.color { - return label.to_string(); - } - - let code = match color { - LabelColor::Assistant => "32", - LabelColor::Tool => "36", - LabelColor::ToolMeta => "33", - LabelColor::Thread => "34", - }; - format!("\x1b[{code}m{label}\x1b[0m") - } - - fn clear_prompt_line_locked(&self) -> io::Result<()> { - let mut prompt = self.prompt.lock().expect("prompt lock poisoned"); - if prompt.visible { - let mut stderr = io::stderr(); - writeln!(stderr)?; - stderr.flush()?; - prompt.visible = false; - } - Ok(()) - } - - fn redraw_prompt_locked(&self) -> io::Result<()> { - if self - .prompt - .lock() - .expect("prompt lock poisoned") - .thread_id - .is_some() - { - self.write_prompt_locked()?; - } - Ok(()) - } - - fn set_prompt_locked(&self, thread_id: &str) { - let mut prompt = self.prompt.lock().expect("prompt lock poisoned"); - prompt.thread_id = Some(thread_id.to_string()); - } - - fn write_prompt_locked(&self) -> io::Result<()> { - let mut prompt = self.prompt.lock().expect("prompt lock poisoned"); - let Some(thread_id) = prompt.thread_id.as_ref() else { - return Ok(()); - }; - let mut stderr = io::stderr(); - write!(stderr, "({thread_id})> ")?; - stderr.flush()?; - prompt.visible = true; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use std::fs; - - use super::*; - - #[test] - fn server_json_line_writes_to_configured_file() { - let path = std::env::temp_dir().join(format!( - "codex-debug-client-output-{}.jsonl", - std::process::id() - )); - let file = File::create(&path).expect("create output file"); - let output = Output::new(Some(file)); - - output - .server_json_line(r#"{"id":1}"#, false) - .expect("write unfiltered line"); - output - .server_json_line(r#"{"id":2}"#, true) - .expect("write filtered line"); - - assert_eq!( - fs::read_to_string(&path).expect("read output file"), - "{\"id\":1}\n{\"id\":2}\n" - ); - let _ = fs::remove_file(path); - } -} diff --git a/codex-rs/debug-client/src/reader.rs b/codex-rs/debug-client/src/reader.rs deleted file mode 100644 index cb51641633..0000000000 --- a/codex-rs/debug-client/src/reader.rs +++ /dev/null @@ -1,338 +0,0 @@ -#![allow(clippy::expect_used)] -use std::io::BufRead; -use std::io::BufReader; -use std::process::ChildStdout; -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::mpsc::Sender; -use std::thread; -use std::thread::JoinHandle; - -use anyhow::Context; -use codex_app_server_protocol::CommandExecutionApprovalDecision; -use codex_app_server_protocol::CommandExecutionRequestApprovalResponse; -use codex_app_server_protocol::FileChangeApprovalDecision; -use codex_app_server_protocol::FileChangeRequestApprovalResponse; -use codex_app_server_protocol::JSONRPCMessage; -use codex_app_server_protocol::JSONRPCNotification; -use codex_app_server_protocol::JSONRPCRequest; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ServerRequest; -use codex_app_server_protocol::ThreadItem; -use codex_app_server_protocol::ThreadListResponse; -use codex_app_server_protocol::ThreadResumeResponse; -use codex_app_server_protocol::ThreadStartResponse; -use serde::Serialize; -use std::io::Write; - -use crate::output::LabelColor; -use crate::output::Output; -use crate::state::PendingRequest; -use crate::state::ReaderEvent; -use crate::state::State; - -pub fn start_reader( - mut stdout: BufReader, - stdin: Arc>>, - state: Arc>, - events: Sender, - output: Output, - auto_approve: bool, - filtered_output: bool, -) -> JoinHandle<()> { - thread::spawn(move || { - let command_decision = if auto_approve { - CommandExecutionApprovalDecision::Accept - } else { - CommandExecutionApprovalDecision::Decline - }; - let file_decision = if auto_approve { - FileChangeApprovalDecision::Accept - } else { - FileChangeApprovalDecision::Decline - }; - - let mut buffer = String::new(); - - loop { - buffer.clear(); - match stdout.read_line(&mut buffer) { - Ok(0) => break, - Ok(_) => {} - Err(err) => { - let _ = output.client_line(&format!("failed to read from server: {err}")); - break; - } - } - - let line = buffer.trim_end_matches(['\n', '\r']); - if !line.is_empty() { - let _ = output.server_json_line(line, filtered_output); - } - - let Ok(message) = serde_json::from_str::(line) else { - continue; - }; - - match message { - JSONRPCMessage::Request(request) => { - if let Err(err) = handle_server_request( - request, - &command_decision, - &file_decision, - &stdin, - &output, - ) { - let _ = - output.client_line(&format!("failed to handle server request: {err}")); - } - } - JSONRPCMessage::Response(response) => { - if let Err(err) = handle_response(response, &state, &events) { - let _ = output.client_line(&format!("failed to handle response: {err}")); - } - } - JSONRPCMessage::Notification(notification) => { - if filtered_output - && let Err(err) = handle_filtered_notification(notification, &output) - { - let _ = - output.client_line(&format!("failed to filter notification: {err}")); - } - } - _ => {} - } - } - }) -} - -fn handle_server_request( - request: JSONRPCRequest, - command_decision: &CommandExecutionApprovalDecision, - file_decision: &FileChangeApprovalDecision, - stdin: &Arc>>, - output: &Output, -) -> anyhow::Result<()> { - let server_request = match ServerRequest::try_from(request) { - Ok(server_request) => server_request, - Err(_) => return Ok(()), - }; - - match server_request { - ServerRequest::CommandExecutionRequestApproval { request_id, params } => { - let response = CommandExecutionRequestApprovalResponse { - decision: command_decision.clone(), - }; - output.client_line(&format!( - "auto-response for command approval {request_id:?}: {command_decision:?} ({params:?})" - ))?; - send_response(stdin, request_id, response) - } - ServerRequest::FileChangeRequestApproval { request_id, params } => { - let response = FileChangeRequestApprovalResponse { - decision: file_decision.clone(), - }; - output.client_line(&format!( - "auto-response for file change approval {request_id:?}: {file_decision:?} ({params:?})" - ))?; - send_response(stdin, request_id, response) - } - _ => Ok(()), - } -} - -fn handle_response( - response: JSONRPCResponse, - state: &Arc>, - events: &Sender, -) -> anyhow::Result<()> { - let pending = { - let mut state = state.lock().expect("state lock poisoned"); - state.pending.remove(&response.id) - }; - - let Some(pending) = pending else { - return Ok(()); - }; - - match pending { - PendingRequest::Start => { - let parsed = serde_json::from_value::(response.result) - .context("decode thread/start response")?; - let thread_id = parsed.thread.id; - { - let mut state = state.lock().expect("state lock poisoned"); - state.thread_id = Some(thread_id.clone()); - if !state.known_threads.iter().any(|id| id == &thread_id) { - state.known_threads.push(thread_id.clone()); - } - } - events.send(ReaderEvent::ThreadReady { thread_id }).ok(); - } - PendingRequest::Resume => { - let parsed = serde_json::from_value::(response.result) - .context("decode thread/resume response")?; - let thread_id = parsed.thread.id; - { - let mut state = state.lock().expect("state lock poisoned"); - state.thread_id = Some(thread_id.clone()); - if !state.known_threads.iter().any(|id| id == &thread_id) { - state.known_threads.push(thread_id.clone()); - } - } - events.send(ReaderEvent::ThreadReady { thread_id }).ok(); - } - PendingRequest::List => { - let parsed = serde_json::from_value::(response.result) - .context("decode thread/list response")?; - let thread_ids: Vec = parsed.data.into_iter().map(|thread| thread.id).collect(); - { - let mut state = state.lock().expect("state lock poisoned"); - for thread_id in &thread_ids { - if !state.known_threads.iter().any(|id| id == thread_id) { - state.known_threads.push(thread_id.clone()); - } - } - } - events - .send(ReaderEvent::ThreadList { - thread_ids, - next_cursor: parsed.next_cursor, - }) - .ok(); - } - } - - Ok(()) -} - -fn handle_filtered_notification( - notification: JSONRPCNotification, - output: &Output, -) -> anyhow::Result<()> { - let Ok(server_notification) = ServerNotification::try_from(notification) else { - return Ok(()); - }; - - match server_notification { - ServerNotification::ItemCompleted(payload) => { - emit_filtered_item(payload.item, &payload.thread_id, output) - } - _ => Ok(()), - } -} - -fn emit_filtered_item(item: ThreadItem, thread_id: &str, output: &Output) -> anyhow::Result<()> { - let thread_label = output.format_label(thread_id, LabelColor::Thread); - match item { - ThreadItem::AgentMessage { text, .. } => { - let label = output.format_label("assistant", LabelColor::Assistant); - output.server_line(&format!("{thread_label} {label}: {text}"))?; - } - ThreadItem::Plan { text, .. } => { - let label = output.format_label("assistant", LabelColor::Assistant); - output.server_line(&format!("{thread_label} {label}: plan"))?; - write_multiline(output, &thread_label, &format!("{label}:"), &text)?; - } - ThreadItem::CommandExecution { - command, - status, - exit_code, - aggregated_output, - .. - } => { - let label = output.format_label("tool", LabelColor::Tool); - output.server_line(&format!( - "{thread_label} {label}: command {command} ({status:?})" - ))?; - if let Some(exit_code) = exit_code { - let label = output.format_label("tool exit", LabelColor::ToolMeta); - output.server_line(&format!("{thread_label} {label}: {exit_code}"))?; - } - if let Some(aggregated_output) = aggregated_output { - let label = output.format_label("tool output", LabelColor::ToolMeta); - write_multiline( - output, - &thread_label, - &format!("{label}:"), - &aggregated_output, - )?; - } - } - ThreadItem::FileChange { - changes, status, .. - } => { - let label = output.format_label("tool", LabelColor::Tool); - output.server_line(&format!( - "{thread_label} {label}: file change ({status:?}, {} files)", - changes.len() - ))?; - } - ThreadItem::McpToolCall { - server, - tool, - status, - arguments, - result, - error, - .. - } => { - let label = output.format_label("tool", LabelColor::Tool); - output.server_line(&format!( - "{thread_label} {label}: {server}.{tool} ({status:?})" - ))?; - if !arguments.is_null() { - let label = output.format_label("tool args", LabelColor::ToolMeta); - output.server_line(&format!("{thread_label} {label}: {arguments}"))?; - } - if let Some(result) = result { - let label = output.format_label("tool result", LabelColor::ToolMeta); - output.server_line(&format!("{thread_label} {label}: {result:?}"))?; - } - if let Some(error) = error { - let label = output.format_label("tool error", LabelColor::ToolMeta); - output.server_line(&format!("{thread_label} {label}: {error:?}"))?; - } - } - _ => {} - } - - Ok(()) -} - -fn write_multiline( - output: &Output, - thread_label: &str, - header: &str, - text: &str, -) -> anyhow::Result<()> { - output.server_line(&format!("{thread_label} {header}"))?; - for line in text.lines() { - output.server_line(&format!("{thread_label} {line}"))?; - } - Ok(()) -} - -fn send_response( - stdin: &Arc>>, - request_id: codex_app_server_protocol::RequestId, - response: T, -) -> anyhow::Result<()> { - let result = serde_json::to_value(response).context("serialize response")?; - let message = JSONRPCResponse { - id: request_id, - result, - }; - let json = serde_json::to_string(&message).context("serialize response message")?; - let mut line = json; - line.push('\n'); - - let mut stdin = stdin.lock().expect("stdin lock poisoned"); - let Some(stdin) = stdin.as_mut() else { - anyhow::bail!("stdin already closed"); - }; - stdin.write_all(line.as_bytes()).context("write response")?; - stdin.flush().context("flush response")?; - Ok(()) -} diff --git a/codex-rs/debug-client/src/state.rs b/codex-rs/debug-client/src/state.rs deleted file mode 100644 index 44e2c5f355..0000000000 --- a/codex-rs/debug-client/src/state.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::collections::HashMap; - -use codex_app_server_protocol::RequestId; - -#[derive(Debug, Default)] -pub struct State { - pub pending: HashMap, - pub thread_id: Option, - pub known_threads: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PendingRequest { - Start, - Resume, - List, -} - -#[derive(Debug, Clone)] -pub enum ReaderEvent { - ThreadReady { - thread_id: String, - }, - ThreadList { - thread_ids: Vec, - next_cursor: Option, - }, -} diff --git a/codex-rs/exec-server/src/client/reqwest_http_client.rs b/codex-rs/exec-server/src/client/reqwest_http_client.rs index 44305e466a..9e22fc01d3 100644 --- a/codex-rs/exec-server/src/client/reqwest_http_client.rs +++ b/codex-rs/exec-server/src/client/reqwest_http_client.rs @@ -5,6 +5,7 @@ //! - in a remote environment, that means the remote runtime after the //! orchestrator has forwarded `http/request` over JSON-RPC +use std::error::Error as StdError; use std::time::Duration; use codex_app_server_protocol::JSONRPCErrorError; @@ -135,15 +136,21 @@ impl ReqwestHttpRequestRunner { } let headers = Self::build_headers(params.headers)?; - let mut request = self.client.request(method, url).headers(headers); + let mut request = self.client.request(method.clone(), url).headers(headers); if let Some(body) = params.body { request = request.body(body.into_inner()); } - let response = request - .send() - .await - .map_err(|error| internal_error(format!("http/request failed: {error}")))?; + let response = match request.send().await { + Ok(response) => response, + Err(error) => { + let error_message = error.to_string(); + log_send_error(&method, error); + return Err(internal_error(format!( + "http/request failed: {error_message}" + ))); + } + }; let status = response.status().as_u16(); let headers = Self::response_headers(response.headers()); @@ -265,3 +272,26 @@ impl ReqwestHttpRequestRunner { .collect() } } + +fn log_send_error(method: &Method, error: reqwest::Error) { + let error = error.without_url(); + let source_chain = error_source_chain(&error); + tracing::warn!( + http_method = method.as_str(), + error_is_timeout = error.is_timeout(), + error_is_connect = error.is_connect(), + error = %error, + error_sources = ?source_chain, + "http/request send failed" + ); +} + +fn error_source_chain(error: &reqwest::Error) -> Option { + let mut sources = Vec::new(); + let mut source = error.source(); + while let Some(error) = source { + sources.push(error.to_string()); + source = error.source(); + } + (!sources.is_empty()).then(|| sources.join(": ")) +} diff --git a/codex-rs/exec-server/src/server/transport.rs b/codex-rs/exec-server/src/server/transport.rs index 92b2c77aaa..57d7048e2b 100644 --- a/codex-rs/exec-server/src/server/transport.rs +++ b/codex-rs/exec-server/src/server/transport.rs @@ -1,9 +1,15 @@ use axum::Router; +use axum::body::Body; use axum::extract::ConnectInfo; use axum::extract::State; use axum::extract::ws::WebSocketUpgrade; +use axum::http::Request; use axum::http::StatusCode; +use axum::http::header::ORIGIN; +use axum::middleware; +use axum::middleware::Next; use axum::response::IntoResponse; +use axum::response::Response; use axum::routing::any; use axum::routing::get; use std::io::Write as _; @@ -13,6 +19,7 @@ use tokio::io::AsyncRead; use tokio::io::AsyncWrite; use tokio::net::TcpListener; use tracing::info; +use tracing::warn; use crate::ExecServerRuntimePaths; use crate::connection::JsonRpcConnection; @@ -123,6 +130,7 @@ async fn run_websocket_listener( let router = Router::new() .route("/", any(websocket_upgrade_handler)) .route("/readyz", get(readiness_handler)) + .layer(middleware::from_fn(reject_requests_with_origin_header)) .with_state(ExecServerWebSocketState { processor }); axum::serve( listener, @@ -141,6 +149,22 @@ async fn readiness_handler() -> StatusCode { StatusCode::OK } +async fn reject_requests_with_origin_header( + request: Request, + next: Next, +) -> Result { + if request.headers().contains_key(ORIGIN) { + warn!( + method = %request.method(), + uri = %request.uri(), + "rejecting exec-server websocket listener request with Origin header" + ); + Err(StatusCode::FORBIDDEN) + } else { + Ok(next.run(request).await) + } +} + async fn websocket_upgrade_handler( websocket: WebSocketUpgrade, ConnectInfo(peer_addr): ConnectInfo, diff --git a/codex-rs/exec-server/tests/websocket.rs b/codex-rs/exec-server/tests/websocket.rs index 03b2cabfcd..3d0bebf106 100644 --- a/codex-rs/exec-server/tests/websocket.rs +++ b/codex-rs/exec-server/tests/websocket.rs @@ -9,6 +9,12 @@ use codex_exec_server::InitializeParams; use codex_exec_server::InitializeResponse; use common::exec_server::exec_server; use pretty_assertions::assert_eq; +use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::Error as WebSocketError; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::HeaderValue; +use tokio_tungstenite::tungstenite::http::StatusCode; +use tokio_tungstenite::tungstenite::http::header::ORIGIN; use uuid::Uuid; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -96,3 +102,24 @@ async fn exec_server_accepts_binary_websocket_json() -> anyhow::Result<()> { server.shutdown().await?; Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn exec_server_rejects_browser_origin_websocket_handshake() -> anyhow::Result<()> { + let mut server = exec_server().await?; + let mut request = server.websocket_url().into_client_request()?; + request + .headers_mut() + .insert(ORIGIN, HeaderValue::from_static("https://evil.example")); + + let error = match connect_async(request).await { + Ok(_) => anyhow::bail!("browser-origin websocket handshake should be rejected"), + Err(error) => error, + }; + let WebSocketError::Http(response) = error else { + anyhow::bail!("browser-origin websocket handshake failed unexpectedly: {error}"); + }; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 2df97b5bd7..8d632396b0 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -779,6 +779,7 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> { request_id: request_ids.next(), params: TurnStartParams { thread_id: primary_thread_id_for_span.clone(), + client_user_message_id: None, input: items.into_iter().map(Into::into).collect(), responsesapi_client_metadata: None, additional_context: None, diff --git a/codex-rs/exec/tests/suite/sandbox.rs b/codex-rs/exec/tests/suite/sandbox.rs index 0a5381b1ef..5f6584aa47 100644 --- a/codex-rs/exec/tests/suite/sandbox.rs +++ b/codex-rs/exec/tests/suite/sandbox.rs @@ -44,6 +44,7 @@ async fn spawn_command_under_sandbox( }, permission_profile, sandbox_cwd, + std::slice::from_ref(sandbox_cwd), &codex_linux_sandbox_exe, /*use_legacy_landlock*/ false, ) diff --git a/codex-rs/ext/extension-api/src/contributors.rs b/codex-rs/ext/extension-api/src/contributors.rs index fda295b7f7..71007e3817 100644 --- a/codex-rs/ext/extension-api/src/contributors.rs +++ b/codex-rs/ext/extension-api/src/contributors.rs @@ -26,6 +26,7 @@ pub use tool_lifecycle::ToolFinishInput; pub use tool_lifecycle::ToolLifecycleFuture; pub use tool_lifecycle::ToolStartInput; pub use turn_lifecycle::TurnAbortInput; +pub use turn_lifecycle::TurnErrorInput; pub use turn_lifecycle::TurnStartInput; pub use turn_lifecycle::TurnStopInput; @@ -79,6 +80,9 @@ pub trait TurnLifecycleContributor: Send + Sync { /// Called after the host aborts a running turn. async fn on_turn_abort(&self, _input: TurnAbortInput<'_>) {} + + /// Called when the host observes an error for a running turn. + async fn on_turn_error(&self, _input: TurnErrorInput<'_>) {} } /// Contributor for host-owned configuration changes. diff --git a/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs index 07c7e7fa81..5fbd1562d2 100644 --- a/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/thread_lifecycle.rs @@ -1,9 +1,14 @@ use crate::ExtensionData; +use codex_protocol::protocol::SessionSource; /// Input supplied when the host starts a runtime for a thread. pub struct ThreadStartInput<'a, C> { /// Host configuration visible at thread start. pub config: &'a C, + /// Source that created the session for this thread. + pub session_source: &'a SessionSource, + /// Whether persistent thread-scoped state is available for this thread. + pub persistent_thread_state_available: bool, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. diff --git a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs index bbd3ae8f39..e2c9e4bf7b 100644 --- a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs @@ -1,4 +1,5 @@ use codex_protocol::config_types::CollaborationMode; +use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; @@ -41,3 +42,17 @@ pub struct TurnAbortInput<'a> { /// Store scoped to this turn runtime. pub turn_store: &'a ExtensionData, } + +/// Input supplied when the host observes an error for a turn. +pub struct TurnErrorInput<'a> { + /// Stable host-owned turn identifier. + pub turn_id: &'a str, + /// Error surfaced by the host for this turn. + pub error: CodexErrorInfo, + /// Store scoped to the host session runtime. + pub session_store: &'a ExtensionData, + /// Store scoped to this thread runtime. + pub thread_store: &'a ExtensionData, + /// Store scoped to this turn runtime. + pub turn_store: &'a ExtensionData, +} diff --git a/codex-rs/ext/extension-api/src/lib.rs b/codex-rs/ext/extension-api/src/lib.rs index 80ca67e290..2f00a8dd98 100644 --- a/codex-rs/ext/extension-api/src/lib.rs +++ b/codex-rs/ext/extension-api/src/lib.rs @@ -11,8 +11,11 @@ pub use capabilities::NoopResponseItemInjector; pub use capabilities::ResponseItemInjectionFuture; pub use capabilities::ResponseItemInjector; pub use codex_tools::ConversationHistory; +pub use codex_tools::ExtensionTurnItem; pub use codex_tools::FunctionCallError; +pub use codex_tools::ImageGenerationCompletionFuture; pub use codex_tools::JsonToolOutput; +pub use codex_tools::NoopTurnItemEmitter; pub use codex_tools::ResponsesApiTool; pub use codex_tools::ToolCall; pub use codex_tools::ToolExecutor; @@ -20,6 +23,8 @@ pub use codex_tools::ToolName; pub use codex_tools::ToolOutput; pub use codex_tools::ToolPayload; pub use codex_tools::ToolSpec; +pub use codex_tools::TurnItemEmissionFuture; +pub use codex_tools::TurnItemEmitter; pub use codex_tools::parse_tool_input_schema; pub use codex_tools::parse_tool_input_schema_without_compaction; pub use contributors::ApprovalReviewContributor; @@ -41,6 +46,7 @@ pub use contributors::ToolLifecycleContributor; pub use contributors::ToolLifecycleFuture; pub use contributors::ToolStartInput; pub use contributors::TurnAbortInput; +pub use contributors::TurnErrorInput; pub use contributors::TurnItemContributor; pub use contributors::TurnLifecycleContributor; pub use contributors::TurnStartInput; diff --git a/codex-rs/ext/goal/src/extension.rs b/codex-rs/ext/goal/src/extension.rs index 68068acbb4..e09f041e31 100644 --- a/codex-rs/ext/goal/src/extension.rs +++ b/codex-rs/ext/goal/src/extension.rs @@ -17,11 +17,15 @@ use codex_extension_api::ToolFinishInput; use codex_extension_api::ToolLifecycleContributor; use codex_extension_api::ToolLifecycleFuture; use codex_extension_api::TurnAbortInput; +use codex_extension_api::TurnErrorInput; use codex_extension_api::TurnLifecycleContributor; use codex_extension_api::TurnStartInput; use codex_extension_api::TurnStopInput; use codex_otel::MetricsClient; use codex_protocol::ThreadId; +use codex_protocol::protocol::CodexErrorInfo; +use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadGoalStatus; use codex_protocol::protocol::TokenUsageInfo; @@ -29,6 +33,7 @@ use crate::accounting::BudgetLimitedGoalDisposition; use crate::accounting::GoalAccountingState; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; +use crate::runtime::GoalRuntimeConfig; use crate::runtime::GoalRuntimeHandle; use crate::spec::UPDATE_GOAL_TOOL_NAME; use crate::steering::budget_limit_steering_item; @@ -85,6 +90,11 @@ where { async fn on_thread_start(&self, input: ThreadStartInput<'_, C>) { let enabled = (self.goals_enabled)(input.config); + let tools_available_for_thread = input.persistent_thread_state_available + && !matches!( + input.session_source, + SessionSource::SubAgent(SubAgentSource::Review) + ); input .thread_store .insert(GoalExtensionConfig::from_enabled(enabled)); @@ -102,7 +112,10 @@ where self.metrics.clone(), self.thread_manager.clone(), accounting_state, - enabled, + GoalRuntimeConfig { + enabled, + tools_available_for_thread, + }, ) }); runtime.set_enabled(enabled); @@ -237,6 +250,22 @@ where } runtime.accounting_state().finish_turn(turn_id); } + + async fn on_turn_error(&self, input: TurnErrorInput<'_>) { + if input.error != CodexErrorInfo::UsageLimitExceeded { + return; + } + let Some(runtime) = goal_runtime_handle(input.thread_store) else { + return; + }; + + if let Err(err) = runtime + .usage_limit_active_goal_for_turn(input.turn_id) + .await + { + tracing::warn!("failed to usage-limit active goal after usage-limit error: {err}"); + } + } } #[async_trait] @@ -330,7 +359,7 @@ where let Some(runtime) = goal_runtime_handle(thread_store) else { return Vec::new(); }; - if !runtime.is_enabled() { + if !runtime.tools_visible() { return Vec::new(); } diff --git a/codex-rs/ext/goal/src/runtime.rs b/codex-rs/ext/goal/src/runtime.rs index 16a4ff6a2f..f077ddc54c 100644 --- a/codex-rs/ext/goal/src/runtime.rs +++ b/codex-rs/ext/goal/src/runtime.rs @@ -5,7 +5,7 @@ use std::sync::atomic::Ordering; use codex_core::ThreadManager; use codex_protocol::ThreadId; -use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ThreadGoal; use crate::accounting::BudgetLimitedGoalDisposition; @@ -20,6 +20,11 @@ pub struct GoalRuntimeHandle { inner: Arc, } +pub(crate) struct GoalRuntimeConfig { + pub(crate) enabled: bool, + pub(crate) tools_available_for_thread: bool, +} + struct GoalRuntimeInner { thread_id: ThreadId, state_dbs: Arc, @@ -28,6 +33,7 @@ struct GoalRuntimeInner { thread_manager: Weak, accounting_state: Arc, enabled: AtomicBool, + tools_available_for_thread: bool, } pub(crate) struct AccountedGoalProgress { @@ -66,7 +72,7 @@ impl GoalRuntimeHandle { metrics: GoalMetrics, thread_manager: Weak, accounting_state: Arc, - enabled: bool, + config: GoalRuntimeConfig, ) -> Self { Self { inner: Arc::new(GoalRuntimeInner { @@ -76,7 +82,8 @@ impl GoalRuntimeHandle { metrics, thread_manager, accounting_state, - enabled: AtomicBool::new(enabled), + enabled: AtomicBool::new(config.enabled), + tools_available_for_thread: config.tools_available_for_thread, }), } } @@ -89,6 +96,10 @@ impl GoalRuntimeHandle { self.inner.enabled.load(Ordering::Relaxed) } + pub(crate) fn tools_visible(&self) -> bool { + self.is_enabled() && self.inner.tools_available_for_thread + } + pub(crate) fn thread_id(&self) -> ThreadId { self.inner.thread_id } @@ -264,7 +275,7 @@ impl GoalRuntimeHandle { Ok(()) } - pub(crate) async fn inject_active_turn_steering(&self, item: ResponseInputItem) { + pub(crate) async fn inject_active_turn_steering(&self, item: ResponseItem) { let Some(thread_manager) = self.inner.thread_manager.upgrade() else { tracing::debug!("skipping goal steering because thread manager is unavailable"); return; @@ -273,11 +284,7 @@ impl GoalRuntimeHandle { tracing::debug!("skipping goal steering because live thread is unavailable"); return; }; - if thread - .inject_response_items_into_active_turn(vec![item]) - .await - .is_err() - { + if thread.inject_if_running(vec![item]).await.is_err() { tracing::debug!("skipping goal steering because no turn is active"); } } diff --git a/codex-rs/ext/goal/src/steering.rs b/codex-rs/ext/goal/src/steering.rs index 83f41ea538..e540ee171d 100644 --- a/codex-rs/ext/goal/src/steering.rs +++ b/codex-rs/ext/goal/src/steering.rs @@ -1,14 +1,22 @@ use codex_core::context::ContextualUserFragment; -use codex_core::context::GoalContext; -use codex_protocol::models::ResponseInputItem; +use codex_core::context::InternalContextSource; +use codex_core::context::InternalModelContextFragment; +use codex_protocol::models::ResponseItem; use codex_protocol::protocol::ThreadGoal; -pub(crate) fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseInputItem { - GoalContext::new(budget_limit_prompt(goal)).into_response_input_item() +pub(crate) fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseItem { + goal_context_input_item(budget_limit_prompt(goal)) } -pub(crate) fn objective_updated_steering_item(goal: &ThreadGoal) -> ResponseInputItem { - GoalContext::new(objective_updated_prompt(goal)).into_response_input_item() +pub(crate) fn objective_updated_steering_item(goal: &ThreadGoal) -> ResponseItem { + goal_context_input_item(objective_updated_prompt(goal)) +} + +fn goal_context_input_item(prompt: String) -> ResponseItem { + ContextualUserFragment::into(InternalModelContextFragment::new( + InternalContextSource::from_static("goal"), + prompt, + )) } fn budget_limit_prompt(goal: &ThreadGoal) -> String { diff --git a/codex-rs/ext/goal/tests/goal_extension_backend.rs b/codex-rs/ext/goal/tests/goal_extension_backend.rs index 584f7362b7..92f4313fc7 100644 --- a/codex-rs/ext/goal/tests/goal_extension_backend.rs +++ b/codex-rs/ext/goal/tests/goal_extension_backend.rs @@ -8,6 +8,7 @@ use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionEventSink; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::FunctionCallError; +use codex_extension_api::NoopTurnItemEmitter; use codex_extension_api::ThreadResumeInput; use codex_extension_api::ThreadStartInput; use codex_extension_api::ToolCall; @@ -16,6 +17,7 @@ use codex_extension_api::ToolCallSource; use codex_extension_api::ToolExecutor; use codex_extension_api::ToolFinishInput; use codex_extension_api::ToolPayload; +use codex_extension_api::TurnErrorInput; use codex_extension_api::TurnStartInput; use codex_extension_api::TurnStopInput; use codex_goal_extension::GoalRuntimeHandle; @@ -25,9 +27,11 @@ use codex_protocol::ThreadId; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::ModeKind; use codex_protocol::config_types::Settings; +use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadGoalStatus; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; @@ -83,6 +87,38 @@ async fn installed_goal_tools_create_goal_and_fill_empty_preview() -> anyhow::Re Ok(()) } +#[tokio::test] +async fn goal_tools_hidden_for_ephemeral_threads() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + let tools = installed_tools_with_start( + runtime, + thread_id, + SessionSource::Cli, + /*persistent_thread_state_available*/ false, + ) + .await; + + assert_eq!(Vec::::new(), tool_names(&tools)); + Ok(()) +} + +#[tokio::test] +async fn goal_tools_hidden_for_review_subagents() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + let tools = installed_tools_with_start( + runtime, + thread_id, + SessionSource::SubAgent(SubAgentSource::Review), + /*persistent_thread_state_available*/ true, + ) + .await; + + assert_eq!(Vec::::new(), tool_names(&tools)); + Ok(()) +} + #[tokio::test] async fn installed_goal_tools_reject_duplicate_goal_creation() -> anyhow::Result<()> { let runtime = test_runtime().await?; @@ -364,7 +400,7 @@ async fn budget_limited_goal_keeps_accounting_after_later_tool_finish() -> anyho } #[tokio::test] -async fn usage_limit_active_goal_accounts_progress_and_clears_accounting() -> anyhow::Result<()> { +async fn turn_error_usage_limit_accounts_progress_and_clears_accounting() -> anyhow::Result<()> { let runtime = test_runtime().await?; let thread_id = test_thread_id()?; seed_thread_metadata(runtime.as_ref(), thread_id).await?; @@ -391,11 +427,18 @@ async fn usage_limit_active_goal_accounts_progress_and_clears_accounting() -> an ), ) .await; - harness - .runtime_handle() - .usage_limit_active_goal_for_turn("turn-1") - .await - .map_err(anyhow::Error::msg)?; + let turn_store = ExtensionData::new("turn-1"); + for contributor in harness.registry.turn_lifecycle_contributors() { + contributor + .on_turn_error(TurnErrorInput { + turn_id: "turn-1", + error: CodexErrorInfo::UsageLimitExceeded, + session_store: &harness.session_store, + thread_store: &harness.thread_store, + turn_store: &turn_store, + }) + .await; + } let goal = runtime .thread_goals() @@ -877,6 +920,21 @@ async fn thread_resume_rehydrates_active_goal_idle_accounting() -> anyhow::Resul async fn installed_tools( runtime: Arc, thread_id: ThreadId, +) -> Vec>> { + installed_tools_with_start( + runtime, + thread_id, + SessionSource::Cli, + /*persistent_thread_state_available*/ true, + ) + .await +} + +async fn installed_tools_with_start( + runtime: Arc, + thread_id: ThreadId, + session_source: SessionSource, + persistent_thread_state_available: bool, ) -> Vec>> { let mut builder = ExtensionRegistryBuilder::<()>::new(); install_with_backend( @@ -893,6 +951,8 @@ async fn installed_tools( contributor .on_thread_start(ThreadStartInput { config: &(), + session_source: &session_source, + persistent_thread_state_available, session_store: &session_store, thread_store: &thread_store, }) @@ -906,6 +966,10 @@ async fn installed_tools( .collect() } +fn tool_names(tools: &[Arc>]) -> Vec { + tools.iter().map(|tool| tool.tool_name().name).collect() +} + struct GoalExtensionHarness { registry: codex_extension_api::ExtensionRegistry<()>, session_store: ExtensionData, @@ -930,10 +994,13 @@ impl GoalExtensionHarness { let registry = builder.build(); let session_store = ExtensionData::new("session-1"); let thread_store = ExtensionData::new(thread_id.to_string()); + let session_source = SessionSource::Cli; for contributor in registry.thread_lifecycle_contributors() { contributor .on_thread_start(ThreadStartInput { config: &(), + session_source: &session_source, + persistent_thread_state_available: true, session_store: &session_store, thread_store: &thread_store, }) @@ -1064,6 +1131,7 @@ fn tool_call(tool_name: &str, call_id: &str, arguments: serde_json::Value) -> To tool_name: codex_extension_api::ToolName::plain(tool_name), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload: ToolPayload::Function { arguments: arguments.to_string(), }, diff --git a/codex-rs/ext/image-generation/BUILD.bazel b/codex-rs/ext/image-generation/BUILD.bazel new file mode 100644 index 0000000000..5ed05a5dc8 --- /dev/null +++ b/codex-rs/ext/image-generation/BUILD.bazel @@ -0,0 +1,9 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "image-generation", + crate_name = "codex_image_generation_extension", + compile_data = [ + "imagegen_description.md", + ], +) diff --git a/codex-rs/ext/image-generation/Cargo.toml b/codex-rs/ext/image-generation/Cargo.toml new file mode 100644 index 0000000000..995f1786bc --- /dev/null +++ b/codex-rs/ext/image-generation/Cargo.toml @@ -0,0 +1,32 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-image-generation-extension" +version.workspace = true + +[lib] +name = "codex_image_generation_extension" +path = "src/lib.rs" +doctest = false + +[lints] +workspace = true + +[dependencies] +async-trait = { workspace = true } +codex-api = { workspace = true } +codex-core = { workspace = true } +codex-extension-api = { workspace = true } +codex-features = { workspace = true } +codex-login = { workspace = true } +codex-model-provider = { workspace = true } +codex-model-provider-info = { workspace = true } +codex-protocol = { workspace = true } +codex-tools = { workspace = true } +http = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } diff --git a/codex-rs/ext/image-generation/imagegen_description.md b/codex-rs/ext/image-generation/imagegen_description.md new file mode 100644 index 0000000000..7ae6ecb5fa --- /dev/null +++ b/codex-rs/ext/image-generation/imagegen_description.md @@ -0,0 +1,11 @@ +The `image_gen.imagegen` tool enables image generation from descriptions and editing of existing images based on specific instructions. Use it when: + +- The user requests an image based on a scene description, such as a diagram, portrait, comic, meme, or any other visual. +- The user wants to modify an attached or previously generated image with specific changes, including adding or removing elements, altering colors, improving quality/resolution, or transforming the style (e.g., cartoon, oil painting). + +Guidelines: +- Set `action` to `generate` when the user asks for a brand new image. +- Set `action` to `edit` when the user asks to modify an existing image from the conversation history. +- Directly generate the image without reconfirmation or clarification. +- After each image generation, do not mention anything related to download. Do not summarize the image. Do not ask followup question. Do not say ANYTHING after you generate an image. +- Always use this tool for image editing unless the user explicitly requests otherwise. Do not use the `python` tool for image editing unless specifically instructed. diff --git a/codex-rs/ext/image-generation/src/backend.rs b/codex-rs/ext/image-generation/src/backend.rs new file mode 100644 index 0000000000..9b837772c7 --- /dev/null +++ b/codex-rs/ext/image-generation/src/backend.rs @@ -0,0 +1,60 @@ +use codex_api::ImageEditRequest; +use codex_api::ImageGenerationRequest; +use codex_api::ImageResponse; +use codex_api::ImagesClient; +use codex_api::ReqwestTransport; +use codex_login::default_client::build_reqwest_client; +use codex_model_provider::SharedModelProvider; +use http::HeaderMap; + +#[derive(Clone)] +pub(crate) struct CodexImagesBackend { + provider: SharedModelProvider, +} + +impl CodexImagesBackend { + /// Creates a backend that sends image requests through the active model provider. + pub(crate) fn new(provider: SharedModelProvider) -> Self { + Self { provider } + } + + /// Resolves the provider and auth required for the current image API request. + async fn client(&self) -> Result, String> { + let provider = self + .provider + .api_provider() + .await + .map_err(|err| err.to_string())?; + let auth = self + .provider + .api_auth() + .await + .map_err(|err| err.to_string())?; + Ok(ImagesClient::new( + ReqwestTransport::new(build_reqwest_client()), + provider, + auth, + )) + } + + /// Sends a standalone image generation request through the configured Images client. + pub(crate) async fn generate( + &self, + request: ImageGenerationRequest, + ) -> Result { + self.client() + .await? + .generate(&request, HeaderMap::new()) + .await + .map_err(|err| err.to_string()) + } + + /// Sends a standalone image edit request through the configured Images client. + pub(crate) async fn edit(&self, request: ImageEditRequest) -> Result { + self.client() + .await? + .edit(&request, HeaderMap::new()) + .await + .map_err(|err| err.to_string()) + } +} diff --git a/codex-rs/ext/image-generation/src/extension.rs b/codex-rs/ext/image-generation/src/extension.rs new file mode 100644 index 0000000000..f7a9f2406f --- /dev/null +++ b/codex-rs/ext/image-generation/src/extension.rs @@ -0,0 +1,91 @@ +use std::sync::Arc; + +use codex_core::config::Config; +use codex_extension_api::ConfigContributor; +use codex_extension_api::ExtensionData; +use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::ThreadLifecycleContributor; +use codex_extension_api::ThreadStartInput; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolContributor; +use codex_extension_api::ToolExecutor; +use codex_features::Feature; +use codex_login::AuthManager; +use codex_model_provider::create_model_provider; +use codex_model_provider_info::ModelProviderInfo; + +use crate::backend::CodexImagesBackend; +use crate::tool::ImageGenerationTool; + +#[derive(Clone)] +struct ImageGenerationExtension { + auth_manager: Arc, +} + +#[derive(Clone)] +struct ImageGenerationExtensionConfig { + enabled: bool, + provider: ModelProviderInfo, +} + +impl From<&Config> for ImageGenerationExtensionConfig { + /// Resolves whether standalone image generation should be available for a thread. + fn from(config: &Config) -> Self { + Self { + enabled: config.features.enabled(Feature::ImageGenExt) + && config.model_provider.is_openai(), + provider: config.model_provider.clone(), + } + } +} + +#[async_trait::async_trait] +impl ThreadLifecycleContributor for ImageGenerationExtension { + /// Seeds image-generation availability when a thread begins. + async fn on_thread_start(&self, input: ThreadStartInput<'_, Config>) { + input + .thread_store + .insert(ImageGenerationExtensionConfig::from(input.config)); + } +} + +impl ConfigContributor for ImageGenerationExtension { + /// Refreshes image-generation availability after thread configuration changes. + fn on_config_changed( + &self, + _session_store: &ExtensionData, + thread_store: &ExtensionData, + _previous_config: &Config, + new_config: &Config, + ) { + thread_store.insert(ImageGenerationExtensionConfig::from(new_config)); + } +} + +impl ToolContributor for ImageGenerationExtension { + /// Creates the image-generation tool exposed by this installed extension. + fn tools( + &self, + _session_store: &ExtensionData, + thread_store: &ExtensionData, + ) -> Vec>> { + let Some(config) = thread_store.get::() else { + return Vec::new(); + }; + if !config.enabled || !self.auth_manager.current_auth_uses_codex_backend() { + return Vec::new(); + } + + vec![Arc::new(ImageGenerationTool::new(CodexImagesBackend::new( + create_model_provider(config.provider.clone(), Some(self.auth_manager.clone())), + )))] + } +} + +/// Installs the feature-gated standalone image-generation extension contributors. +pub fn install(registry: &mut ExtensionRegistryBuilder, auth_manager: Arc) { + let extension = Arc::new(ImageGenerationExtension { auth_manager }); + registry.thread_lifecycle_contributor(extension.clone()); + registry.config_contributor(extension.clone()); + registry.tool_contributor(extension); +} diff --git a/codex-rs/ext/image-generation/src/lib.rs b/codex-rs/ext/image-generation/src/lib.rs new file mode 100644 index 0000000000..63f1ab2482 --- /dev/null +++ b/codex-rs/ext/image-generation/src/lib.rs @@ -0,0 +1,8 @@ +mod backend; +mod extension; +mod tool; + +pub use extension::install; + +pub(crate) const IMAGE_GEN_NAMESPACE: &str = "image_gen"; +pub(crate) const IMAGEGEN_TOOL_NAME: &str = "imagegen"; diff --git a/codex-rs/ext/image-generation/src/tests.rs b/codex-rs/ext/image-generation/src/tests.rs new file mode 100644 index 0000000000..f866a9018b --- /dev/null +++ b/codex-rs/ext/image-generation/src/tests.rs @@ -0,0 +1,319 @@ +use codex_api::ImageBackground; +use codex_api::ImageEditRequest; +use codex_api::ImageGenerationRequest; +use codex_api::ImageQuality; +use codex_api::ImageUrl; +use codex_extension_api::ToolOutput; +use codex_extension_api::ToolPayload; +use codex_extension_api::ToolSpec; +use codex_protocol::models::ContentItem; +use codex_protocol::models::DEFAULT_IMAGE_DETAIL; +use codex_protocol::models::FunctionCallOutputBody; +use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; +use codex_tools::ResponsesApiNamespaceTool; +use pretty_assertions::assert_eq; + +use super::GeneratedImageOutput; +use super::ImageRequest; +use super::ImagegenAction; +use super::ImagegenArgs; +use super::imagegen_tool_spec; +use super::request_for_action; +use crate::IMAGE_GEN_NAMESPACE; +use crate::IMAGEGEN_TOOL_NAME; + +const RESULT: &str = "cG5n"; +const OUTPUT_HINT: &str = "Generated images are saved to /tmp as /tmp/call-1.png by default."; + +#[test] +fn uses_reserved_image_gen_namespace() { + let ToolSpec::Namespace(spec) = imagegen_tool_spec() else { + panic!("imagegen should advertise a namespace tool"); + }; + assert_eq!(spec.name, IMAGE_GEN_NAMESPACE); + let ResponsesApiNamespaceTool::Function(function) = &spec.tools[0]; + assert_eq!(function.name, IMAGEGEN_TOOL_NAME); +} + +#[test] +fn generate_uses_fixed_request_defaults() { + assert_eq!( + request_for_action(&args(ImagegenAction::Generate, "paint a moonlit lake"), &[]) + .expect("generation request should build"), + ImageRequest::Generate(ImageGenerationRequest { + prompt: "paint a moonlit lake".to_string(), + background: Some(ImageBackground::Auto), + model: "gpt-image-2".to_string(), + n: None, + quality: Some(ImageQuality::Auto), + size: Some("auto".to_string()), + }) + ); +} + +#[test] +fn generated_output_returns_image_input_and_output_hint() { + let output = GeneratedImageOutput { + result: RESULT.to_string(), + output_hint: Some(OUTPUT_HINT.to_string()), + }; + + let ResponseInputItem::FunctionCallOutput { + output: response_output, + .. + } = output.to_response_item("call-1", &function_payload()) + else { + panic!("imagegen should return function tool output"); + }; + let FunctionCallOutputBody::ContentItems(content_items) = response_output.body else { + panic!("imagegen output should contain generated image bytes"); + }; + assert_eq!( + content_items, + vec![ + FunctionCallOutputContentItem::InputImage { + image_url: format!("data:image/png;base64,{RESULT}"), + detail: Some(DEFAULT_IMAGE_DETAIL), + }, + FunctionCallOutputContentItem::InputText { + text: OUTPUT_HINT.to_string(), + }, + ] + ); +} + +#[test] +fn edit_matches_context_selector_for_generated_images_after_latest_user_anchor() { + let history = vec![ + generated_item("g1"), + generated_item("g2"), + generated_item("g3"), + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ + ContentItem::InputImage { + image_url: "data:image/png;base64,u1".to_string(), + detail: None, + }, + ContentItem::InputImage { + image_url: "data:image/png;base64,u2".to_string(), + detail: None, + }, + ], + phase: None, + }, + generated_item("g4"), + generated_item("g5"), + generated_item("g6"), + generated_item("g7"), + ]; + + assert_eq!( + edit_request("change the lighting", &history), + expected_edit_request( + "change the lighting", + &[ + "data:image/png;base64,u1", + "data:image/png;base64,u2", + "data:image/png;base64,g5", + "data:image/png;base64,g6", + "data:image/png;base64,g7", + ] + ) + ); +} + +#[test] +fn edit_preserves_a_generated_image_when_user_anchor_fills_the_limit() { + let history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: ["a", "b", "c", "d", "e"] + .into_iter() + .map(|image| ContentItem::InputImage { + image_url: format!("data:image/png;base64,{image}"), + detail: None, + }) + .collect(), + phase: None, + }, + generated_item("generated"), + ]; + + assert_eq!( + edit_request("edit the last generated image", &history), + expected_edit_request( + "edit the last generated image", + &[ + "data:image/png;base64,b", + "data:image/png;base64,c", + "data:image/png;base64,d", + "data:image/png;base64,e", + "data:image/png;base64,generated", + ] + ) + ); +} + +#[test] +fn edit_uses_latest_user_upload_before_a_text_only_follow_up() { + let history = vec![ + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputImage { + image_url: "data:image/png;base64,user".to_string(), + detail: None, + }], + phase: None, + }, + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "edit this image".to_string(), + }], + phase: None, + }, + ]; + + assert_eq!( + edit_request("change the lighting", &history), + expected_edit_request("change the lighting", &["data:image/png;base64,user"]) + ); +} + +#[test] +fn edit_reuses_images_from_prior_standalone_imagegen_calls() { + let history = vec![ + ResponseItem::FunctionCall { + id: None, + name: IMAGEGEN_TOOL_NAME.to_string(), + namespace: Some(IMAGE_GEN_NAMESPACE.to_string()), + arguments: "{}".to_string(), + call_id: "imagegen-1".to_string(), + }, + generated_function_output("imagegen-1", "standalone"), + ]; + + assert_eq!( + edit_request("change the lighting", &history), + expected_edit_request("change the lighting", &["data:image/png;base64,standalone"]) + ); +} + +#[test] +fn edit_keeps_newest_standalone_generated_images_when_over_limit() { + let history = (1..=6) + .flat_map(|index| { + let call_id = format!("imagegen-{index}"); + vec![ + ResponseItem::FunctionCall { + id: None, + name: IMAGEGEN_TOOL_NAME.to_string(), + namespace: Some(IMAGE_GEN_NAMESPACE.to_string()), + arguments: "{}".to_string(), + call_id: call_id.clone(), + }, + generated_function_output(&call_id, &index.to_string()), + ] + }) + .collect::>(); + + assert_eq!( + edit_request("change the lighting", &history), + expected_edit_request( + "change the lighting", + &[ + "data:image/png;base64,2", + "data:image/png;base64,3", + "data:image/png;base64,4", + "data:image/png;base64,5", + "data:image/png;base64,6", + ] + ) + ); +} + +#[test] +fn edit_without_image_history_returns_tool_error() { + let error = request_for_action(&args(ImagegenAction::Edit, "change the lighting"), &[]) + .expect_err("edit should require image context"); + + assert_eq!( + error.to_string(), + "image edit requested without any usable image in conversation history" + ); +} + +fn args(action: ImagegenAction, prompt: &str) -> ImagegenArgs { + ImagegenArgs { + prompt: prompt.to_string(), + action, + } +} + +fn edit_request(prompt: &str, history: &[ResponseItem]) -> ImageEditRequest { + let ImageRequest::Edit(request) = + request_for_action(&args(ImagegenAction::Edit, prompt), history) + .expect("edit request should build") + else { + panic!("expected edit request"); + }; + request +} + +fn expected_edit_request(prompt: &str, images: &[&str]) -> ImageEditRequest { + ImageEditRequest { + images: images + .iter() + .map(|image_url| ImageUrl { + image_url: (*image_url).to_string(), + }) + .collect(), + prompt: prompt.to_string(), + background: Some(ImageBackground::Auto), + model: "gpt-image-2".to_string(), + n: None, + quality: Some(ImageQuality::Auto), + size: Some("auto".to_string()), + } +} + +fn generated_item(result: &str) -> ResponseItem { + ResponseItem::ImageGenerationCall { + id: format!("id-{result}"), + status: "completed".to_string(), + revised_prompt: None, + result: result.to_string(), + } +} + +fn generated_function_output(call_id: &str, result: &str) -> ResponseItem { + ResponseItem::FunctionCallOutput { + call_id: call_id.to_string(), + output: FunctionCallOutputPayload { + body: FunctionCallOutputBody::ContentItems(vec![ + FunctionCallOutputContentItem::InputImage { + image_url: format!("data:image/png;base64,{result}"), + detail: Some(DEFAULT_IMAGE_DETAIL), + }, + FunctionCallOutputContentItem::InputText { + text: "generated image save hint".to_string(), + }, + ]), + success: Some(true), + }, + } +} + +fn function_payload() -> ToolPayload { + ToolPayload::Function { + arguments: "{}".to_string(), + } +} diff --git a/codex-rs/ext/image-generation/src/tool.rs b/codex-rs/ext/image-generation/src/tool.rs new file mode 100644 index 0000000000..75a79db2bf --- /dev/null +++ b/codex-rs/ext/image-generation/src/tool.rs @@ -0,0 +1,324 @@ +use codex_api::ImageBackground; +use codex_api::ImageEditRequest; +use codex_api::ImageGenerationRequest; +use codex_api::ImageQuality; +use codex_api::ImageUrl; +use codex_extension_api::FunctionCallError; +use codex_extension_api::ToolCall; +use codex_extension_api::ToolExecutor; +use codex_extension_api::ToolName; +use codex_extension_api::ToolOutput; +use codex_extension_api::ToolPayload; +use codex_extension_api::ToolSpec; +use codex_extension_api::parse_tool_input_schema; +use codex_protocol::models::ContentItem; +use codex_protocol::models::DEFAULT_IMAGE_DETAIL; +use codex_protocol::models::FunctionCallOutputBody; +use codex_protocol::models::FunctionCallOutputContentItem; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseInputItem; +use codex_protocol::models::ResponseItem; +use codex_tools::ResponsesApiNamespace; +use codex_tools::ResponsesApiNamespaceTool; +use codex_tools::ResponsesApiTool; +use codex_tools::ToolExposure; +use codex_tools::default_namespace_description; +use schemars::JsonSchema; +use schemars::r#gen::SchemaSettings; +use serde::Deserialize; +use serde_json::Map; +use serde_json::Value; + +use crate::IMAGE_GEN_NAMESPACE; +use crate::IMAGEGEN_TOOL_NAME; +use crate::backend::CodexImagesBackend; + +const IMAGE_MODEL: &str = "gpt-image-2"; +const MAX_EDIT_IMAGES: usize = 5; +const IMAGEGEN_DESCRIPTION: &str = include_str!("../imagegen_description.md"); + +#[derive(Clone)] +pub(crate) struct ImageGenerationTool { + backend: CodexImagesBackend, +} + +impl ImageGenerationTool { + /// Creates an image-generation tool backed by an image API executor. + pub(crate) fn new(backend: CodexImagesBackend) -> Self { + Self { backend } + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +struct ImagegenArgs { + prompt: String, + action: ImagegenAction, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +enum ImagegenAction { + Generate, + Edit, +} + +#[async_trait::async_trait] +impl ToolExecutor for ImageGenerationTool { + /// Keeps the tool in the existing image-generation Responses namespace. + fn tool_name(&self) -> ToolName { + ToolName::namespaced(IMAGE_GEN_NAMESPACE, IMAGEGEN_TOOL_NAME) + } + + /// Advertises the model contract: a rewritten prompt and semantic action. + fn spec(&self) -> ToolSpec { + imagegen_tool_spec() + } + + /// Keeps this model-facing tool out of the nested code-mode tool surface. + fn exposure(&self) -> ToolExposure { + ToolExposure::DirectModelOnly + } + + /// Executes the selected image operation and returns the completed image result. + async fn handle(&self, call: ToolCall) -> Result, FunctionCallError> { + let args = parse_args(&call)?; + let request = request_for_action(&args, call.conversation_history.items())?; + let response = match request { + ImageRequest::Generate(request) => self.backend.generate(request).await, + ImageRequest::Edit(request) => self.backend.edit(request).await, + } + .map_err(|err| { + FunctionCallError::RespondToModel(format!("image generation failed: {err}")) + })?; + let Some(result) = response.data.into_iter().next().map(|data| data.b64_json) else { + return Err(FunctionCallError::RespondToModel( + "image generation returned no image data".to_string(), + )); + }; + let output_hint = call + .turn_item_emitter + .image_generation_completed(call.call_id.clone(), args.prompt, result.clone()) + .await; + Ok(Box::new(GeneratedImageOutput { + result, + output_hint, + })) + } +} + +#[derive(Debug, PartialEq)] +enum ImageRequest { + Generate(ImageGenerationRequest), + Edit(ImageEditRequest), +} + +/// Maps the model-selected action to the fixed image API request parameters. +fn request_for_action( + args: &ImagegenArgs, + history: &[ResponseItem], +) -> Result { + match args.action { + ImagegenAction::Generate => Ok(ImageRequest::Generate(ImageGenerationRequest { + prompt: args.prompt.clone(), + background: Some(ImageBackground::Auto), + model: IMAGE_MODEL.to_string(), + n: None, + quality: Some(ImageQuality::Auto), + size: Some("auto".to_string()), + })), + ImagegenAction::Edit => { + let images = edit_images(history); + if images.is_empty() { + return Err(FunctionCallError::RespondToModel( + "image edit requested without any usable image in conversation history" + .to_string(), + )); + } + Ok(ImageRequest::Edit(ImageEditRequest { + images, + prompt: args.prompt.clone(), + background: Some(ImageBackground::Auto), + model: IMAGE_MODEL.to_string(), + n: None, + quality: Some(ImageQuality::Auto), + size: Some("auto".to_string()), + })) + } + } +} + +/// Selects edit context using the hosted imagegen anchor and truncation behavior. +fn edit_images(history: &[ResponseItem]) -> Vec { + let latest_uploaded_images = history.iter().enumerate().rev().find_map(|(index, item)| { + let ResponseItem::Message { role, content, .. } = item else { + return None; + }; + if role != "user" { + return None; + } + let images = content + .iter() + .filter_map(|item| match item { + ContentItem::InputImage { image_url, .. } => Some(ImageUrl { + image_url: image_url.clone(), + }), + ContentItem::InputText { .. } | ContentItem::OutputText { .. } => None, + }) + .collect::>(); + (!images.is_empty()).then_some((index, images)) + }); + let (user_images, follow_up_start) = latest_uploaded_images + .map_or_else(|| (Vec::new(), 0), |(index, images)| (images, index + 1)); + let mut generated_images = Vec::new(); + for item in &history[follow_up_start..] { + match item { + ResponseItem::ImageGenerationCall { result, .. } if !result.is_empty() => { + generated_images.push(ImageUrl { + image_url: format!("data:image/png;base64,{result}"), + }); + } + ResponseItem::FunctionCallOutput { call_id, output } + if history.iter().any(|item| { + matches!( + item, + ResponseItem::FunctionCall { + name, + namespace: Some(namespace), + call_id: function_call_id, + .. + } if function_call_id == call_id + && name == IMAGEGEN_TOOL_NAME + && namespace == IMAGE_GEN_NAMESPACE + ) + }) => + { + generated_images.extend(output.content_items().into_iter().flatten().filter_map( + |item| match item { + FunctionCallOutputContentItem::InputImage { image_url, .. } => { + Some(ImageUrl { + image_url: image_url.clone(), + }) + } + FunctionCallOutputContentItem::InputText { .. } + | FunctionCallOutputContentItem::EncryptedContent { .. } => None, + }, + )); + } + ResponseItem::Message { .. } + | ResponseItem::Reasoning { .. } + | ResponseItem::LocalShellCall { .. } + | ResponseItem::FunctionCall { .. } + | ResponseItem::ToolSearchCall { .. } + | ResponseItem::FunctionCallOutput { .. } + | ResponseItem::CustomToolCall { .. } + | ResponseItem::CustomToolCallOutput { .. } + | ResponseItem::ToolSearchOutput { .. } + | ResponseItem::WebSearchCall { .. } + | ResponseItem::ImageGenerationCall { .. } + | ResponseItem::Compaction { .. } + | ResponseItem::CompactionTrigger + | ResponseItem::ContextCompaction { .. } + | ResponseItem::Other => {} + } + } + truncate_images(user_images, generated_images) +} + +/// Truncates edit inputs while preserving the newest generated image when possible. +fn truncate_images( + mut user_images: Vec, + mut generated_images: Vec, +) -> Vec { + let mut excess = (user_images.len() + generated_images.len()).saturating_sub(MAX_EDIT_IMAGES); + let drop_generated = excess.min(generated_images.len().saturating_sub(1)); + generated_images.drain(..drop_generated); + excess -= drop_generated; + let drop_user = excess.min(user_images.len()); + user_images.drain(..drop_user); + excess -= drop_user; + generated_images.drain(..excess); + + user_images.extend(generated_images); + user_images +} + +/// Parses the strict model-facing arguments for an image-generation call. +fn parse_args(call: &ToolCall) -> Result { + serde_json::from_str(call.function_arguments()?) + .map_err(|err| FunctionCallError::RespondToModel(err.to_string())) +} + +/// Builds the namespace function schema exposed to the model. +fn imagegen_tool_spec() -> ToolSpec { + let mut schema_value = serde_json::to_value( + SchemaSettings::draft2019_09() + .with(|settings| settings.inline_subschemas = true) + .into_generator() + .into_root_schema_for::(), + ) + .unwrap_or_else(|err| panic!("imagegen schema should serialize: {err}")); + let Value::Object(ref mut schema) = schema_value else { + unreachable!("imagegen root schema must be an object"); + }; + let mut input_schema = Map::new(); + for key in ["properties", "required", "type", "additionalProperties"] { + if let Some(value) = schema.remove(key) { + input_schema.insert(key.to_string(), value); + } + } + ToolSpec::Namespace(ResponsesApiNamespace { + name: IMAGE_GEN_NAMESPACE.to_string(), + description: default_namespace_description(IMAGE_GEN_NAMESPACE), + tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool { + name: IMAGEGEN_TOOL_NAME.to_string(), + description: IMAGEGEN_DESCRIPTION.to_string(), + strict: false, + parameters: parse_tool_input_schema(&Value::Object(input_schema)) + .unwrap_or_else(|err| panic!("imagegen input schema should parse: {err}")), + output_schema: None, + defer_loading: None, + })], + }) +} + +struct GeneratedImageOutput { + result: String, + output_hint: Option, +} + +impl ToolOutput for GeneratedImageOutput { + /// Avoids copying image bytes into tool-call telemetry. + fn log_preview(&self) -> String { + "[generated image]".to_string() + } + + /// Reports a completed images request as successful tool execution. + fn success_for_logging(&self) -> bool { + true + } + + /// Returns generated bytes and persisted-artifact context for model follow-up. + fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem { + let mut content = vec![FunctionCallOutputContentItem::InputImage { + image_url: format!("data:image/png;base64,{}", self.result), + detail: Some(DEFAULT_IMAGE_DETAIL), + }]; + if let Some(output_hint) = &self.output_hint { + content.push(FunctionCallOutputContentItem::InputText { + text: output_hint.clone(), + }); + } + ResponseInputItem::FunctionCallOutput { + call_id: call_id.to_string(), + output: FunctionCallOutputPayload { + body: FunctionCallOutputBody::ContentItems(content), + success: Some(true), + }, + } + } +} + +#[cfg(test)] +#[path = "tests.rs"] +mod tests; diff --git a/codex-rs/ext/memories/src/lib.rs b/codex-rs/ext/memories/src/lib.rs index d17c4c4956..25120c7a3a 100644 --- a/codex-rs/ext/memories/src/lib.rs +++ b/codex-rs/ext/memories/src/lib.rs @@ -15,7 +15,7 @@ pub(crate) const MAX_SEARCH_RESULTS: usize = 200; pub(crate) const DEFAULT_READ_MAX_TOKENS: usize = 20_000; pub(crate) const MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT: usize = 2_500; -pub(crate) const MEMORY_TOOLS_NAMESPACE: &str = "memories/"; +pub(crate) const MEMORY_TOOLS_NAMESPACE: &str = "memories"; pub(crate) const ADD_AD_HOC_NOTE_TOOL_NAME: &str = "add_ad_hoc_note"; pub(crate) const LIST_TOOL_NAME: &str = "list"; pub(crate) const READ_TOOL_NAME: &str = "read"; diff --git a/codex-rs/ext/memories/src/metrics.rs b/codex-rs/ext/memories/src/metrics.rs index 610a3cb9ed..443156b724 100644 --- a/codex-rs/ext/memories/src/metrics.rs +++ b/codex-rs/ext/memories/src/metrics.rs @@ -15,7 +15,7 @@ pub(crate) fn record_tool_call( return; }; - let tool = format!("{MEMORY_TOOLS_NAMESPACE}{operation}"); + let tool = format!("{MEMORY_TOOLS_NAMESPACE}/{operation}"); let _ = metrics_client.counter( MEMORIES_TOOL_CALL_METRIC, /*inc*/ 1, diff --git a/codex-rs/ext/memories/src/tests.rs b/codex-rs/ext/memories/src/tests.rs index fbb23bd7ac..f2d79c850c 100644 --- a/codex-rs/ext/memories/src/tests.rs +++ b/codex-rs/ext/memories/src/tests.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use codex_extension_api::ContextContributor; use codex_extension_api::ExtensionData; use codex_extension_api::ExtensionRegistryBuilder; +use codex_extension_api::NoopTurnItemEmitter; use codex_extension_api::PromptSlot; use codex_extension_api::ToolCall; use codex_extension_api::ToolContributor; @@ -22,6 +23,16 @@ use crate::extension::MemoriesExtension; use crate::extension::MemoriesExtensionConfig; use crate::local::LocalMemoriesBackend; +#[test] +fn memory_tool_namespace_matches_responses_api_identifier() { + assert!(!crate::MEMORY_TOOLS_NAMESPACE.is_empty()); + assert!( + crate::MEMORY_TOOLS_NAMESPACE + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + ); +} + #[test] fn tools_are_not_contributed_without_thread_config() { let extension = MemoriesExtension::default(); @@ -202,6 +213,7 @@ async fn add_ad_hoc_note_tool_creates_note_file() { tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload: payload.clone(), }) .await @@ -243,6 +255,7 @@ async fn add_ad_hoc_note_tool_rejects_paths_as_filenames() { tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload, }) .await; @@ -285,6 +298,7 @@ async fn read_tool_reads_memory_file() { tool_name: memory_tool_name(crate::READ_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload: payload.clone(), }) .await @@ -330,6 +344,7 @@ async fn search_tool_accepts_multiple_queries() { tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload: payload.clone(), }) .await @@ -401,6 +416,7 @@ async fn search_tool_accepts_windowed_all_match_mode() { tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload: payload.clone(), }) .await @@ -452,6 +468,7 @@ async fn search_tool_rejects_legacy_single_query() { tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME), truncation_policy: TruncationPolicy::Bytes(1024), conversation_history: codex_extension_api::ConversationHistory::default(), + turn_item_emitter: Arc::new(NoopTurnItemEmitter), payload, }) .await; diff --git a/codex-rs/ext/web-search/Cargo.toml b/codex-rs/ext/web-search/Cargo.toml index 978aa4c45d..0faabf21a8 100644 --- a/codex-rs/ext/web-search/Cargo.toml +++ b/codex-rs/ext/web-search/Cargo.toml @@ -26,6 +26,7 @@ codex-tools = { workspace = true } http = { workspace = true } schemars = { workspace = true } serde_json = { workspace = true } +url = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } diff --git a/codex-rs/ext/web-search/src/extension.rs b/codex-rs/ext/web-search/src/extension.rs index b7b6c83951..2a7f3b882f 100644 --- a/codex-rs/ext/web-search/src/extension.rs +++ b/codex-rs/ext/web-search/src/extension.rs @@ -146,6 +146,8 @@ mod tests { use super::Config; use super::WebSearchExtensionConfig; use super::install; + use crate::tool::RUN_TOOL_NAME; + use crate::tool::WEB_NAMESPACE; #[test] fn installed_extension_contributes_web_run_when_enabled() { @@ -170,6 +172,9 @@ mod tests { .map(|tool| tool.tool_name()) .collect::>(); - assert_eq!(tool_names, vec![ToolName::namespaced("web", "run")]); + assert_eq!( + tool_names, + vec![ToolName::namespaced(WEB_NAMESPACE, RUN_TOOL_NAME)] + ); } } diff --git a/codex-rs/ext/web-search/src/tool.rs b/codex-rs/ext/web-search/src/tool.rs index 875476db9a..2cf25b007c 100644 --- a/codex-rs/ext/web-search/src/tool.rs +++ b/codex-rs/ext/web-search/src/tool.rs @@ -1,8 +1,11 @@ use codex_api::ReqwestTransport; use codex_api::SearchClient; use codex_api::SearchCommands; +use codex_api::SearchQuery; use codex_api::SearchRequest; use codex_api::SearchSettings; +use codex_core::web_search_action_detail; +use codex_extension_api::ExtensionTurnItem; use codex_extension_api::FunctionCallError; use codex_extension_api::ResponsesApiTool; use codex_extension_api::ToolCall; @@ -13,18 +16,21 @@ use codex_extension_api::ToolSpec; use codex_extension_api::parse_tool_input_schema_without_compaction; use codex_login::default_client::build_reqwest_client; use codex_model_provider::SharedModelProvider; +use codex_protocol::items::WebSearchItem; +use codex_protocol::models::WebSearchAction; use codex_tools::ResponsesApiNamespace; use codex_tools::ResponsesApiNamespaceTool; use codex_tools::ToolExposure; use codex_tools::default_namespace_description; use http::HeaderMap; +use url::Url; use crate::history::recent_input; use crate::output::EncryptedSearchOutput; use crate::schema::commands_schema; -const WEB_NAMESPACE: &str = "web"; -const RUN_TOOL_NAME: &str = "run"; +pub(crate) const WEB_NAMESPACE: &str = "web"; +pub(crate) const RUN_TOOL_NAME: &str = "run"; const WEB_RUN_DESCRIPTION: &str = include_str!("../web_run_description.md"); pub(crate) struct WebSearchTool { @@ -66,6 +72,7 @@ impl ToolExecutor for WebSearchTool { async fn handle(&self, call: ToolCall) -> Result, FunctionCallError> { let commands = parse_commands(&call)?; + let command_action = command_action(&commands); let provider = self .provider .api_provider() @@ -92,10 +99,16 @@ impl ToolExecutor for WebSearchTool { u64::try_from(call.truncation_policy.token_budget()).unwrap_or(u64::MAX), ), }; + call.turn_item_emitter + .emit_started(web_search_item(&call.call_id, WebSearchAction::Other)) + .await; let response = client .search(&request, HeaderMap::new()) .await .map_err(|err| FunctionCallError::Fatal(err.to_string()))?; + call.turn_item_emitter + .emit_completed(web_search_item(&call.call_id, command_action)) + .await; Ok(Box::new(EncryptedSearchOutput::new( response.encrypted_output, @@ -112,3 +125,110 @@ fn parse_commands(call: &ToolCall) -> Result serde_json::from_str(arguments) .map_err(|err| FunctionCallError::RespondToModel(err.to_string())) } + +fn command_action(commands: &SearchCommands) -> WebSearchAction { + commands + .search_query + .as_deref() + .and_then(query_action) + .or_else(|| commands.image_query.as_deref().and_then(query_action)) + .or_else(|| { + commands + .open + .as_deref() + .and_then(|operations| operations.first()) + .and_then(|operation| { + literal_url(&operation.ref_id) + .map(|url| WebSearchAction::OpenPage { url: Some(url) }) + }) + }) + .or_else(|| { + commands + .find + .as_deref() + .and_then(|operations| operations.first()) + .map(|operation| WebSearchAction::FindInPage { + url: literal_url(&operation.ref_id), + pattern: Some(operation.pattern.clone()), + }) + }) + .unwrap_or(WebSearchAction::Other) +} + +fn query_action(queries: &[SearchQuery]) -> Option { + match queries { + [] => None, + [query] => Some(WebSearchAction::Search { + query: Some(query.q.clone()), + queries: None, + }), + queries => Some(WebSearchAction::Search { + query: None, + queries: Some(queries.iter().map(|query| query.q.clone()).collect()), + }), + } +} + +fn literal_url(ref_id: &str) -> Option { + Url::parse(ref_id).is_ok().then(|| ref_id.to_string()) +} + +fn web_search_item(call_id: &str, action: WebSearchAction) -> ExtensionTurnItem { + ExtensionTurnItem::WebSearch(WebSearchItem { + id: call_id.to_string(), + query: web_search_action_detail(&action), + action, + }) +} + +#[cfg(test)] +mod tests { + use codex_api::SearchCommands; + use codex_protocol::models::WebSearchAction; + use pretty_assertions::assert_eq; + + use super::command_action; + + #[test] + fn command_action_reports_queries_and_navigation_detail() { + let cases = [ + ( + r#"{"image_query":[{"q":"waterfalls"},{"q":"mountains"}]}"#, + WebSearchAction::Search { + query: None, + queries: Some(vec!["waterfalls".to_string(), "mountains".to_string()]), + }, + ), + ( + r#"{"open":[{"ref_id":"https://example.com/docs"}]}"#, + WebSearchAction::OpenPage { + url: Some("https://example.com/docs".to_string()), + }, + ), + ( + r#"{"find":[{"ref_id":"https://example.com/docs","pattern":"install"}]}"#, + WebSearchAction::FindInPage { + url: Some("https://example.com/docs".to_string()), + pattern: Some("install".to_string()), + }, + ), + ( + r#"{"find":[{"ref_id":"turn0search0","pattern":"install"}]}"#, + WebSearchAction::FindInPage { + url: None, + pattern: Some("install".to_string()), + }, + ), + ( + r#"{"open":[{"ref_id":"turn0search0"}]}"#, + WebSearchAction::Other, + ), + ]; + + for (arguments, expected) in cases { + let commands: SearchCommands = + serde_json::from_str(arguments).expect("valid search command arguments"); + assert_eq!(command_action(&commands), expected); + } + } +} diff --git a/codex-rs/external-agent-sessions/src/export.rs b/codex-rs/external-agent-sessions/src/export.rs index 01220c07c1..e09805d4d2 100644 --- a/codex-rs/external-agent-sessions/src/export.rs +++ b/codex-rs/external-agent-sessions/src/export.rs @@ -78,6 +78,7 @@ fn rollout_items_from_messages(messages: &[ConversationMessage]) -> Vec, +} + +impl DebouncedWatchReceiver { + /// Creates a debouncing wrapper around a raw watcher [`Receiver`]. + pub fn new(rx: Receiver, interval: Duration) -> Self { + Self { + rx, + interval, + changed_paths: BTreeSet::new(), + } + } + + /// Receives the next debounced event batch. + pub async fn recv(&mut self) -> Option { + while self.changed_paths.is_empty() { + self.changed_paths.extend(self.rx.recv().await?.paths); + } + let deadline = Instant::now() + self.interval; + + loop { + tokio::select! { + event = self.rx.recv() => match event { + Some(event) => self.changed_paths.extend(event.paths), + None => break, + }, + _ = sleep_until(deadline) => break, + } + } + + Some(FileWatcherEvent { + paths: std::mem::take(&mut self.changed_paths) + .into_iter() + .collect(), + }) + } +} + /// Handle used to register watched paths for one logical consumer. pub struct FileWatcherSubscriber { id: SubscriberId, diff --git a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json index 7d63b56c96..347820f7ed 100644 --- a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json @@ -2,21 +2,6 @@ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "definitions": { - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, "PermissionRequestBehaviorWire": { "enum": [ "allow", @@ -65,7 +50,8 @@ "default": null }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "PermissionRequest", + "type": "string" } }, "required": [ diff --git a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json index 964c3ba624..011f887265 100644 --- a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json @@ -8,21 +8,6 @@ ], "type": "string" }, - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, "PostToolUseHookSpecificOutputWire": { "additionalProperties": false, "properties": { @@ -31,7 +16,8 @@ "type": "string" }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "PostToolUse", + "type": "string" }, "updatedMCPToolOutput": { "default": null diff --git a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json index a74abd14e8..6730b27fd4 100644 --- a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json @@ -2,21 +2,6 @@ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "definitions": { - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, "PreToolUseDecisionWire": { "enum": [ "approve", @@ -32,7 +17,8 @@ "type": "string" }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "PreToolUse", + "type": "string" }, "permissionDecision": { "allOf": [ diff --git a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json index e1abb88a52..1dd51e0010 100644 --- a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json @@ -2,21 +2,6 @@ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "definitions": { - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, "SessionStartHookSpecificOutputWire": { "additionalProperties": false, "properties": { @@ -25,7 +10,8 @@ "type": "string" }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "SessionStart", + "type": "string" } }, "required": [ diff --git a/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json b/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json index 4e645bb918..02493da98b 100644 --- a/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json @@ -2,22 +2,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "definitions": { - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, - "SessionStartHookSpecificOutputWire": { + "SubagentStartHookSpecificOutputWire": { "additionalProperties": false, "properties": { "additionalContext": { @@ -25,7 +10,8 @@ "type": "string" }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "SubagentStart", + "type": "string" } }, "required": [ @@ -42,7 +28,7 @@ "hookSpecificOutput": { "allOf": [ { - "$ref": "#/definitions/SessionStartHookSpecificOutputWire" + "$ref": "#/definitions/SubagentStartHookSpecificOutputWire" } ], "default": null diff --git a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json index 61c530ce04..97875c108b 100644 --- a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json @@ -8,21 +8,6 @@ ], "type": "string" }, - "HookEventNameWire": { - "enum": [ - "PreToolUse", - "PermissionRequest", - "PostToolUse", - "PreCompact", - "PostCompact", - "SessionStart", - "UserPromptSubmit", - "SubagentStart", - "SubagentStop", - "Stop" - ], - "type": "string" - }, "UserPromptSubmitHookSpecificOutputWire": { "additionalProperties": false, "properties": { @@ -31,7 +16,8 @@ "type": "string" }, "hookEventName": { - "$ref": "#/definitions/HookEventNameWire" + "const": "UserPromptSubmit", + "type": "string" } }, "required": [ diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index 11b44395c8..b4f214146a 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -94,7 +94,8 @@ pub(crate) fn parse_session_start(stdout: &str) -> Option { let wire: SessionStartCommandOutputWire = parse_json(stdout)?; Some(session_start_output( wire.universal, - wire.hook_specific_output, + wire.hook_specific_output + .and_then(|output| output.additional_context), )) } @@ -102,15 +103,15 @@ pub(crate) fn parse_subagent_start(stdout: &str) -> Option { let wire: SubagentStartCommandOutputWire = parse_json(stdout)?; Some(session_start_output( wire.universal, - wire.hook_specific_output, + wire.hook_specific_output + .and_then(|output| output.additional_context), )) } fn session_start_output( universal: HookUniversalOutputWire, - hook_specific_output: Option, + additional_context: Option, ) -> SessionStartOutput { - let additional_context = hook_specific_output.and_then(|output| output.additional_context); SessionStartOutput { universal: UniversalOutput::from(universal), additional_context, diff --git a/codex-rs/hooks/src/schema.rs b/codex-rs/hooks/src/schema.rs index bd2ac16dfb..d90d8a3e52 100644 --- a/codex-rs/hooks/src/schema.rs +++ b/codex-rs/hooks/src/schema.rs @@ -182,6 +182,7 @@ pub(crate) struct PostCompactCommandOutputWire { #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct PermissionRequestHookSpecificOutputWire { + #[schemars(schema_with = "permission_request_hook_event_name_schema")] pub hook_event_name: HookEventNameWire, #[serde(default)] pub decision: Option, @@ -223,6 +224,7 @@ pub(crate) enum PermissionRequestBehaviorWire { #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct PostToolUseHookSpecificOutputWire { + #[schemars(schema_with = "post_tool_use_hook_event_name_schema")] pub hook_event_name: HookEventNameWire, #[serde(default)] pub additional_context: Option, @@ -235,6 +237,7 @@ pub(crate) struct PostToolUseHookSpecificOutputWire { #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct PreToolUseHookSpecificOutputWire { + #[schemars(schema_with = "pre_tool_use_hook_event_name_schema")] pub hook_event_name: HookEventNameWire, #[serde(default)] pub permission_decision: Option, @@ -388,6 +391,7 @@ pub(crate) struct SessionStartCommandOutputWire { #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct SessionStartHookSpecificOutputWire { + #[schemars(schema_with = "session_start_hook_event_name_schema")] pub hook_event_name: HookEventNameWire, #[serde(default)] pub additional_context: Option, @@ -401,7 +405,17 @@ pub(crate) struct SubagentStartCommandOutputWire { #[serde(flatten)] pub universal: HookUniversalOutputWire, #[serde(default)] - pub hook_specific_output: Option, + pub hook_specific_output: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +pub(crate) struct SubagentStartHookSpecificOutputWire { + #[schemars(schema_with = "subagent_start_hook_event_name_schema")] + pub hook_event_name: HookEventNameWire, + #[serde(default)] + pub additional_context: Option, } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] @@ -423,6 +437,7 @@ pub(crate) struct UserPromptSubmitCommandOutputWire { #[serde(rename_all = "camelCase")] #[serde(deny_unknown_fields)] pub(crate) struct UserPromptSubmitHookSpecificOutputWire { + #[schemars(schema_with = "user_prompt_submit_hook_event_name_schema")] pub hook_event_name: HookEventNameWire, #[serde(default)] pub additional_context: Option, @@ -817,10 +832,13 @@ mod tests { use super::PRE_TOOL_USE_INPUT_FIXTURE; use super::PRE_TOOL_USE_OUTPUT_FIXTURE; use super::PermissionRequestCommandInput; + use super::PermissionRequestCommandOutputWire; use super::PostCompactCommandInput; use super::PostToolUseCommandInput; + use super::PostToolUseCommandOutputWire; use super::PreCompactCommandInput; use super::PreToolUseCommandInput; + use super::PreToolUseCommandOutputWire; use super::SESSION_START_INPUT_FIXTURE; use super::SESSION_START_OUTPUT_FIXTURE; use super::STOP_INPUT_FIXTURE; @@ -829,17 +847,21 @@ mod tests { use super::SUBAGENT_START_OUTPUT_FIXTURE; use super::SUBAGENT_STOP_INPUT_FIXTURE; use super::SUBAGENT_STOP_OUTPUT_FIXTURE; + use super::SessionStartCommandOutputWire; use super::StopCommandInput; use super::SubagentCommandInputFields; use super::SubagentStartCommandInput; + use super::SubagentStartCommandOutputWire; use super::SubagentStopCommandInput; use super::USER_PROMPT_SUBMIT_INPUT_FIXTURE; use super::USER_PROMPT_SUBMIT_OUTPUT_FIXTURE; use super::UserPromptSubmitCommandInput; + use super::UserPromptSubmitCommandOutputWire; use super::schema_json; use super::write_schema_fixtures; use crate::events::common::SubagentHookContext; use pretty_assertions::assert_eq; + use schemars::JsonSchema; use serde_json::Value; use serde_json::json; use tempfile::TempDir; @@ -914,6 +936,20 @@ mod tests { value.replace("\r\n", "\n") } + fn assert_output_hook_event_name_const(definition: &str, expected: &str) { + let schema: Value = + serde_json::from_slice(&schema_json::().expect("serialize hook output schema")) + .expect("parse hook output schema"); + + assert_eq!( + schema["definitions"][definition]["properties"]["hookEventName"], + json!({ + "const": expected, + "type": "string", + }) + ); + } + #[test] fn generated_hook_schemas_match_fixtures() { let temp_dir = TempDir::new().expect("create temp dir"); @@ -950,6 +986,34 @@ mod tests { } } + #[test] + fn hook_specific_output_event_names_are_event_specific_in_output_schemas() { + assert_output_hook_event_name_const::( + "PermissionRequestHookSpecificOutputWire", + "PermissionRequest", + ); + assert_output_hook_event_name_const::( + "PostToolUseHookSpecificOutputWire", + "PostToolUse", + ); + assert_output_hook_event_name_const::( + "PreToolUseHookSpecificOutputWire", + "PreToolUse", + ); + assert_output_hook_event_name_const::( + "SessionStartHookSpecificOutputWire", + "SessionStart", + ); + assert_output_hook_event_name_const::( + "SubagentStartHookSpecificOutputWire", + "SubagentStart", + ); + assert_output_hook_event_name_const::( + "UserPromptSubmitHookSpecificOutputWire", + "UserPromptSubmit", + ); + } + #[test] fn turn_scoped_hook_inputs_include_codex_turn_id_extension() { // Codex intentionally diverges from Claude's public hook docs here so diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index e18f2a17b4..729a3bee07 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -190,6 +190,7 @@ async fn run_cmd_result_with_permission_profile_for_cwd( params, &permission_profile, &sandbox_cwd, + std::slice::from_ref(&sandbox_cwd), &codex_linux_sandbox_exe, use_legacy_landlock, /*stdout_stream*/ None, @@ -448,6 +449,7 @@ async fn assert_network_blocked(cmd: &[&str]) { params, &permission_profile, &sandbox_cwd, + std::slice::from_ref(&sandbox_cwd), &codex_linux_sandbox_exe, /*use_legacy_landlock*/ false, /*stdout_stream*/ None, diff --git a/codex-rs/login/src/auth/manager.rs b/codex-rs/login/src/auth/manager.rs index d94c48165d..22e2c9f3b9 100644 --- a/codex-rs/login/src/auth/manager.rs +++ b/codex-rs/login/src/auth/manager.rs @@ -84,6 +84,7 @@ struct ChatgptAuthState { } const TOKEN_REFRESH_INTERVAL: i64 = 8; +const CHATGPT_ACCESS_TOKEN_REFRESH_WINDOW_MINUTES: i64 = 5; const REFRESH_TOKEN_EXPIRED_MESSAGE: &str = "Your access token could not be refreshed because your refresh token has expired. Please log out and sign in again."; const REFRESH_TOKEN_REUSED_MESSAGE: &str = "Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again."; @@ -844,8 +845,8 @@ async fn request_chatgpt_token_refresh( } else { let body = response.text().await.unwrap_or_default(); tracing::error!("Failed to refresh token: {status}: {body}"); - if status == StatusCode::UNAUTHORIZED { - let failed = classify_refresh_token_failure(&body); + let failed = classify_refresh_token_failure(&body); + if status == StatusCode::UNAUTHORIZED || failed.reason != RefreshTokenFailedReason::Other { Err(RefreshTokenError::Permanent(failed)) } else { let message = try_parse_error_message(&body); @@ -871,7 +872,7 @@ fn classify_refresh_token_failure(body: &str) -> RefreshTokenFailedError { tracing::warn!( backend_code = normalized_code.as_deref(), backend_body = body, - "Encountered unknown 401 response while refreshing token" + "Encountered unknown response while refreshing token" ); } @@ -1421,15 +1422,15 @@ impl AuthManager { } /// Current cached auth (clone). May be `None` if not logged in or load failed. - /// For stale managed ChatGPT auth, first performs a guarded reload and then - /// refreshes only if the on-disk auth is unchanged. + /// For managed ChatGPT auth that needs a proactive refresh, first performs + /// a guarded reload and then refreshes only if the on-disk auth is unchanged. pub async fn auth(&self) -> Option { if let Some(auth) = self.resolve_external_api_key_auth().await { return Some(auth); } let auth = self.auth_cached()?; - if Self::is_stale_for_proactive_refresh(&auth) + if Self::should_refresh_proactively(&auth) && let Err(err) = self.refresh_token().await { tracing::error!("Failed to refresh token: {}", err); @@ -1808,7 +1809,7 @@ impl AuthManager { ) } - fn is_stale_for_proactive_refresh(auth: &CodexAuth) -> bool { + fn should_refresh_proactively(auth: &CodexAuth) -> bool { let chatgpt_auth = match auth { CodexAuth::Chatgpt(chatgpt_auth) => chatgpt_auth, _ => return false, @@ -1821,7 +1822,9 @@ impl AuthManager { if let Some(tokens) = auth_dot_json.tokens.as_ref() && let Ok(Some(expires_at)) = parse_jwt_expiration(&tokens.access_token) { - return expires_at <= Utc::now(); + return expires_at + <= Utc::now() + + chrono::Duration::minutes(CHATGPT_ACCESS_TOKEN_REFRESH_WINDOW_MINUTES); } let last_refresh = match auth_dot_json.last_refresh { Some(last_refresh) => last_refresh, diff --git a/codex-rs/login/tests/suite/auth_refresh.rs b/codex-rs/login/tests/suite/auth_refresh.rs index afdf466d09..83897a0d38 100644 --- a/codex-rs/login/tests/suite/auth_refresh.rs +++ b/codex-rs/login/tests/suite/auth_refresh.rs @@ -158,6 +158,102 @@ async fn refresh_token_refreshes_when_auth_is_unchanged() -> Result<()> { Ok(()) } +#[serial_test::serial(auth_refresh)] +#[tokio::test] +async fn auth_refreshes_when_access_token_is_near_expiry() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oauth/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token": "new-access-token", + "refresh_token": "new-refresh-token" + }))) + .expect(1) + .mount(&server) + .await; + + let ctx = RefreshTokenTestContext::new(&server).await?; + let initial_last_refresh = Utc::now(); + let near_expiry_access_token = access_token_with_expiration(Utc::now() + Duration::minutes(4)); + let initial_tokens = build_tokens(&near_expiry_access_token, INITIAL_REFRESH_TOKEN); + let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::Chatgpt), + openai_api_key: None, + tokens: Some(initial_tokens.clone()), + last_refresh: Some(initial_last_refresh), + agent_identity: None, + }; + ctx.write_auth(&initial_auth).await?; + + let cached_auth = ctx + .auth_manager + .auth() + .await + .context("auth should be cached")?; + + let refreshed_tokens = TokenData { + access_token: "new-access-token".to_string(), + refresh_token: "new-refresh-token".to_string(), + ..initial_tokens.clone() + }; + let cached = cached_auth + .get_token_data() + .context("token data should refresh")?; + assert_eq!(cached, refreshed_tokens); + let stored = ctx.load_auth()?; + let tokens = stored.tokens.as_ref().context("tokens should exist")?; + assert_eq!(tokens, &refreshed_tokens); + let refreshed_at = stored + .last_refresh + .as_ref() + .context("last_refresh should be recorded")?; + assert!( + *refreshed_at >= initial_last_refresh, + "last_refresh should advance" + ); + + server.verify().await; + Ok(()) +} + +#[serial_test::serial(auth_refresh)] +#[tokio::test] +async fn auth_skips_access_token_outside_refresh_window() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + let ctx = RefreshTokenTestContext::new(&server).await?; + let initial_last_refresh = Utc::now(); + let fresh_access_token = access_token_with_expiration(Utc::now() + Duration::minutes(6)); + let initial_tokens = build_tokens(&fresh_access_token, INITIAL_REFRESH_TOKEN); + let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::Chatgpt), + openai_api_key: None, + tokens: Some(initial_tokens.clone()), + last_refresh: Some(initial_last_refresh), + agent_identity: None, + }; + ctx.write_auth(&initial_auth).await?; + + let cached_auth = ctx + .auth_manager + .auth() + .await + .context("auth should be cached")?; + + let cached = cached_auth + .get_token_data() + .context("token data should remain cached")?; + assert_eq!(cached, initial_tokens); + assert_eq!(ctx.load_auth()?, initial_auth); + let requests = server.received_requests().await.unwrap_or_default(); + assert!(requests.is_empty(), "expected no refresh token requests"); + + Ok(()) +} + #[serial_test::serial(auth_refresh)] #[tokio::test] async fn refresh_token_skips_refresh_when_auth_changed() -> Result<()> { @@ -625,6 +721,73 @@ async fn refresh_token_does_not_retry_after_permanent_failure() -> Result<()> { Ok(()) } +#[serial_test::serial(auth_refresh)] +#[tokio::test] +async fn refresh_token_does_not_retry_after_bad_request_reused_failure() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oauth/token")) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": { + "code": "refresh_token_reused" + } + }))) + .expect(1) + .mount(&server) + .await; + + let ctx = RefreshTokenTestContext::new(&server).await?; + let initial_last_refresh = Utc::now() - Duration::days(1); + let initial_tokens = build_tokens(INITIAL_ACCESS_TOKEN, INITIAL_REFRESH_TOKEN); + let initial_auth = AuthDotJson { + auth_mode: Some(AuthMode::Chatgpt), + openai_api_key: None, + tokens: Some(initial_tokens.clone()), + last_refresh: Some(initial_last_refresh), + agent_identity: None, + }; + ctx.write_auth(&initial_auth).await?; + + let first_err = ctx + .auth_manager + .refresh_token() + .await + .err() + .context("first refresh should fail")?; + assert_eq!( + first_err.failed_reason(), + Some(RefreshTokenFailedReason::Exhausted) + ); + + let second_err = ctx + .auth_manager + .refresh_token() + .await + .err() + .context("second refresh should fail without retrying")?; + assert_eq!( + second_err.failed_reason(), + Some(RefreshTokenFailedReason::Exhausted) + ); + + let stored = ctx.load_auth()?; + assert_eq!(stored, initial_auth); + let cached_auth = ctx + .auth_manager + .auth() + .await + .context("auth should remain cached")?; + let cached = cached_auth + .get_token_data() + .context("token data should remain cached")?; + assert_eq!(cached, initial_tokens); + + server.verify().await; + Ok(()) +} + #[serial_test::serial(auth_refresh)] #[tokio::test] async fn refresh_token_reloads_changed_auth_after_permanent_failure() -> Result<()> { diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 62615fd16c..05b995e721 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -114,6 +114,7 @@ pub async fn run_codex_tool_session( additional_context: Default::default(), thread_settings: Default::default(), }, + client_user_message_id: None, trace: None, }; diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index 3123bcf335..2f85b35143 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -539,6 +539,7 @@ impl MessageProcessor { .submit_with_id(Submission { id: request_id_string, op: codex_protocol::protocol::Op::Interrupt, + client_user_message_id: None, trace: None, }) .await diff --git a/codex-rs/memories/write/src/start.rs b/codex-rs/memories/write/src/start.rs index 007f5f8bbc..809bf775b1 100644 --- a/codex-rs/memories/write/src/start.rs +++ b/codex-rs/memories/write/src/start.rs @@ -50,6 +50,10 @@ pub fn start_memories_startup_task( tokio::spawn(async move { let root = memory_root(&config.codex_home); + if let Err(err) = tokio::fs::create_dir_all(&root).await { + warn!("failed creating memories root: {err}"); + return; + } if let Err(err) = seed_extension_instructions(&root).await { warn!("failed seeding memory extension instructions: {err}"); } diff --git a/codex-rs/memories/write/src/startup_tests.rs b/codex-rs/memories/write/src/startup_tests.rs index 1a735b3668..bd0a9904e6 100644 --- a/codex-rs/memories/write/src/startup_tests.rs +++ b/codex-rs/memories/write/src/startup_tests.rs @@ -26,6 +26,21 @@ use tempfile::TempDir; use tokio::time::Duration; use tokio::time::Instant; +#[tokio::test] +async fn memories_startup_creates_memory_root() -> anyhow::Result<()> { + let server = start_mock_server().await; + let home = Arc::new(TempDir::new()?); + let memory_root = home.path().join("memories"); + let test = build_test_codex(&server, home).await?; + + assert!(!memory_root.exists()); + trigger_memories_startup(&test).await; + wait_for_dir(&memory_root).await?; + + shutdown_test_codex(&test).await?; + Ok(()) +} + #[tokio::test] async fn memories_startup_phase2_tracks_workspace_diff_across_runs() -> anyhow::Result<()> { let server = start_mock_server().await; @@ -408,6 +423,21 @@ async fn wait_for_file_removed(path: &Path) -> anyhow::Result<()> { } } +async fn wait_for_dir(path: &Path) -> anyhow::Result<()> { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if tokio::fs::try_exists(path).await? && path.is_dir() { + return Ok(()); + } + assert!( + Instant::now() < deadline, + "timed out waiting for {} to be created", + path.display() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + async fn wait_for_request(mock: &ResponseMock, expected_count: usize) -> Vec { let deadline = Instant::now() + Duration::from_secs(10); loop { diff --git a/codex-rs/model-provider-info/src/lib.rs b/codex-rs/model-provider-info/src/lib.rs index 65f71851d6..c20a51a3aa 100644 --- a/codex-rs/model-provider-info/src/lib.rs +++ b/codex-rs/model-provider-info/src/lib.rs @@ -37,6 +37,7 @@ pub const OPENAI_PROVIDER_ID: &str = "openai"; pub const CHATGPT_CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex"; const AMAZON_BEDROCK_PROVIDER_NAME: &str = "Amazon Bedrock"; pub const AMAZON_BEDROCK_PROVIDER_ID: &str = "amazon-bedrock"; +pub const AMAZON_BEDROCK_GPT_5_5_MODEL_ID: &str = "openai.gpt-5.5"; pub const AMAZON_BEDROCK_GPT_5_4_MODEL_ID: &str = "openai.gpt-5.4"; pub const AMAZON_BEDROCK_DEFAULT_BASE_URL: &str = "https://bedrock-mantle.us-east-1.api.aws/openai/v1"; diff --git a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs index 8fec7f835e..97a817fd21 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs @@ -1,149 +1,46 @@ use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_4_MODEL_ID; -use codex_models_manager::model_info::BASE_INSTRUCTIONS; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::config_types::ServiceTier; -use codex_protocol::config_types::Verbosity; -use codex_protocol::openai_models::ApplyPatchToolType; -use codex_protocol::openai_models::ConfigShellToolType; -use codex_protocol::openai_models::InputModality; +use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_5_MODEL_ID; +use codex_models_manager::bundled_models_response; use codex_protocol::openai_models::ModelInfo; -use codex_protocol::openai_models::ModelServiceTier; -use codex_protocol::openai_models::ModelVisibility; use codex_protocol::openai_models::ModelsResponse; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::openai_models::ReasoningEffortPreset; -use codex_protocol::openai_models::SPEED_TIER_FAST; -use codex_protocol::openai_models::TruncationPolicyConfig; -use codex_protocol::openai_models::WebSearchToolType; -const GPT_OSS_CONTEXT_WINDOW: i64 = 128_000; -const GPT_5_4_CONTEXT_WINDOW: i64 = 272_000; -const GPT_5_4_MAX_CONTEXT_WINDOW: i64 = 1_000_000; +const GPT_5_BEDROCK_CONTEXT_WINDOW: i64 = 272_000; +const GPT_5_5_OPENAI_MODEL_ID: &str = "gpt-5.5"; +const GPT_5_4_OPENAI_MODEL_ID: &str = "gpt-5.4"; pub(crate) fn static_model_catalog() -> ModelsResponse { ModelsResponse { models: vec![ - gpt_5_4_cmb_bedrock_model(/*priority*/ 0), - bedrock_oss_model( - "openai.gpt-oss-120b", - "GPT OSS 120B on Bedrock", + gpt_5_bedrock_model( + GPT_5_5_OPENAI_MODEL_ID, + AMAZON_BEDROCK_GPT_5_5_MODEL_ID, + /*priority*/ 0, + ), + gpt_5_bedrock_model( + GPT_5_4_OPENAI_MODEL_ID, + AMAZON_BEDROCK_GPT_5_4_MODEL_ID, /*priority*/ 1, ), - bedrock_oss_model( - "openai.gpt-oss-20b", - "GPT OSS 20B on Bedrock", - /*priority*/ 2, - ), ], } } -fn gpt_5_4_cmb_bedrock_model(priority: i32) -> ModelInfo { - ModelInfo { - slug: AMAZON_BEDROCK_GPT_5_4_MODEL_ID.to_string(), - display_name: "gpt-5.4".to_string(), - description: Some("Strong model for everyday coding.".to_string()), - default_reasoning_level: Some(ReasoningEffort::Medium), - supported_reasoning_levels: gpt_5_4_cmb_reasoning_levels(), - shell_type: ConfigShellToolType::ShellCommand, - visibility: ModelVisibility::List, - supported_in_api: true, - priority, - additional_speed_tiers: Vec::new(), - service_tiers: vec![ModelServiceTier { - id: ServiceTier::Fast.request_value().to_string(), - name: SPEED_TIER_FAST.to_string(), - description: "Fastest inference with increased plan usage".to_string(), - }], - default_service_tier: None, - availability_nux: None, - upgrade: None, - base_instructions: BASE_INSTRUCTIONS.to_string(), - model_messages: None, - supports_reasoning_summaries: true, - default_reasoning_summary: ReasoningSummary::None, - support_verbosity: true, - default_verbosity: Some(Verbosity::Medium), - apply_patch_tool_type: Some(ApplyPatchToolType::Freeform), - web_search_tool_type: WebSearchToolType::TextAndImage, - truncation_policy: TruncationPolicyConfig::tokens(/*limit*/ 10_000), - supports_parallel_tool_calls: true, - supports_image_detail_original: true, - context_window: Some(GPT_5_4_CONTEXT_WINDOW), - max_context_window: Some(GPT_5_4_MAX_CONTEXT_WINDOW), - auto_compact_token_limit: None, - effective_context_window_percent: 95, - experimental_supported_tools: Vec::new(), - input_modalities: vec![InputModality::Text, InputModality::Image], - used_fallback_model_metadata: false, - supports_search_tool: true, - } +fn gpt_5_bedrock_model(openai_slug: &str, bedrock_slug: &str, priority: i32) -> ModelInfo { + let mut model = bundled_openai_model(openai_slug); + model.slug = bedrock_slug.to_string(); + model.priority = priority; + model.context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW); + model.max_context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW); + model } -fn bedrock_oss_model(slug: &str, display_name: &str, priority: i32) -> ModelInfo { - ModelInfo { - slug: slug.to_string(), - display_name: display_name.to_string(), - description: Some(display_name.to_string()), - default_reasoning_level: Some(ReasoningEffort::Medium), - supported_reasoning_levels: vec![ - reasoning_effort_preset(ReasoningEffort::Low), - reasoning_effort_preset(ReasoningEffort::Medium), - reasoning_effort_preset(ReasoningEffort::High), - ], - shell_type: ConfigShellToolType::ShellCommand, - visibility: ModelVisibility::List, - supported_in_api: true, - priority, - additional_speed_tiers: Vec::new(), - service_tiers: Vec::new(), - default_service_tier: None, - availability_nux: None, - upgrade: None, - base_instructions: BASE_INSTRUCTIONS.to_string(), - model_messages: None, - supports_reasoning_summaries: true, - default_reasoning_summary: ReasoningSummary::None, - support_verbosity: false, - default_verbosity: None, - apply_patch_tool_type: None, - web_search_tool_type: WebSearchToolType::Text, - truncation_policy: TruncationPolicyConfig::tokens(/*limit*/ 10_000), - supports_parallel_tool_calls: true, - supports_image_detail_original: false, - context_window: Some(GPT_OSS_CONTEXT_WINDOW), - max_context_window: Some(GPT_OSS_CONTEXT_WINDOW), - auto_compact_token_limit: None, - effective_context_window_percent: 95, - experimental_supported_tools: Vec::new(), - input_modalities: vec![InputModality::Text], - used_fallback_model_metadata: false, - supports_search_tool: false, - } -} - -fn gpt_5_4_cmb_reasoning_levels() -> Vec { - vec![ - reasoning_effort_preset(ReasoningEffort::Minimal), - reasoning_effort_preset(ReasoningEffort::Low), - reasoning_effort_preset(ReasoningEffort::Medium), - reasoning_effort_preset(ReasoningEffort::High), - ] -} - -fn reasoning_effort_preset(effort: ReasoningEffort) -> ReasoningEffortPreset { - ReasoningEffortPreset { - effort, - description: match effort { - ReasoningEffort::None => "No reasoning", - ReasoningEffort::Minimal => "Minimal reasoning", - ReasoningEffort::Low => "Fast responses with lighter reasoning", - ReasoningEffort::Medium => "Balances speed and reasoning depth for everyday tasks", - ReasoningEffort::High => "Greater reasoning depth for complex problems", - ReasoningEffort::XHigh => "Extra high reasoning depth for complex problems", - } - .to_string(), - } +fn bundled_openai_model(slug: &str) -> ModelInfo { + bundled_models_response() + .unwrap_or_else(|err| panic!("bundled models.json should parse: {err}")) + .models + .into_iter() + .find(|model| model.slug == slug) + .unwrap_or_else(|| panic!("bundled models.json should include {slug}")) } #[cfg(test)] @@ -156,24 +53,38 @@ mod tests { fn catalog_uses_mantle_model_ids_as_slugs() { let catalog = static_model_catalog(); - assert_eq!(catalog.models.len(), 3); - assert_eq!(catalog.models[0].slug, AMAZON_BEDROCK_GPT_5_4_MODEL_ID); - assert_eq!(catalog.models[1].slug, "openai.gpt-oss-120b"); - assert_eq!(catalog.models[2].slug, "openai.gpt-oss-20b"); + assert_eq!(catalog.models.len(), 2); + assert_eq!(catalog.models[0].slug, AMAZON_BEDROCK_GPT_5_5_MODEL_ID); + assert_eq!(catalog.models[1].slug, AMAZON_BEDROCK_GPT_5_4_MODEL_ID); } #[test] - fn gpt_5_4_cmb_advertises_only_bedrock_supported_reasoning_levels() { + fn gpt_5_bedrock_models_use_bedrock_context_window() { let catalog = static_model_catalog(); - let cmb_model = catalog + let gpt_5_5 = catalog + .models + .iter() + .find(|model| model.slug == AMAZON_BEDROCK_GPT_5_5_MODEL_ID) + .expect("Bedrock catalog should include GPT-5.5"); + let gpt_5_4 = catalog .models .iter() .find(|model| model.slug == AMAZON_BEDROCK_GPT_5_4_MODEL_ID) - .expect("Bedrock catalog should include GPT-5.4 CMB"); + .expect("Bedrock catalog should include GPT-5.4"); assert_eq!( - cmb_model.supported_reasoning_levels, - gpt_5_4_cmb_reasoning_levels() + (gpt_5_5.context_window, gpt_5_5.max_context_window), + ( + Some(GPT_5_BEDROCK_CONTEXT_WINDOW), + Some(GPT_5_BEDROCK_CONTEXT_WINDOW) + ) + ); + assert_eq!( + (gpt_5_4.context_window, gpt_5_4.max_context_window), + ( + Some(GPT_5_BEDROCK_CONTEXT_WINDOW), + Some(GPT_5_BEDROCK_CONTEXT_WINDOW) + ) ); } } diff --git a/codex-rs/model-provider/src/provider.rs b/codex-rs/model-provider/src/provider.rs index 1ef7c22962..f5e5ab2ff5 100644 --- a/codex-rs/model-provider/src/provider.rs +++ b/codex-rs/model-provider/src/provider.rs @@ -507,14 +507,7 @@ mod tests { .map(|model| model.slug.as_str()) .collect::>(); - assert_eq!( - model_ids, - vec![ - "openai.gpt-5.4", - "openai.gpt-oss-120b", - "openai.gpt-oss-20b" - ] - ); + assert_eq!(model_ids, vec!["openai.gpt-5.5", "openai.gpt-5.4"]); let default_model = manager .list_models(RefreshStrategy::Online) @@ -523,7 +516,7 @@ mod tests { .find(|preset| preset.is_default) .expect("Bedrock catalog should have a default model"); - assert_eq!(default_model.model, "openai.gpt-5.4"); + assert_eq!(default_model.model, "openai.gpt-5.5"); } #[tokio::test] diff --git a/codex-rs/models-manager/src/model_info.rs b/codex-rs/models-manager/src/model_info.rs index 17b843440a..e57b4e186e 100644 --- a/codex-rs/models-manager/src/model_info.rs +++ b/codex-rs/models-manager/src/model_info.rs @@ -99,6 +99,7 @@ pub fn model_info_from_slug(slug: &str) -> ModelInfo { input_modalities: default_input_modalities(), used_fallback_model_metadata: true, // this is the fallback model metadata supports_search_tool: false, + tool_mode: None, } } diff --git a/codex-rs/network-proxy/src/config.rs b/codex-rs/network-proxy/src/config.rs index 398ec321a3..0b0a8233f5 100644 --- a/codex-rs/network-proxy/src/config.rs +++ b/codex-rs/network-proxy/src/config.rs @@ -107,7 +107,7 @@ impl NetworkDomainPermissions { #[serde(rename_all = "lowercase")] pub enum NetworkUnixSocketPermission { Allow, - None, + Deny, } #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)] diff --git a/codex-rs/otel/src/metrics/names.rs b/codex-rs/otel/src/metrics/names.rs index 817545c87d..d2093ed3f7 100644 --- a/codex-rs/otel/src/metrics/names.rs +++ b/codex-rs/otel/src/metrics/names.rs @@ -28,6 +28,10 @@ pub const TURN_NETWORK_PROXY_METRIC: &str = "codex.turn.network_proxy"; pub const TURN_MEMORY_METRIC: &str = "codex.turn.memory"; pub const TURN_TOOL_CALL_METRIC: &str = "codex.turn.tool.call"; pub const TURN_TOKEN_USAGE_METRIC: &str = "codex.turn.token_usage"; +pub const GUARDIAN_REVIEW_COUNT_METRIC: &str = "codex.guardian.review"; +pub const GUARDIAN_REVIEW_DURATION_METRIC: &str = "codex.guardian.review.duration_ms"; +pub const GUARDIAN_REVIEW_TTFT_DURATION_METRIC: &str = "codex.guardian.review.ttft.duration_ms"; +pub const GUARDIAN_REVIEW_TOKEN_USAGE_METRIC: &str = "codex.guardian.review.token_usage"; pub const GOAL_CREATED_METRIC: &str = "codex.goal.created"; pub const GOAL_RESUMED_METRIC: &str = "codex.goal.resumed"; pub const GOAL_COMPLETED_METRIC: &str = "codex.goal.completed"; diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 7d12579564..ee61dc3949 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -56,6 +56,9 @@ pub enum TurnItem { #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] pub struct UserMessageItem { pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub client_id: Option, pub content: Vec, } @@ -237,6 +240,7 @@ impl UserMessageItem { pub fn new(content: &[UserInput]) -> Self { Self { id: uuid::Uuid::new_v4().to_string(), + client_id: None, content: content.to_vec(), } } @@ -245,6 +249,7 @@ impl UserMessageItem { // 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(), @@ -272,6 +277,7 @@ impl UserMessageItem { if let UserInput::Text { text, text_elements, + .. } = input { // Text element ranges are relative to each text chunk; offset them so they align diff --git a/codex-rs/protocol/src/mcp.rs b/codex-rs/protocol/src/mcp.rs index f6e69743b9..a1916d424c 100644 --- a/codex-rs/protocol/src/mcp.rs +++ b/codex-rs/protocol/src/mcp.rs @@ -26,6 +26,18 @@ impl std::fmt::Display for RequestId { } } +/// Presentation metadata advertised by an initialized MCP server. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct McpServerInfo { + pub name: String, + pub title: Option, + pub version: String, + pub description: Option, + pub icons: Option>, + pub website_url: Option, +} + /// Definition for a tool the client can call. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)] #[serde(rename_all = "camelCase")] diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 86603db1ef..cbf8895ddb 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -1237,7 +1237,9 @@ impl From> for ResponseInputItem { .into_iter() .flat_map(|c| match c { UserInput::Text { text, .. } => vec![ContentItem::InputText { text }], - UserInput::Image { image_url, detail } => { + UserInput::Image { + image_url, detail, .. + } => { image_index += 1; let detail = detail.unwrap_or(DEFAULT_IMAGE_DETAIL); vec![ContentItem::InputImage { @@ -1245,7 +1247,7 @@ impl From> for ResponseInputItem { detail: Some(detail), }] } - UserInput::LocalImage { path, detail } => { + UserInput::LocalImage { path, detail, .. } => { image_index += 1; let detail = detail.unwrap_or(DEFAULT_IMAGE_DETAIL); match std::fs::read(&path) { diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index d0a58b5024..b9fa9c933d 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -8,7 +8,9 @@ use std::str::FromStr; use schemars::JsonSchema; use serde::Deserialize; +use serde::Deserializer; use serde::Serialize; +use serde::de::DeserializeOwned; use strum::IntoEnumIterator; use strum_macros::Display; use strum_macros::EnumIter; @@ -227,6 +229,25 @@ pub enum TruncationMode { Tokens, } +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ToolMode { + Direct, + CodeMode, + CodeModeOnly, +} + +fn deserialize_optional_model_selector<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, + T: DeserializeOwned, +{ + let Some(value) = Option::::deserialize(deserializer)? else { + return Ok(None); + }; + Ok(serde_json::from_value(serde_json::Value::String(value)).ok()) +} + #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)] pub struct TruncationPolicyConfig { pub mode: TruncationMode, @@ -318,6 +339,12 @@ pub struct ModelInfo { pub used_fallback_model_metadata: bool, #[serde(default)] pub supports_search_tool: bool, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_optional_model_selector" + )] + pub tool_mode: Option, } impl ModelInfo { @@ -612,6 +639,7 @@ mod tests { input_modalities: default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, } } @@ -829,6 +857,44 @@ mod tests { assert!(!model.supports_image_detail_original); assert_eq!(model.web_search_tool_type, WebSearchToolType::Text); assert!(!model.supports_search_tool); + assert_eq!(model.tool_mode, None); + } + + #[test] + fn model_info_deserializes_known_tool_mode() { + let mut value = + serde_json::to_value(test_model(/*spec*/ None)).expect("serialize test model"); + let object = value + .as_object_mut() + .expect("model info should be an object"); + object.insert( + "tool_mode".to_string(), + serde_json::Value::String("code_mode_only".to_string()), + ); + let model = serde_json::from_value::(value).expect("deserialize model info"); + + assert_eq!(model.tool_mode, Some(ToolMode::CodeModeOnly)); + } + + #[test] + fn model_info_treats_unknown_tool_mode_as_omitted() { + let mut value = + serde_json::to_value(test_model(/*spec*/ None)).expect("serialize test model"); + let object = value + .as_object_mut() + .expect("model info should be an object"); + object.insert( + "tool_mode".to_string(), + serde_json::Value::String("future_tool_mode".to_string()), + ); + let model = serde_json::from_value::(value).expect("deserialize model info"); + + assert_eq!(model.tool_mode, None); + let serialized = serde_json::to_value(model).expect("serialize model info"); + let object = serialized + .as_object() + .expect("model info should be an object"); + assert!(!object.contains_key("tool_mode")); } #[test] diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index a675362b62..3c0b5cb462 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -129,6 +129,9 @@ pub struct Submission { pub id: String, /// Payload pub op: Op, + /// Client-provided id for the user message represented by `Op::UserInput`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_user_message_id: Option, /// Optional W3C trace carrier propagated across async submission handoffs. #[serde(default, skip_serializing_if = "Option::is_none")] pub trace: Option, @@ -2164,6 +2167,8 @@ pub struct AgentMessageEvent { #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema, TS)] pub struct UserMessageEvent { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, pub message: String, /// Image URLs sourced from `UserInput::Image`. These are safe /// to replay in legacy UI history events and correspond to images sent to @@ -2767,6 +2772,10 @@ pub struct TurnContextItem { #[serde(default, skip_serializing_if = "Option::is_none")] pub turn_id: Option, pub cwd: PathBuf, + /// Effective workspace roots used to materialize symbolic + /// `:workspace_roots` filesystem permissions in `permission_profile`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workspace_roots: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub current_date: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5088,6 +5097,7 @@ mod tests { #[test] fn user_message_event_serializes_empty_metadata_vectors() -> Result<()> { let event = UserMessageEvent { + client_id: None, message: "hello".to_string(), images: None, local_images: Vec::new(), @@ -5133,7 +5143,7 @@ mod tests { #[test] fn user_message_item_legacy_event_preserves_image_details() { let local_path = PathBuf::from("/tmp/local.png"); - let item = UserMessageItem::new(&[ + let mut item = UserMessageItem::new(&[ crate::user_input::UserInput::Image { image_url: "https://example.com/first.png".to_string(), detail: Some(ImageDetail::Original), @@ -5147,6 +5157,7 @@ mod tests { detail: Some(ImageDetail::Original), }, ]); + item.client_id = Some("client-message-1".to_string()); let EventMsg::UserMessage(event) = item.as_legacy_event() else { panic!("expected user message event"); @@ -5159,6 +5170,7 @@ mod tests { "https://example.com/second.png".to_string(), ]) ); + assert_eq!(event.client_id, Some("client-message-1".to_string())); assert_eq!(event.image_details, vec![Some(ImageDetail::Original)]); assert_eq!(event.local_images, vec![local_path]); assert_eq!(event.local_image_details, vec![Some(ImageDetail::Original)]); @@ -5204,6 +5216,7 @@ mod tests { let item = TurnContextItem { turn_id: None, cwd: test_path_buf("/tmp"), + workspace_roots: None, current_date: None, timezone: None, approval_policy: AskForApproval::Never, diff --git a/codex-rs/rmcp-client/src/http_client_adapter.rs b/codex-rs/rmcp-client/src/http_client_adapter.rs index 0a5643aabf..6f98f78920 100644 --- a/codex-rs/rmcp-client/src/http_client_adapter.rs +++ b/codex-rs/rmcp-client/src/http_client_adapter.rs @@ -28,6 +28,7 @@ use reqwest::header::CONTENT_TYPE; use reqwest::header::HeaderMap; use reqwest::header::HeaderName; use rmcp::model::ClientJsonRpcMessage; +use rmcp::model::JsonRpcMessage; use rmcp::model::ServerJsonRpcMessage; use rmcp::transport::streamable_http_client::AuthRequiredError; use rmcp::transport::streamable_http_client::InsufficientScopeError; @@ -88,6 +89,8 @@ impl StreamableHttpClient for StreamableHttpClientAdapter { auth_token: Option, custom_headers: HashMap, ) -> std::result::Result> { + let (mcp_method, mcp_request_id) = client_jsonrpc_message_fields(&message); + let has_session_id = session_id.is_some(); let mut headers = self.default_headers.clone(); headers.extend(custom_headers); self.add_auth_headers(&mut headers); @@ -121,7 +124,8 @@ impl StreamableHttpClient for StreamableHttpClientAdapter { } let body = serde_json::to_vec(&message).map_err(StreamableHttpError::Deserialize)?; - let (response, mut body_stream) = self + let has_authorization_header = headers.contains_key(AUTHORIZATION); + let response = self .http_client .http_request_stream(HttpRequestParams { method: "POST".to_string(), @@ -132,9 +136,22 @@ impl StreamableHttpClient for StreamableHttpClientAdapter { request_id: "buffered-request".to_string(), stream_response: true, }) - .await - .map_err(StreamableHttpClientAdapterError::from) - .map_err(StreamableHttpError::Client)?; + .await; + let (response, mut body_stream) = match response { + Ok(response) => response, + Err(error) => { + log_post_message_http_error( + &uri, + mcp_method.as_deref(), + mcp_request_id.as_deref(), + has_session_id, + has_authorization_header, + ); + return Err(StreamableHttpError::Client( + StreamableHttpClientAdapterError::from(error), + )); + } + }; if response.status == StatusCode::NOT_FOUND.as_u16() && session_id.is_some() { return Err(StreamableHttpError::Client( @@ -354,6 +371,50 @@ fn body_preview(body: impl Into) -> String { body_preview } +fn client_jsonrpc_message_fields( + message: &ClientJsonRpcMessage, +) -> (Option, Option) { + match message { + JsonRpcMessage::Request(request) => ( + Some(request.request.method().to_string()), + Some(request.id.to_string()), + ), + JsonRpcMessage::Response(response) => (None, Some(response.id.to_string())), + JsonRpcMessage::Notification(_) => (None, None), + JsonRpcMessage::Error(error) => (None, error.id.as_ref().map(ToString::to_string)), + } +} + +fn log_post_message_http_error( + uri: &str, + mcp_method: Option<&str>, + mcp_request_id: Option<&str>, + has_session_id: bool, + has_authorization_header: bool, +) { + let parsed_url = reqwest::Url::parse(uri).ok(); + tracing::warn!( + endpoint_scheme = parsed_url + .as_ref() + .map(reqwest::Url::scheme) + .unwrap_or(""), + endpoint_host = parsed_url + .as_ref() + .and_then(reqwest::Url::host_str) + .unwrap_or(""), + endpoint_path = parsed_url + .as_ref() + .map(reqwest::Url::path) + .unwrap_or(""), + endpoint_has_query = parsed_url.as_ref().is_some_and(|url| url.query().is_some()), + mcp_method = mcp_method.unwrap_or(""), + mcp_request_id = mcp_request_id.unwrap_or(""), + has_session_id = has_session_id, + has_authorization_header = has_authorization_header, + "streamable HTTP post_message failed" + ); +} + fn insert_header( headers: &mut HeaderMap, name: HeaderName, diff --git a/codex-rs/rollout/src/metadata.rs b/codex-rs/rollout/src/metadata.rs index 2dd2df3a41..00c6e3e637 100644 --- a/codex-rs/rollout/src/metadata.rs +++ b/codex-rs/rollout/src/metadata.rs @@ -1,6 +1,5 @@ use crate::ARCHIVED_SESSIONS_SUBDIR; use crate::SESSIONS_SUBDIR; -use crate::list; use crate::list::parse_timestamp_uuid_from_filename; use crate::recorder::RolloutRecorder; use crate::state_db::normalize_cwd_for_state_db; @@ -286,25 +285,6 @@ pub(crate) async fn backfill_sessions_with_lease( continue; } stats.upserted = stats.upserted.saturating_add(1); - if let Ok(meta_line) = list::read_session_meta_line(&rollout.path).await { - if let Err(err) = runtime - .persist_dynamic_tools( - meta_line.meta.id, - meta_line.meta.dynamic_tools.as_deref(), - ) - .await - { - warn!( - "failed to backfill dynamic tools {}: {err}", - rollout.path.display() - ); - } - } else { - warn!( - "failed to read session meta for dynamic tools {}", - rollout.path.display() - ); - } } } Err(err) => { diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 90fe15c312..371155e041 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -109,6 +109,7 @@ async fn state_db_init_backfills_before_returning() -> anyhow::Result<()> { RolloutLine { timestamp: "2026-01-27T12:34:57Z".to_string(), item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello from startup backfill".to_string(), images: None, local_images: Vec::new(), @@ -400,6 +401,7 @@ async fn recorder_materializes_on_flush_with_pending_items() -> std::io::Result< recorder .record_canonical_items(&[RolloutItem::EventMsg(EventMsg::UserMessage( UserMessageEvent { + client_id: None, message: "first-user-message".to_string(), images: None, local_images: Vec::new(), @@ -1127,6 +1129,7 @@ async fn resume_candidate_matches_cwd_reads_latest_turn_context() -> std::io::Re item: RolloutItem::TurnContext(TurnContextItem { turn_id: Some("turn-1".to_string()), cwd: latest_cwd.clone(), + workspace_roots: None, current_date: None, timezone: None, approval_policy: AskForApproval::Never, diff --git a/codex-rs/rollout/src/state_db.rs b/codex-rs/rollout/src/state_db.rs index ea087e5c6d..2b6153484d 100644 --- a/codex-rs/rollout/src/state_db.rs +++ b/codex-rs/rollout/src/state_db.rs @@ -8,7 +8,6 @@ use crate::sqlite_metrics; use chrono::DateTime; use chrono::Utc; use codex_protocol::ThreadId; -use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::protocol::RolloutItem; use codex_protocol::protocol::SessionSource; pub use codex_state::LogEntry; @@ -454,37 +453,6 @@ pub async fn find_rollout_path_by_id( }) } -/// Get dynamic tools for a thread id using SQLite. -pub async fn get_dynamic_tools( - context: Option<&codex_state::StateRuntime>, - thread_id: ThreadId, - stage: &str, -) -> Option> { - let ctx = context?; - match ctx.get_dynamic_tools(thread_id).await { - Ok(tools) => tools, - Err(err) => { - warn!("state db get_dynamic_tools failed during {stage}: {err}"); - None - } - } -} - -/// Persist dynamic tools for a thread id using SQLite, if none exist yet. -pub async fn persist_dynamic_tools( - context: Option<&codex_state::StateRuntime>, - thread_id: ThreadId, - tools: Option<&[DynamicToolSpec]>, - stage: &str, -) { - let Some(ctx) = context else { - return; - }; - if let Err(err) = ctx.persist_dynamic_tools(thread_id, tools).await { - warn!("state db persist_dynamic_tools failed during {stage}: {err}"); - } -} - pub async fn mark_thread_memory_mode_polluted( context: Option<&codex_state::StateRuntime>, thread_id: ThreadId, @@ -570,21 +538,6 @@ pub async fn reconcile_rollout( "state db reconcile_rollout memory_mode update failed {}: {err}", rollout_path.display() ); - return; - } - if let Ok(meta_line) = crate::list::read_session_meta_line(rollout_path).await { - persist_dynamic_tools( - Some(ctx), - meta_line.meta.id, - meta_line.meta.dynamic_tools.as_deref(), - "reconcile_rollout", - ) - .await; - } else { - warn!( - "state db reconcile_rollout missing session meta {}", - rollout_path.display() - ); } } diff --git a/codex-rs/rollout/src/tests.rs b/codex-rs/rollout/src/tests.rs index bcd395d820..a8bfc0cd84 100644 --- a/codex-rs/rollout/src/tests.rs +++ b/codex-rs/rollout/src/tests.rs @@ -94,133 +94,6 @@ async fn insert_state_db_thread( runtime } -// TODO(jif) fix -// #[tokio::test] -// async fn list_threads_prefers_state_db_when_available() { -// let temp = TempDir::new().unwrap(); -// let home = temp.path(); -// let fs_uuid = Uuid::from_u128(101); -// write_session_file( -// home, -// "2025-01-03T13-00-00", -// fs_uuid, -// 1, -// Some(SessionSource::Cli), -// ) -// .unwrap(); -// -// let db_uuid = Uuid::from_u128(102); -// let db_thread_id = ThreadId::from_string(&db_uuid.to_string()).expect("valid thread id"); -// let db_rollout_path = home.join(format!( -// "sessions/2025/01/03/rollout-2025-01-03T12-00-00-{db_uuid}.jsonl" -// )); -// insert_state_db_thread(home, db_thread_id, db_rollout_path.as_path(), false).await; -// -// let page = RolloutRecorder::list_threads( -// home, -// 10, -// None, -// ThreadSortKey::CreatedAt, -// NO_SOURCE_FILTER, -// None, -// TEST_PROVIDER, -// ) -// .await -// .expect("thread listing should succeed"); -// -// assert_eq!(page.items.len(), 1); -// assert_eq!(page.items[0].path, db_rollout_path); -// assert_eq!(page.items[0].thread_id, Some(db_thread_id)); -// assert_eq!(page.items[0].cwd, Some(home.to_path_buf())); -// assert_eq!( -// page.items[0].first_user_message.as_deref(), -// Some("Hello from user") -// ); -// } - -// #[tokio::test] -// async fn list_threads_db_excludes_archived_entries() { -// let temp = TempDir::new().unwrap(); -// let home = temp.path(); -// let sessions_root = home.join("sessions/2025/01/03"); -// let archived_root = home.join("archived_sessions"); -// fs::create_dir_all(&sessions_root).unwrap(); -// fs::create_dir_all(&archived_root).unwrap(); -// -// let active_uuid = Uuid::from_u128(211); -// let active_thread_id = -// ThreadId::from_string(&active_uuid.to_string()).expect("valid active thread id"); -// let active_rollout_path = -// sessions_root.join(format!("rollout-2025-01-03T12-00-00-{active_uuid}.jsonl")); -// insert_state_db_thread(home, active_thread_id, active_rollout_path.as_path(), false).await; -// -// let archived_uuid = Uuid::from_u128(212); -// let archived_thread_id = -// ThreadId::from_string(&archived_uuid.to_string()).expect("valid archived thread id"); -// let archived_rollout_path = -// archived_root.join(format!("rollout-2025-01-03T11-00-00-{archived_uuid}.jsonl")); -// insert_state_db_thread( -// home, -// archived_thread_id, -// archived_rollout_path.as_path(), -// true, -// ) -// .await; -// -// let page = RolloutRecorder::list_threads( -// home, -// 10, -// None, -// ThreadSortKey::CreatedAt, -// NO_SOURCE_FILTER, -// None, -// TEST_PROVIDER, -// ) -// .await -// .expect("thread listing should succeed"); -// -// assert_eq!(page.items.len(), 1); -// assert_eq!(page.items[0].path, active_rollout_path); -// } - -// #[tokio::test] -// async fn list_threads_falls_back_to_files_when_state_db_is_unavailable() { -// let temp = TempDir::new().unwrap(); -// let home = temp.path(); -// let fs_uuid = Uuid::from_u128(301); -// write_session_file( -// home, -// "2025-01-03T13-00-00", -// fs_uuid, -// 1, -// Some(SessionSource::Cli), -// ) -// .unwrap(); -// -// let page = RolloutRecorder::list_threads( -// home, -// 10, -// None, -// ThreadSortKey::CreatedAt, -// NO_SOURCE_FILTER, -// None, -// TEST_PROVIDER, -// ) -// .await -// .expect("thread listing should succeed"); -// -// assert_eq!(page.items.len(), 1); -// let file_name = page.items[0] -// .path -// .file_name() -// .and_then(|value| value.to_str()) -// .expect("rollout file name should be utf8"); -// assert!( -// file_name.contains(&fs_uuid.to_string()), -// "expected file path from filesystem listing, got: {file_name}" -// ); -// } - #[tokio::test] async fn find_thread_path_falls_back_when_db_path_is_stale() { let temp = TempDir::new().unwrap(); @@ -1400,6 +1273,7 @@ async fn test_updated_at_uses_file_mtime() -> Result<()> { let user_event_line = RolloutLine { timestamp: ts.to_string(), item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: "hello".into(), images: None, text_elements: Vec::new(), diff --git a/codex-rs/shell-command/src/command_safety/is_safe_command.rs b/codex-rs/shell-command/src/command_safety/is_safe_command.rs index b35144a12b..bca44139cd 100644 --- a/codex-rs/shell-command/src/command_safety/is_safe_command.rs +++ b/codex-rs/shell-command/src/command_safety/is_safe_command.rs @@ -4,6 +4,7 @@ use crate::command_safety::is_dangerous_command::executable_name_lookup_key; // may appear before it (e.g., `-C`, `-c`, `--git-dir`). // Implemented in `is_dangerous_command` and shared here. use crate::command_safety::is_dangerous_command::find_git_subcommand; +#[cfg(windows)] use crate::command_safety::windows_safe_commands::is_safe_command_windows; #[cfg(windows)] use crate::command_safety::windows_safe_commands::is_safe_powershell_words as is_safe_powershell_words_windows; @@ -20,8 +21,11 @@ pub fn is_known_safe_command(command: &[String]) -> bool { }) .collect(); - if is_safe_command_windows(&command) { - return true; + #[cfg(windows)] + { + if is_safe_command_windows(&command) { + return true; + } } if is_safe_to_call_with_exec(&command) { @@ -748,4 +752,51 @@ mod tests { assert!(!is_safe_powershell_words(&command)); } } + + #[cfg(unix)] + #[test] + fn non_windows_safe_classification_does_not_spawn_repo_powershell_path() { + use std::fs; + use std::io::Write; + use std::os::unix::fs::PermissionsExt; + use std::time::SystemTime; + use std::time::UNIX_EPOCH; + + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock should be after unix epoch") + .as_nanos(); + let temp_dir = std::env::temp_dir().join(format!( + "codex-safe-command-pwsh-test-{}-{unique}", + std::process::id() + )); + fs::create_dir(&temp_dir).expect("create temp dir for fake pwsh"); + let fake_pwsh = temp_dir.join("pwsh"); + let marker = temp_dir.join("marker"); + let quoted_marker = marker.to_string_lossy().replace('\'', "'\\''"); + + let mut script = fs::File::create(&fake_pwsh).expect("create fake pwsh"); + writeln!( + script, + "#!/bin/sh\nprintf spawned > '{quoted_marker}'\nexit 0" + ) + .expect("write fake pwsh"); + let mut permissions = fs::metadata(&fake_pwsh) + .expect("stat fake pwsh") + .permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&fake_pwsh, permissions).expect("make fake pwsh executable"); + + assert!(!is_known_safe_command(&[ + fake_pwsh.to_string_lossy().into_owned(), + "-Command".to_string(), + "Get-ChildItem".to_string(), + ])); + assert!( + !marker.exists(), + "non-Windows safety classification must not spawn a PowerShell-looking path" + ); + + fs::remove_dir_all(temp_dir).expect("remove temp dir"); + } } diff --git a/codex-rs/shell-command/src/command_safety/mod.rs b/codex-rs/shell-command/src/command_safety/mod.rs index 2040364e5b..60bed2effc 100644 --- a/codex-rs/shell-command/src/command_safety/mod.rs +++ b/codex-rs/shell-command/src/command_safety/mod.rs @@ -2,5 +2,6 @@ mod powershell_parser; pub mod is_dangerous_command; pub mod is_safe_command; +#[cfg(windows)] pub(crate) mod windows_safe_commands; pub(crate) use powershell_parser::try_parse_powershell_ast_commands; diff --git a/codex-rs/shell-command/src/powershell.rs b/codex-rs/shell-command/src/powershell.rs index f7b294c0f8..e8c9a500c4 100644 --- a/codex-rs/shell-command/src/powershell.rs +++ b/codex-rs/shell-command/src/powershell.rs @@ -8,8 +8,9 @@ use crate::shell_detect::detect_shell_type; const POWERSHELL_FLAGS: &[&str] = &["-nologo", "-noprofile", "-command", "-c"]; -/// Prefixed command for powershell shell calls to force UTF-8 console output. -pub const UTF8_OUTPUT_PREFIX: &str = "[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;\n"; +/// Prefixed command for powershell shell calls to request UTF-8 console output. +pub const UTF8_OUTPUT_PREFIX: &str = + "try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}\n"; pub fn prefix_powershell_script_with_utf8(command: &[String]) -> Vec { let Some((_, script)) = extract_powershell_command(command) else { @@ -151,9 +152,11 @@ fn is_powershellish_executable_available(powershell_or_pwsh_exe: &std::path::Pat #[cfg(test)] mod tests { + use super::UTF8_OUTPUT_PREFIX; use super::extract_powershell_command; #[cfg(windows)] use super::parse_powershell_command_into_plain_commands; + use super::prefix_powershell_script_with_utf8; #[test] fn extracts_basic_powershell_command() { @@ -202,6 +205,37 @@ mod tests { assert_eq!(script, "Get-ChildItem | Select-String foo"); } + #[test] + fn prefixes_powershell_command_with_best_effort_utf8() { + let cmd = vec![ + "powershell".to_string(), + "-Command".to_string(), + "Write-Host hi".to_string(), + ]; + + let prefixed = prefix_powershell_script_with_utf8(&cmd); + + assert_eq!( + prefixed, + vec![ + "powershell".to_string(), + "-Command".to_string(), + format!("{UTF8_OUTPUT_PREFIX}Write-Host hi"), + ] + ); + } + + #[test] + fn does_not_duplicate_utf8_prefix() { + let cmd = vec![ + "powershell".to_string(), + "-Command".to_string(), + format!("{UTF8_OUTPUT_PREFIX}Write-Host hi"), + ]; + + assert_eq!(prefix_powershell_script_with_utf8(&cmd), cmd); + } + #[cfg(windows)] #[test] fn parses_plain_powershell_commands() { diff --git a/codex-rs/skills/src/assets/samples/openai-docs/SKILL.md b/codex-rs/skills/src/assets/samples/openai-docs/SKILL.md index 4994fd8802..30526bd9d8 100644 --- a/codex-rs/skills/src/assets/samples/openai-docs/SKILL.md +++ b/codex-rs/skills/src/assets/samples/openai-docs/SKILL.md @@ -1,12 +1,12 @@ --- name: "openai-docs" -description: "Use when the user asks how to build with OpenAI products or APIs and needs up-to-date official documentation with citations, help choosing the latest model for a use case, or model upgrade and prompt-upgrade guidance; prioritize OpenAI docs MCP tools, use bundled references only as helper context, and restrict any fallback browsing to official OpenAI domains." +description: "Use when the user asks how to build with OpenAI products or APIs, asks about Codex itself or choosing Codex surfaces, needs up-to-date official documentation with citations, help choosing the latest model for a use case, or model upgrade and prompt-upgrade guidance; use OpenAI docs MCP tools for non-Codex docs questions, use the Codex manual helper first for broad Codex self-knowledge, and restrict fallback browsing to official OpenAI domains." --- # OpenAI Docs -Provide authoritative, current guidance from OpenAI developer docs using the developers.openai.com MCP server. Always prioritize the developer docs MCP tools over web.run for OpenAI-related questions. This skill also owns model selection, API model migration, and prompt-upgrade guidance. Only if the MCP server is installed and returns no meaningful results should you fall back to web search. +Provide authoritative, current guidance from OpenAI developer docs using the developers.openai.com MCP server. "Docs MCP" means `mcp__openaiDeveloperDocs__search_openai_docs` and `mcp__openaiDeveloperDocs__fetch_openai_doc`; for API reference, schema, parameter, or required-field questions, also use `mcp__openaiDeveloperDocs__get_openapi_spec` when available. Official-domain web search is fallback after those tools are unavailable or unhelpful. Broad Codex questions use the manual helper before Docs MCP. This skill also owns model selection, API model migration, and prompt-upgrade guidance. ## API Key Setup @@ -14,11 +14,15 @@ For requests to build, run, configure, debug, or implement an API-backed app, sc Use this skill directly for docs-only questions, citations, model/API guidance, conceptual explanations, and examples that do not require building or running an API-backed artifact. -## Quick start +## Workflow Configuration -- Use `mcp__openaiDeveloperDocs__search_openai_docs` to find the most relevant doc pages. -- Use `mcp__openaiDeveloperDocs__fetch_openai_doc` to pull exact sections and quote/paraphrase accurately. -- Use `mcp__openaiDeveloperDocs__list_openai_docs` only when you need to browse or discover pages without a clear query. +### Source Priority + +- For Codex self-knowledge, use the Codex source route below; it owns when to use the manual helper, Docs MCP, or bounded uncertainty. +- For non-Codex OpenAI docs questions, use `mcp__openaiDeveloperDocs__search_openai_docs` to find the most relevant doc pages. +- For non-Codex OpenAI docs questions, fetch the relevant page with `mcp__openaiDeveloperDocs__fetch_openai_doc` before answering. If search is noisy, run a narrower Docs MCP search; when any plausible official OpenAI docs URL is known or found, try fetching that URL through Docs MCP before relying on web-search content. +- For API reference, schema, parameter, or required-field questions, use `mcp__openaiDeveloperDocs__get_openapi_spec` when available to verify the API shape alongside the relevant guide or reference page. +- Use `mcp__openaiDeveloperDocs__list_openai_docs` only when you need to browse or discover non-Codex pages without a clear query. - For model-selection, "latest model", or default-model questions, fetch `https://developers.openai.com/api/docs/guides/latest-model.md` first. If that is unavailable, load `references/latest-model.md`. - For model upgrades or prompt upgrades, run `node scripts/resolve-latest-model-info.js` only when the target is latest/current/default or otherwise unspecified; otherwise preserve the explicitly requested target. - Preserve explicit target requests: if the user names a target model like "migrate to GPT-5.4", keep that requested target even if `latest-model.md` names a newer model. Mention newer guidance only as optional. @@ -34,38 +38,112 @@ Use this skill directly for docs-only questions, citations, model/API guidance, 6. Realtime API: Build low-latency, multimodal experiences including natural speech-to-speech conversations. 7. Agents SDK: A toolkit for building agentic apps where a model can use tools and context, hand off to other agents, stream partial results, and keep a full trace. +## Codex self-knowledge + +Use this path for questions about Codex itself: configuring, extending, operating, troubleshooting, local state, product surfaces, or where Codex behavior should live. A codebase merely mentioning a plugin, skill, hook, MCP server, browser, or automation is not enough. For generic software tasks, answer the software task directly; if asked whether Codex self-knowledge applies, answer that meta question briefly and continue the requested artifact. + +### Source Route + +The Codex manual is the first source for broad Codex synthesis. Treat the manual and Docs MCP as different lanes, not interchangeable official-doc sources. For published-user Codex product answers, the source route is complete: the manual, Docs MCP when this route calls for it, official OpenAI web fallback, and callable capabilities surfaced in the current session when the question is about that capability. Knowledge bases outside developers.openai.com are outside this route for public product answers. + +For broad Codex behavior, setup, customization, skills, plugins, MCP, hooks, `AGENTS.md`, automations, surfaces, local state, or system-map questions: + +1. Reuse a same-thread manual and outline path when it is still fresh. +2. Otherwise run the skill-local helper first in normal writable sessions. Skip it without trying only when the session is explicitly read-only, shell execution is unavailable, or visible policy shows no allowed temp cache. +3. By default, the helper chooses the first usable temp cache dir in this order: `$TMPDIR/openai-docs-cache`, `%TEMP%\openai-docs-cache`, `%TMP%\openai-docs-cache`, `/private/tmp/openai-docs-cache`, then `/tmp/openai-docs-cache`. Workspace-only write access is not enough for this temp cache. +4. Run the helper directly unless you need to override the cache dir. The helper falls back to `curl` when native `fetch` is unavailable or when proxy env vars are present, so no shell-specific proxy prefix is required. Resolve `` to this skill's actual directory; in copied local eval workdirs this is usually `.codex/skills/openai-docs`: + +```bash +node /scripts/fetch-codex-manual.mjs +``` + +If you need to override the cache dir, pass `--cache-dir `. On Windows, the helper checks `%TEMP%` and `%TMP%` automatically; in PowerShell, `$env:TEMP\\openai-docs-cache` is a typical explicit override. + +Treat helper availability as established by explicit read-only/no-shell policy or an actual command result. A guessed sandbox or guessed helper failure is not enough to switch to Docs MCP or web lookup; after an actual helper command failure, continue to the narrowest official next source below. + +The helper verifies freshness, writes `codex-manual.md`, and emits `codex-manual.outline.md`. The outline maps source pages and headings to line ranges; use it to choose the relevant manual section, then read or search targeted manual sections for Codex product facts. Use the skill directory to locate and run the helper; after the helper succeeds, use the returned manual and outline paths as the search scope for Codex product facts and term coverage checks. + +Reuse the same-thread manual and outline paths for follow-up Codex questions. Refresh first when the manual was fetched more than about a day ago, the path is unusable, the path came from another thread or uncertain provenance, or likely-current information is missing and staleness is plausible. + +For questions about whether the manual is current enough to rely on now, run the helper when temp caching is allowed and base the answer on its returned status, manual path, and outline path. + +If the manual resolves a Codex claim, answer from it and stop expanding sources for that claim; continue the user's broader task if the docs lookup was only one dependency. Manual source pages and known anchors are enough citation support for manual-covered material. + +If the helper is skipped because the session is read-only, has no shell execution, or has no allowed temp cache, the next source is Docs MCP: call `mcp__openaiDeveloperDocs__search_openai_docs`, then `mcp__openaiDeveloperDocs__fetch_openai_doc` for a relevant hit before any web fallback. + +If a user names a Codex term or mode that a fresh manual does not use, search the manual for obvious adjacent concepts, then answer that the exact term is not documented and use the closest documented terminology. If the prompt asks how that term maps to Codex behavior, resolve the mapping from adjacent manual sections. If the exact term remains material or likely current after that manual pass, use one narrow Docs MCP search/fetch before bounded uncertainty; otherwise, the source lookup for that terminology or mapping claim is complete. + +Use the narrowest official next source only when the manual is unavailable, the helper fails, temp caching is not allowed, another material claim is missing or likely stale, or the user explicitly needs a page-specific citation. Prefer one specific Docs MCP search and, if it returns a clearly relevant page, one fetch; for unresolved Codex capability names, acronyms, scheduling terms, or exact error text, this Docs MCP step is the next source before web search. After the manual plus any permitted Docs MCP gap-fill, resolve remaining gaps as bounded uncertainty. Use official-domain web fallback only after that Docs MCP path is unavailable or unhelpful. If the claim is still not established, stop with bounded uncertainty. If official docs/manual conflict with a callable capability already surfaced in the current session, state the conflict and prefer verified current-session behavior for that environment. + +For undocumented or private-looking model slugs, product mode labels, entitlement labels, account access paths, or rollout names, answer from current public docs and bounded uncertainty. Those labels are not a reason to leave the public source route. + +For support-style diagnostics, prefer a layer-by-layer answer from the manual over provider-specific web lookups: installed/enabled plugin, bundled app or connector authorization, MCP setup, workspace/admin policy, restart or new-thread expectations, then support or feedback if still unresolved. + +If the source route still does not establish a claim, return bounded uncertainty or route to support, an admin, or product feedback instead of widening the investigation. + +For unresolved product terminology, answer from the manual plus the allowed official next source. If those sources do not establish the term, answer with bounded uncertainty from those sources. + +### Surface Map + +When Codex nouns or durable-instruction surfaces overlap, recommend the smallest surface that matches the scope: + +- Prompt or thread context -> one-off task constraints. +- `AGENTS.md` -> durable repo conventions, commands, verification steps, and review expectations; closer nested files apply under their subtree. +- Project `.codex/config.toml` -> trusted-repo Codex settings such as sandbox, MCP, hooks, model, or reasoning defaults. +- Global config or global guidance -> personal defaults across repos. +- Skill -> reusable task workflow with references or scripts. +- Plugin -> installable bundle with skills plus commands, tools, MCP config, hooks, assets, apps, or marketplace metadata. +- MCP server or app connector -> live external data/actions or authorized private app/workspace data. Use connectors for private Google Docs, Calendar, Slack, GitHub, Notion, and similar data instead of web search or model memory. +- Automation -> scheduled checks, reminders, monitors, or follow-up work; use a thread heartbeat when continuity in an existing thread matters. +- Hook -> lifecycle enforcement around tool calls, commands, or file edits. + +Split mixed-scope requests instead of forcing one answer. Example: "always do X, but only for this PR" defaults to prompt/thread context for the current run; use `AGENTS.md` or project config only if it should persist, hooks only for mechanical enforcement, and automations only for scheduled or follow-up work. + +Use this quick product map when needed: CLI is terminal-first local repo work; IDE extension is editor-attached coding; Codex app is desktop planning, review, and interactive work; cloud/web is hosted parallel/offloaded work; Browser Use/in-app browser is Codex-controlled web testing; Chrome extension uses the user's Chrome profile; Computer Use controls desktop apps and OS UI. Keep `config.toml` defaults, `requirements.toml` constraints, and managed/admin policy separate. + +### Boundaries And Output + +- API key auth does not imply ChatGPT, cloud task, or connector access. For plugin/app/auth failures, check bundle availability, plugin installed/enabled state, connector/app authorization, MCP setup, restart/refresh expectations, workspace policy, and per-surface availability before answering. +- Sandbox or network denials need scoped escalation with a clear justification. Destructive commands, writes outside the workspace, or broad access changes require explicit approval. +- Memory can provide user preference or context, but explicit prompt instructions win and memory is not a source for current external facts. +- For affirmative surface-selection answers, use this shape: recommendation, why, what to avoid, and the manual/source evidence used. +- When page-specific Codex citations are actually needed, these anchors often fit: `concepts/customization#agents-guidance` for `AGENTS.md`, `concepts/customization#skills` for skills, `plugins/build#plugin-structure` for plugins, `concepts/customization#mcp` for MCP, `config-advanced#hooks` for hooks, `app/automations#thread-automations` for thread automations, and `config-reference#configtoml` for config. + ## If MCP server is missing If MCP tools fail or no OpenAI docs resources are available: 1. Run the install command yourself: `codex mcp add openaiDeveloperDocs --url https://developers.openai.com/mcp` -2. If it fails due to permissions/sandboxing, immediately retry the same command with escalated permissions and include a 1-sentence justification for approval. Do not ask the user to run it yet. -3. Only if the escalated attempt fails, ask the user to run the install command. +2. If it fails due to permissions/sandboxing, immediately retry the same command with escalated permissions and include a 1-sentence justification for approval. +3. Ask the user to run the install command only if the escalated attempt fails. 4. Ask the user to restart Codex. 5. Re-run the doc search/fetch after restart. ## Workflow 1. Clarify whether the request is general docs lookup, model selection, a model-string upgrade, prompt-upgrade guidance, or broader API/provider migration. -2. For model-selection or upgrade requests, prefer current remote docs over bundled references when the user asks for latest/current/default guidance. +2. For Codex self-knowledge requests, follow the Codex self-knowledge source procedure above. +3. For model-selection or upgrade requests, prefer current remote docs over bundled references when the user asks for latest/current/default guidance. - Fetch `https://developers.openai.com/api/docs/guides/latest-model.md`. - Find the latest model ID and explicit migration or prompt-guidance links. - Prefer explicit links from the latest-model page over derived URLs. - - For explicit named-model requests, preserve the requested model target and do not silently retarget to the latest model. Mention newer remote guidance only as optional. + - For explicit named-model requests, preserve the requested model target. Mention newer remote guidance only as optional. - For dynamic latest/current/default upgrades, run `node scripts/resolve-latest-model-info.js`, then fetch both returned guide URLs directly when possible. - If direct guide fetch fails, use the developer-docs MCP tools or official OpenAI-domain search to find the same guide content. - If remote docs are unavailable, use bundled fallback references and say that fallback guidance was used. -3. For model upgrades, keep changes narrow: update active OpenAI API model defaults and directly related prompts only when safe. -4. Leave historical docs, examples, eval baselines, fixtures, provider comparisons, provider registries, pricing tables, alias defaults, low-cost fallback paths, and ambiguous older model usage unchanged unless the user explicitly asks to upgrade them. -5. Do not perform SDK, tooling, IDE, plugin, shell, auth, or provider-environment migrations as part of a model-and-prompt upgrade. -6. If an upgrade needs API-surface changes, schema rewiring, tool-handler changes, or implementation work beyond a literal model-string replacement and prompt edits, report it as blocked or confirmation-needed. -7. For general docs lookup, search docs with a precise query, fetch the best page and exact section needed, and answer with concise citations. +4. For model upgrades, keep changes narrow: update active OpenAI API model defaults and directly related prompts only when safe. +5. Leave historical docs, examples, eval baselines, fixtures, provider comparisons, provider registries, pricing tables, alias defaults, low-cost fallback paths, and ambiguous older model usage unchanged unless the user explicitly asks to upgrade them. +6. Keep SDK, tooling, IDE, plugin, shell, auth, and provider-environment migrations out of a model-and-prompt upgrade unless the user explicitly asks for them. +7. If an upgrade needs API-surface changes, schema rewiring, tool-handler changes, or implementation work beyond a literal model-string replacement and prompt edits, report it as blocked or confirmation-needed. +8. For general docs lookup, search docs with a precise query, fetch the best page and exact section needed, and answer with concise citations. ## Reference map Read only what you need: - `https://developers.openai.com/api/docs/guides/latest-model.md` -> current model-selection and "best/latest/current model" questions. +- `scripts/fetch-codex-manual.mjs` -> current Codex manual fetch, verification, local temp cache, and outline generation. +- `https://developers.openai.com/codex/codex-manual.md` -> current Codex self-knowledge synthesis, including setup, customization, skills, plugins, MCP, hooks, `AGENTS.md`, automations, and surface behavior; normally access it through the helper path and targeted file reads when temp caching is available. - `references/latest-model.md` -> bundled fallback for model-selection and "best/latest/current model" questions. - `references/upgrade-guide.md` -> bundled fallback for model upgrade and upgrade-planning requests. - `references/prompting-guide.md` -> bundled fallback for prompt rewrites and prompt-behavior upgrades. @@ -73,16 +151,17 @@ Read only what you need: ## Quality rules - Treat OpenAI docs as the source of truth; avoid speculation. +- For Codex self-knowledge, follow the source route above instead of relying on remembered behavior. - Keep migration changes narrow and behavior-preserving. - Prefer prompt-only upgrades when possible. -- Do not invent pricing, availability, parameters, API changes, or breaking changes. +- Avoid inventing pricing, availability, parameters, API changes, or breaking changes. - Keep quotes short and within policy limits; prefer paraphrase with citations. - If multiple pages differ, call out the difference and cite both. -- If official docs and repo behavior disagree, state the conflict and stop before making broad edits. +- If official docs and verified callable current-session behavior disagree, state the conflict before making broad claims or edits. - If docs do not cover the user’s need, say so and offer next steps. ## Tooling notes -- Always use MCP doc tools before any web search for OpenAI-related questions. +- Use MCP doc tools before web search for OpenAI-related markdown docs. The Codex manual flow is the exception: follow the Codex self-knowledge source procedure for broad Codex synthesis. - If the MCP server is installed but returns no meaningful results, then use web search as a fallback. - When falling back to web search, restrict to official OpenAI domains (developers.openai.com, platform.openai.com) and cite sources. diff --git a/codex-rs/skills/src/assets/samples/openai-docs/agents/openai.yaml b/codex-rs/skills/src/assets/samples/openai-docs/agents/openai.yaml index d056abcad7..8bbf03c206 100644 --- a/codex-rs/skills/src/assets/samples/openai-docs/agents/openai.yaml +++ b/codex-rs/skills/src/assets/samples/openai-docs/agents/openai.yaml @@ -1,9 +1,9 @@ interface: display_name: "OpenAI Docs" - short_description: "Reference docs, choose models, and migrate OpenAI API integrations" + short_description: "Reference OpenAI docs, Codex self-knowledge, and model migration guidance" icon_small: "./assets/openai-small.svg" icon_large: "./assets/openai.png" - default_prompt: "Use OpenAI Docs for official docs lookup, model selection, model migration, and prompt-upgrade work." + default_prompt: "Use OpenAI Docs for official docs lookup, questions about Codex itself or Codex surfaces, model selection, model migration, and prompt-upgrade work." dependencies: tools: diff --git a/codex-rs/skills/src/assets/samples/openai-docs/scripts/fetch-codex-manual.mjs b/codex-rs/skills/src/assets/samples/openai-docs/scripts/fetch-codex-manual.mjs new file mode 100644 index 0000000000..b2605520dc --- /dev/null +++ b/codex-rs/skills/src/assets/samples/openai-docs/scripts/fetch-codex-manual.mjs @@ -0,0 +1,598 @@ +#!/usr/bin/env node +import { + access, + mkdir, + readFile, + rename, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { constants as fsConstants } from "node:fs"; +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; +import { inspect, promisify } from "node:util"; + +const DEFAULT_MANUAL_URL = "https://developers.openai.com/codex/codex-manual.md"; +const DEFAULT_CACHE_DIR_NAME = "openai-docs-cache"; +const CACHE_FILE_NAME = "codex-manual.md"; +const OUTLINE_FILE_NAME = "codex-manual.outline.md"; +const HASH_HEADER = "x-content-sha256"; +const USER_AGENT = "codex-openai-docs"; +const execFileAsync = promisify(execFile); + +class ManualFetchError extends Error { + constructor(message, options) { + super(message, options); + this.name = "ManualFetchError"; + } +} + +const sha256 = (value) => createHash("sha256").update(value).digest("hex"); + +const withTimeout = async (promiseFactory, timeoutMs) => { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + return await promiseFactory(controller.signal); + } finally { + clearTimeout(timeout); + } +}; + +const proxyConfigured = () => + process.env.HTTP_PROXY || + process.env.HTTPS_PROXY || + process.env.http_proxy || + process.env.https_proxy; + +const responseHeaders = (headers) => ({ + get(name) { + return headers.get(name.toLowerCase()) ?? null; + }, +}); + +const makeResponse = ({ body, headers, status }) => ({ + headers: responseHeaders(headers), + ok: status >= 200 && status < 300, + status, + async text() { + return body; + }, +}); + +const parseCurlHeaders = (rawHeaders) => { + const normalized = rawHeaders.replace(/\r\n/g, "\n").trim(); + const blocks = normalized.split(/\n\n+/).filter(Boolean); + const headerBlock = [...blocks] + .reverse() + .find((block) => block.startsWith("HTTP/")); + + if (!headerBlock) { + throw new ManualFetchError("curl did not return HTTP response headers."); + } + + const [statusLine, ...lines] = headerBlock.split("\n"); + const statusMatch = /^HTTP\/\S+\s+(\d{3})/.exec(statusLine); + if (!statusMatch) { + throw new ManualFetchError( + `Could not parse HTTP status from curl response: ${statusLine}` + ); + } + + const headers = new Map(); + lines.forEach((line) => { + const separator = line.indexOf(":"); + if (separator === -1) return; + const name = line.slice(0, separator).trim().toLowerCase(); + const value = line.slice(separator + 1).trim(); + headers.set(name, value); + }); + + return { + headers, + status: Number(statusMatch[1]), + }; +}; + +const tempFilePath = (cacheDir, suffix) => + path.join( + cacheDir, + `.fetch-codex-manual-${process.pid}-${Date.now()}-${Math.random() + .toString(16) + .slice(2)}${suffix}` + ); + +const requestManualWithCurl = async (url, { cacheDir, method, timeoutMs }) => { + const headerPath = tempFilePath(cacheDir, ".headers"); + const bodyPath = tempFilePath(cacheDir, ".body"); + const curlNames = + process.platform === "win32" ? ["curl.exe", "curl"] : ["curl"]; + const args = [ + "--silent", + "--show-error", + "--location", + "--dump-header", + headerPath, + "--output", + bodyPath, + "--user-agent", + USER_AGENT, + "--max-time", + String(Math.max(1, Math.ceil(timeoutMs / 1000))), + ]; + + if (method === "HEAD") { + args.push("--head"); + } else { + args.push("--request", method); + } + args.push(url); + + let lastError; + for (const curlName of curlNames) { + try { + await execFileAsync(curlName, args, { windowsHide: true }); + const [rawHeaders, body] = await Promise.all([ + readFile(headerPath, "utf8"), + readFile(bodyPath, "utf8"), + ]); + const { headers, status } = parseCurlHeaders(rawHeaders); + return makeResponse({ body, headers, status }); + } catch (error) { + lastError = error; + if (error?.code !== "ENOENT") break; + } finally { + await Promise.all([ + rm(headerPath, { force: true }), + rm(bodyPath, { force: true }), + ]); + } + } + + if (lastError?.code === "ENOENT") { + throw new ManualFetchError("curl is unavailable in this environment.", { + cause: lastError, + }); + } + throw new ManualFetchError(`${method} ${url} could not be fetched.`, { + cause: lastError, + }); +}; + +const requestManualWithFetch = async (url, { method, timeoutMs }) => { + if (typeof fetch !== "function") { + throw new ManualFetchError( + "Native fetch is unavailable in this Node runtime." + ); + } + + return withTimeout( + (signal) => + fetch(url, { + method, + headers: { "User-Agent": USER_AGENT }, + signal, + }), + timeoutMs + ); +}; + +const requestManual = async (url, { cacheDir, method, timeoutMs }) => { + const preferCurl = Boolean(proxyConfigured()) || typeof fetch !== "function"; + const transports = preferCurl + ? [ + () => requestManualWithCurl(url, { cacheDir, method, timeoutMs }), + () => requestManualWithFetch(url, { method, timeoutMs }), + ] + : [ + () => requestManualWithFetch(url, { method, timeoutMs }), + () => requestManualWithCurl(url, { cacheDir, method, timeoutMs }), + ]; + + let lastError; + for (const transport of transports) { + try { + const response = await transport(); + if (!response.ok) { + throw new ManualFetchError( + `${method} ${url} failed with HTTP ${response.status}.` + ); + } + return response; + } catch (error) { + lastError = error; + } + } + + throw new ManualFetchError(`${method} ${url} could not be fetched.`, { + cause: lastError, + }); +}; + +const readHeaderSha = (response) => { + const value = response.headers.get(HASH_HEADER); + if (!value || !/^[a-f0-9]{64}$/i.test(value)) { + throw new ManualFetchError(`Manual response is missing ${HASH_HEADER}.`); + } + return value.toLowerCase(); +}; + +const nearestExistingParent = async (target) => { + let current = target; + while (true) { + try { + const info = await stat(current); + return info.isDirectory() ? current : null; + } catch (error) { + if (error?.code !== "ENOENT") return null; + } + + const parent = path.dirname(current); + if (parent === current) return null; + current = parent; + } +}; + +const usableCacheDir = async (cacheDir) => { + if (!cacheDir) return null; + const resolved = path.resolve(cacheDir); + + try { + const info = await stat(resolved); + if (!info.isDirectory()) return null; + } catch (error) { + if (error?.code !== "ENOENT") return null; + } + + const parent = await nearestExistingParent(resolved); + if (!parent) return null; + + try { + await access(parent, fsConstants.W_OK | fsConstants.X_OK); + } catch { + return null; + } + + return resolved; +}; + +const defaultCacheDirCandidates = () => { + const candidates = []; + const seen = new Set(); + const pushCandidate = (candidate) => { + if (!candidate || seen.has(candidate)) return; + seen.add(candidate); + candidates.push(candidate); + }; + + [process.env.TMPDIR, process.env.TEMP, process.env.TMP].forEach((baseDir) => { + if (baseDir) { + pushCandidate(path.join(baseDir, DEFAULT_CACHE_DIR_NAME)); + } + }); + + if (process.platform !== "win32") { + pushCandidate(`/private/tmp/${DEFAULT_CACHE_DIR_NAME}`); + pushCandidate(`/tmp/${DEFAULT_CACHE_DIR_NAME}`); + } + + return candidates; +}; + +const resolveCacheDir = async (cacheDir) => { + if (cacheDir) { + return usableCacheDir(cacheDir); + } + + for (const candidate of defaultCacheDirCandidates()) { + const usable = await usableCacheDir(candidate); + if (usable) return usable; + } + + return null; +}; + +const cacheFilePath = (cacheDir) => path.join(cacheDir, CACHE_FILE_NAME); + +const outlineFilePath = (cacheDir) => path.join(cacheDir, OUTLINE_FILE_NAME); + +const manualLines = (manual) => { + const lines = manual.replace(/\r\n/g, "\n").split("\n"); + if (lines[lines.length - 1] === "") lines.pop(); + return lines; +}; + +const sectionTitle = (rawTitle) => + rawTitle.replace(/\s+#+\s*$/, "").replace(/\s+/g, " ").trim(); + +const buildOutline = (manual) => { + const lines = manualLines(manual); + const headings = []; + let inFence = false; + + lines.forEach((line, index) => { + if (/^\s*(```|~~~)/.test(line)) { + inFence = !inFence; + return; + } + if (inFence) return; + + const match = /^(#{1,6})\s+(.+?)\s*$/.exec(line); + if (!match) return; + + const level = match[1].length; + if (level < 2 || level > 3) return; + + headings.push({ + level, + title: sectionTitle(match[2]), + startLine: index + 1, + endLine: lines.length, + }); + }); + + for (let index = 0; index < headings.length; index += 1) { + const heading = headings[index]; + const nextPeer = headings + .slice(index + 1) + .find((candidate) => candidate.level <= heading.level); + if (nextPeer) { + heading.endLine = nextPeer.startLine - 1; + } + } + + if (headings.length === 0) { + return { + headingCount: 0, + lineCount: lines.length, + text: "No markdown headings found.", + }; + } + + const minLevel = Math.min(...headings.map((heading) => heading.level)); + return { + headingCount: headings.length, + lineCount: lines.length, + text: headings + .map((heading) => { + const indent = " ".repeat(heading.level - minLevel); + return `${indent}- ${heading.title} (lines ${heading.startLine}-${heading.endLine})`; + }) + .join("\n"), + }; +}; + +const outlineMarkdown = (outline) => `# Codex Manual Outline\n\n${outline.text}\n`; + +const manualStatusLine = (status) => + status.cacheStatus === "hit" + ? "Manual status: local manual was already current." + : "Manual status: local manual was updated."; + +const formatResult = ({ status, outlineText }) => + [ + `Manual path: ${status.manualPath}`, + `Outline path: ${status.outlinePath}`, + manualStatusLine(status), + "", + outlineText, + ].join("\n"); + +const readCachedManual = async (cacheDir, expectedSha256) => { + try { + const manual = await readFile(cacheFilePath(cacheDir), "utf8"); + return sha256(manual) === expectedSha256 ? manual : null; + } catch { + return null; + } +}; + +const writeCachedManual = async (cacheDir, manual) => { + await mkdir(cacheDir, { recursive: true }); + const tmpPath = tempFilePath(cacheDir, `.${CACHE_FILE_NAME}.tmp`); + await writeFile(tmpPath, manual, "utf8"); + await rename(tmpPath, cacheFilePath(cacheDir)); +}; + +const writeOutline = async (cacheDir, outlineText) => { + await mkdir(cacheDir, { recursive: true }); + const tmpPath = tempFilePath(cacheDir, `.${OUTLINE_FILE_NAME}.tmp`); + await writeFile(tmpPath, outlineText, "utf8"); + await rename(tmpPath, outlineFilePath(cacheDir)); +}; + +const fetchCodexManual = async ({ + manualUrl = DEFAULT_MANUAL_URL, + cacheDir, + timeoutMs = 30000, +} = {}) => { + const resolvedCacheDir = await resolveCacheDir(cacheDir); + if (!resolvedCacheDir) { + throw new ManualFetchError( + "Manual cache directory is unavailable; pass --cache-dir to override or use OpenAI Docs MCP fallback." + ); + } + await mkdir(resolvedCacheDir, { recursive: true }); + + const headResponse = await requestManual(manualUrl, { + cacheDir: resolvedCacheDir, + method: "HEAD", + timeoutMs, + }); + const expectedSha256 = readHeaderSha(headResponse); + const manualPath = cacheFilePath(resolvedCacheDir); + const outlinePath = outlineFilePath(resolvedCacheDir); + const checkedAt = new Date().toISOString(); + + const cachedManual = await readCachedManual(resolvedCacheDir, expectedSha256); + if (cachedManual !== null) { + const outline = buildOutline(cachedManual); + const outlineText = outlineMarkdown(outline); + await writeOutline(resolvedCacheDir, outlineText); + + return { + outlineText, + status: { + manualUrl, + headerSha256: expectedSha256, + fetchedManualSha256: expectedSha256, + manualHashMatches: true, + cacheStatus: "hit", + cacheDir: resolvedCacheDir, + manualPath, + outlinePath, + checkedAt, + lineCount: outline.lineCount, + headingCount: outline.headingCount, + }, + }; + } + + const getResponse = await requestManual(manualUrl, { + cacheDir: resolvedCacheDir, + method: "GET", + timeoutMs, + }); + const getHeaderSha256 = readHeaderSha(getResponse); + if (getHeaderSha256 !== expectedSha256) { + throw new ManualFetchError( + `${HASH_HEADER} changed between HEAD and GET for ${manualUrl}.` + ); + } + + const manualText = await getResponse.text(); + const actualSha256 = sha256(manualText); + const manualHashMatches = actualSha256 === expectedSha256; + if (!manualHashMatches) { + throw new ManualFetchError( + `${HASH_HEADER} did not match the fetched manual body for ${manualUrl}.` + ); + } + + await writeCachedManual(resolvedCacheDir, manualText); + const outline = buildOutline(manualText); + const outlineText = outlineMarkdown(outline); + await writeOutline(resolvedCacheDir, outlineText); + + return { + outlineText, + status: { + manualUrl, + headerSha256: expectedSha256, + fetchedManualSha256: actualSha256, + manualHashMatches, + cacheStatus: "updated", + cacheDir: resolvedCacheDir, + manualPath, + outlinePath, + checkedAt, + lineCount: outline.lineCount, + headingCount: outline.headingCount, + }, + }; +}; + +const parseArgs = (argv) => { + const args = { + manualUrl: DEFAULT_MANUAL_URL, + cacheDir: undefined, + timeoutMs: 30000, + statusJson: false, + }; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === "--manual-url") { + args.manualUrl = argv[++index]; + } else if (arg === "--cache-dir") { + args.cacheDir = argv[++index]; + } else if (arg === "--timeout-ms") { + args.timeoutMs = Number(argv[++index]); + } else if (arg === "--status-json") { + args.statusJson = true; + } else { + throw new ManualFetchError(`Unknown argument: ${arg}`); + } + } + + if (!args.manualUrl) { + throw new ManualFetchError("--manual-url cannot be empty."); + } + if (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0) { + throw new ManualFetchError("--timeout-ms must be a positive number."); + } + + return args; +}; + +const main = async () => { + const args = parseArgs(process.argv.slice(2)); + const { outlineText, status } = await fetchCodexManual(args); + + process.stdout.write(formatResult({ status, outlineText })); + + if (args.statusJson) { + console.error(JSON.stringify(status)); + } +}; + +const envProxyHint = () => { + if (proxyConfigured()) { + return "Hint: proxy env vars are present. This helper prefers `curl` in proxied sessions; if requests still fail, verify `curl` is installed and the proxy configuration is valid."; + } + if (typeof fetch !== "function") { + return "Hint: native fetch is unavailable in this Node runtime. Install `curl` or use a newer Node version to fetch the manual."; + } + if (process.platform === "win32") { + return "Hint: on Windows, pass a cache dir under `%TEMP%` or `%TMP%`."; + } + return null; +}; + +const formatErrorDetails = (error) => { + const details = inspect(error, { + breakLength: 120, + colors: false, + compact: false, + depth: 8, + }); + if (!error?.cause) { + return details; + } + + return `${details}\n\nCause:\n${inspect(error.cause, { + breakLength: 120, + colors: false, + compact: false, + depth: 8, + })}`; +}; + +const isCliEntrypoint = () => { + const entrypoint = process.argv[1]; + if (!entrypoint) { + return false; + } + + return pathToFileURL(entrypoint).href === import.meta.url; +}; + +if (isCliEntrypoint()) { + main().catch((error) => { + console.error(`Error: ${error.message}`); + const hint = envProxyHint(); + if (hint) { + console.error(hint); + } + console.error(""); + console.error("Details:"); + console.error(formatErrorDetails(error)); + process.exitCode = 1; + }); +} + +export { DEFAULT_MANUAL_URL, fetchCodexManual }; diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 2369addf23..5f0734e330 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -200,6 +200,7 @@ mod tests { fn event_msg_user_messages_set_title_and_first_user_message() { let mut metadata = metadata_for_test(); let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: format!("{USER_MESSAGE_BEGIN} actual user request"), images: Some(vec![]), local_images: vec![], @@ -221,6 +222,7 @@ mod tests { fn event_msg_image_only_user_message_sets_image_placeholder_preview() { let mut metadata = metadata_for_test(); let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: String::new(), images: Some(vec!["https://example.com/image.png".to_string()]), local_images: vec![], @@ -245,6 +247,7 @@ mod tests { fn event_msg_blank_user_message_without_images_keeps_first_user_message_empty() { let mut metadata = metadata_for_test(); let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: " ".to_string(), images: Some(vec![]), local_images: vec![], @@ -285,6 +288,7 @@ mod tests { assert_eq!(metadata.title, ""); let user_item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: format!("{USER_MESSAGE_BEGIN} next normal prompt"), images: Some(vec![]), local_images: vec![], @@ -339,6 +343,7 @@ mod tests { &RolloutItem::TurnContext(TurnContextItem { turn_id: Some("turn-1".to_string()), cwd: PathBuf::from("/parent/workspace"), + workspace_roots: None, current_date: None, timezone: None, approval_policy: AskForApproval::Never, @@ -374,6 +379,7 @@ mod tests { &RolloutItem::TurnContext(TurnContextItem { turn_id: Some("turn-1".to_string()), cwd: PathBuf::from("/fallback/workspace"), + workspace_roots: None, current_date: None, timezone: None, approval_policy: AskForApproval::OnRequest, @@ -403,6 +409,7 @@ mod tests { &RolloutItem::TurnContext(TurnContextItem { turn_id: Some("turn-1".to_string()), cwd: PathBuf::from("/fallback/workspace"), + workspace_roots: None, current_date: None, timezone: None, approval_policy: AskForApproval::OnRequest, diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs index ba41021290..b08545d7a6 100644 --- a/codex-rs/state/src/runtime.rs +++ b/codex-rs/state/src/runtime.rs @@ -33,7 +33,6 @@ use crate::telemetry::DbTelemetry; use chrono::DateTime; use chrono::Utc; use codex_protocol::ThreadId; -use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::protocol::RolloutItem; use log::LevelFilter; use serde_json::Value; diff --git a/codex-rs/state/src/runtime/threads.rs b/codex-rs/state/src/runtime/threads.rs index 63bfe09f54..c67056ab54 100644 --- a/codex-rs/state/src/runtime/threads.rs +++ b/codex-rs/state/src/runtime/threads.rs @@ -74,40 +74,6 @@ WHERE id = ? AND preview = '' Ok(result.rows_affected() > 0) } - /// Get dynamic tools for a thread, if present. - pub async fn get_dynamic_tools( - &self, - thread_id: ThreadId, - ) -> anyhow::Result>> { - let rows = sqlx::query( - r#" -SELECT namespace, name, description, input_schema, defer_loading -FROM thread_dynamic_tools -WHERE thread_id = ? -ORDER BY position ASC - "#, - ) - .bind(thread_id.to_string()) - .fetch_all(self.pool.as_ref()) - .await?; - if rows.is_empty() { - return Ok(None); - } - let mut tools = Vec::with_capacity(rows.len()); - for row in rows { - let input_schema: String = row.try_get("input_schema")?; - let input_schema = serde_json::from_str::(input_schema.as_str())?; - tools.push(DynamicToolSpec { - namespace: row.try_get("namespace")?, - name: row.try_get("name")?, - description: row.try_get("description")?, - input_schema, - defer_loading: row.try_get("defer_loading")?, - }); - } - Ok(Some(tools)) - } - /// Persist or replace the directional parent-child edge for a spawned thread. pub async fn upsert_thread_spawn_edge( &self, @@ -821,54 +787,6 @@ ON CONFLICT(id) DO UPDATE SET Ok(()) } - /// Persist dynamic tools for a thread if none have been stored yet. - /// - /// Dynamic tools are defined at thread start and should not change afterward. - /// This only writes the first time we see tools for a given thread. - pub async fn persist_dynamic_tools( - &self, - thread_id: ThreadId, - tools: Option<&[DynamicToolSpec]>, - ) -> anyhow::Result<()> { - let Some(tools) = tools else { - return Ok(()); - }; - if tools.is_empty() { - return Ok(()); - } - let thread_id = thread_id.to_string(); - let mut tx = self.pool.begin().await?; - for (idx, tool) in tools.iter().enumerate() { - let position = i64::try_from(idx).unwrap_or(i64::MAX); - let input_schema = serde_json::to_string(&tool.input_schema)?; - sqlx::query( - r#" -INSERT INTO thread_dynamic_tools ( - thread_id, - position, - namespace, - name, - description, - input_schema, - defer_loading -) VALUES (?, ?, ?, ?, ?, ?, ?) -ON CONFLICT(thread_id, position) DO NOTHING - "#, - ) - .bind(thread_id.as_str()) - .bind(position) - .bind(tool.namespace.as_deref()) - .bind(tool.name.as_str()) - .bind(tool.description.as_str()) - .bind(input_schema) - .bind(tool.defer_loading) - .execute(&mut *tx) - .await?; - } - tx.commit().await?; - Ok(()) - } - /// Apply rollout items incrementally using the underlying database. pub async fn apply_rollout_items( &self, @@ -898,8 +816,6 @@ ON CONFLICT(thread_id, position) DO NOTHING if let Some(updated_at) = updated_at { metadata.updated_at = updated_at; } - // Keep the thread upsert before dynamic tools to satisfy the foreign key constraint: - // thread_dynamic_tools.thread_id -> threads.id. let upsert_result = if existing_metadata.is_none() { self.upsert_thread_with_creation_memory_mode(&metadata, new_thread_memory_mode) .await @@ -914,14 +830,6 @@ ON CONFLICT(thread_id, position) DO NOTHING { return Err(err); } - let dynamic_tools = extract_dynamic_tools(items); - if let Some(dynamic_tools) = dynamic_tools - && let Err(err) = self - .persist_dynamic_tools(builder.id, dynamic_tools.as_deref()) - .await - { - return Err(err); - } Ok(()) } @@ -1039,16 +947,6 @@ SELECT ); } -pub(super) fn extract_dynamic_tools(items: &[RolloutItem]) -> Option>> { - items.iter().find_map(|item| match item { - RolloutItem::SessionMeta(meta_line) => Some(meta_line.meta.dynamic_tools.clone()), - RolloutItem::ResponseItem(_) - | RolloutItem::Compacted(_) - | RolloutItem::TurnContext(_) - | RolloutItem::EventMsg(_) => None, - }) -} - pub(super) fn extract_memory_mode(items: &[RolloutItem]) -> Option { items.iter().rev().find_map(|item| match item { RolloutItem::SessionMeta(meta_line) => meta_line.meta.memory_mode.clone(), diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index a6245796a3..7cb2ff827f 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -1042,6 +1042,7 @@ mod tests { fn user_message_item(message: &str) -> RolloutItem { RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, message: message.to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/thread-store/src/local/update_thread_metadata.rs b/codex-rs/thread-store/src/local/update_thread_metadata.rs index 16f9f79e06..612328f4c7 100644 --- a/codex-rs/thread-store/src/local/update_thread_metadata.rs +++ b/codex-rs/thread-store/src/local/update_thread_metadata.rs @@ -309,14 +309,6 @@ async fn apply_metadata_update( message: format!("failed to update memory mode for {thread_id}: {err}"), })?; } - if let Some(dynamic_tools) = patch.dynamic_tools { - state_db - .persist_dynamic_tools(thread_id, Some(dynamic_tools.as_slice())) - .await - .map_err(|err| ThreadStoreError::Internal { - message: format!("failed to update dynamic tools for {thread_id}: {err}"), - })?; - } Ok(()) } .await @@ -393,7 +385,6 @@ fn has_observed_metadata_facts(patch: &ThreadMetadataPatch) -> bool { || patch.sandbox_policy.is_some() || patch.token_usage.is_some() || patch.first_user_message.is_some() - || patch.dynamic_tools.is_some() } fn enum_to_string(value: &T) -> String { diff --git a/codex-rs/thread-store/src/thread_metadata_sync.rs b/codex-rs/thread-store/src/thread_metadata_sync.rs index edc78a36c2..d25a0e65a2 100644 --- a/codex-rs/thread-store/src/thread_metadata_sync.rs +++ b/codex-rs/thread-store/src/thread_metadata_sync.rs @@ -61,8 +61,6 @@ impl ThreadMetadataSync { } else { None }; - let dynamic_tools = - (!params.dynamic_tools.is_empty()).then(|| params.dynamic_tools.clone()); let update = ThreadMetadataPatch { model_provider: Some(params.metadata.model_provider.clone()), created_at: Some(created_at), @@ -76,7 +74,6 @@ impl ThreadMetadataSync { cli_version: Some(env!("CARGO_PKG_VERSION").to_string()), git_info: git_info.map(git_info_patch_from_observation), memory_mode: Some(params.metadata.memory_mode), - dynamic_tools, ..Default::default() }; Self { @@ -228,9 +225,6 @@ impl ThreadMetadataSync { { update.memory_mode = Some(memory_mode); } - if let Some(dynamic_tools) = meta_line.meta.dynamic_tools.clone() { - update.dynamic_tools = Some(dynamic_tools); - } } RolloutItem::TurnContext(turn_ctx) => { if !self.cwd_seen && !turn_ctx.cwd.as_os_str().is_empty() { @@ -365,7 +359,6 @@ fn update_has_metadata_facts(update: &ThreadMetadataPatch) -> bool { || update.first_user_message.is_some() || update.git_info.is_some() || update.memory_mode.is_some() - || update.dynamic_tools.is_some() } fn git_info_patch_from_observation(git_info: GitInfo) -> GitInfoPatch { @@ -542,6 +535,7 @@ mod tests { fn user_message(message: &str) -> UserMessageEvent { UserMessageEvent { + client_id: None, message: message.to_string(), images: None, local_images: Vec::new(), diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index ca75ca1b69..1e26e5dc77 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -529,8 +529,6 @@ pub struct ThreadMetadataPatch { pub git_info: Option, /// Thread memory behavior. pub memory_mode: Option, - /// Dynamic tools available to this thread. - pub dynamic_tools: Option>, } impl ThreadMetadataPatch { @@ -608,9 +606,6 @@ impl ThreadMetadataPatch { if next.memory_mode.is_some() { self.memory_mode = next.memory_mode; } - if next.dynamic_tools.is_some() { - self.dynamic_tools = next.dynamic_tools; - } } pub fn is_empty(&self) -> bool { @@ -636,7 +631,6 @@ impl ThreadMetadataPatch { && self.first_user_message.is_none() && self.git_info.is_none() && self.memory_mode.is_none() - && self.dynamic_tools.is_none() } } diff --git a/codex-rs/tools/src/lib.rs b/codex-rs/tools/src/lib.rs index 4c0fb44a7c..e09526048d 100644 --- a/codex-rs/tools/src/lib.rs +++ b/codex-rs/tools/src/lib.rs @@ -62,7 +62,12 @@ pub use responses_api::mcp_tool_to_deferred_responses_api_tool; pub use responses_api::mcp_tool_to_responses_api_tool; pub use responses_api::tool_definition_to_responses_api_tool; pub use tool_call::ConversationHistory; +pub use tool_call::ExtensionTurnItem; +pub use tool_call::ImageGenerationCompletionFuture; +pub use tool_call::NoopTurnItemEmitter; pub use tool_call::ToolCall; +pub use tool_call::TurnItemEmissionFuture; +pub use tool_call::TurnItemEmitter; pub use tool_config::ShellCommandBackendConfig; pub use tool_config::ToolEnvironmentMode; pub use tool_config::ToolUserShellType; diff --git a/codex-rs/tools/src/tool_call.rs b/codex-rs/tools/src/tool_call.rs index 32d428648f..9bbe00a6c4 100644 --- a/codex-rs/tools/src/tool_call.rs +++ b/codex-rs/tools/src/tool_call.rs @@ -1,8 +1,11 @@ use crate::FunctionCallError; use crate::ToolName; use crate::ToolPayload; +use codex_protocol::items::WebSearchItem; use codex_protocol::models::ResponseItem; use codex_utils_output_truncation::TruncationPolicy; +use std::future::Future; +use std::pin::Pin; use std::sync::Arc; /// Raw response history snapshot available when an extension tool is invoked. @@ -23,17 +26,87 @@ impl ConversationHistory { } } +/// Future returned when an extension tool emits a visible turn-item lifecycle event. +pub type TurnItemEmissionFuture<'a> = Pin + Send + 'a>>; + +/// Future returned when an image-generation extension publishes completed image bytes. +pub type ImageGenerationCompletionFuture<'a> = + Pin> + Send + 'a>>; + +/// Visible turn items that an extension fully owns and may emit as-is. +/// +/// Add only item kinds that require no additional host finalization before +/// persistence or client delivery. Richer items need a host-owned publish path. +#[derive(Clone, Debug, PartialEq)] +pub enum ExtensionTurnItem { + WebSearch(WebSearchItem), +} + +/// Host-provided capability for extension tools to emit finalized visible turn items. +/// +/// Implementations route lifecycle events through the host's normal item event +/// pipeline, including any persistence and client delivery owned by the host. +pub trait TurnItemEmitter: Send + Sync { + /// Emits the beginning of one visible turn item. + fn emit_started<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a>; + + /// Emits the completion of one visible turn item. + fn emit_completed<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a>; + + /// Publishes image bytes for host persistence and visible completion. + /// + /// Returns persisted-artifact context for the extension's model-facing + /// function output when the host saves the generated image successfully. + fn image_generation_completed<'a>( + &'a self, + _call_id: String, + _prompt: String, + _result: String, + ) -> ImageGenerationCompletionFuture<'a> { + Box::pin(std::future::ready(None)) + } +} + +/// Turn-item emitter used when a caller does not expose visible item emission. +#[derive(Debug, Default, Clone, Copy)] +pub struct NoopTurnItemEmitter; + +impl TurnItemEmitter for NoopTurnItemEmitter { + fn emit_started<'a>(&'a self, _item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> { + Box::pin(std::future::ready(())) + } + + fn emit_completed<'a>(&'a self, _item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> { + Box::pin(std::future::ready(())) + } +} + // TODO: this is temporary and will disappear in the next PR (as we make codex-extension-api generic on Invocation. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct ToolCall { pub turn_id: String, pub call_id: String, pub tool_name: ToolName, pub truncation_policy: TruncationPolicy, pub conversation_history: ConversationHistory, + pub turn_item_emitter: Arc, pub payload: ToolPayload, } +impl std::fmt::Debug for ToolCall { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ToolCall") + .field("turn_id", &self.turn_id) + .field("call_id", &self.call_id) + .field("tool_name", &self.tool_name) + .field("truncation_policy", &self.truncation_policy) + .field("conversation_history", &self.conversation_history) + .field("turn_item_emitter", &"") + .field("payload", &self.payload) + .finish() + } +} + impl ToolCall { pub fn function_arguments(&self) -> Result<&str, FunctionCallError> { match &self.payload { diff --git a/codex-rs/tools/src/tool_config_tests.rs b/codex-rs/tools/src/tool_config_tests.rs index 033bf07b10..2e49c15584 100644 --- a/codex-rs/tools/src/tool_config_tests.rs +++ b/codex-rs/tools/src/tool_config_tests.rs @@ -44,6 +44,7 @@ fn model_with_shell_type(shell_type: ConfigShellToolType) -> ModelInfo { input_modalities: codex_protocol::openai_models::default_input_modalities(), used_fallback_model_metadata: false, supports_search_tool: false, + tool_mode: None, } } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 24eb68b248..ff652b802e 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1047,11 +1047,13 @@ See the Codex keymap documentation for supported actions and examples." .unwrap_or(false); if should_check { let cwd = app.config.cwd.clone(); + let workspace_roots = app.config.effective_workspace_roots(); let env_map: std::collections::HashMap = std::env::vars().collect(); let tx = app.app_event_tx.clone(); let logs_base_dir = app.config.codex_home.clone(); Self::spawn_world_writable_scan( cwd, + workspace_roots, env_map, logs_base_dir, startup_permission_profile, diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index b3e1edb901..d90f511d6f 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -1061,6 +1061,7 @@ mod tests { let statuses = vec![ McpServerStatus { name: "docs".to_string(), + server_info: None, tools: HashMap::from([( "list".to_string(), Tool { @@ -1080,6 +1081,7 @@ mod tests { }, McpServerStatus { name: "disabled".to_string(), + server_info: None, tools: HashMap::new(), resources: Vec::new(), resource_templates: Vec::new(), diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index e83662c2a2..92ed5d470c 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -8,6 +8,12 @@ use super::*; #[cfg(target_os = "windows")] use codex_utils_approval_presets::ApprovalPreset; +#[cfg(target_os = "windows")] +pub(super) struct WindowsSetupPermissions { + pub(super) permission_profile: PermissionProfile, + pub(super) workspace_roots: Vec, +} + impl App { pub(super) async fn rebuild_config_for_cwd(&self, cwd: PathBuf) -> Result { let mut overrides = self.harness_overrides.clone(); @@ -45,19 +51,25 @@ impl App { } #[cfg(target_os = "windows")] - pub(super) async fn permission_profile_for_windows_setup( + pub(super) async fn windows_setup_permissions( &self, preset: &ApprovalPreset, profile_selection: Option<&PermissionProfileSelection>, - ) -> Result { + ) -> Result { match profile_selection { - Some(selection) => Ok(self - .rebuild_config_for_permission_profile(selection.profile_id.as_str()) - .await? - .permissions - .permission_profile() - .clone()), - None => Ok(preset.permission_profile.clone()), + Some(selection) => { + let selected_config = self + .rebuild_config_for_permission_profile(selection.profile_id.as_str()) + .await?; + Ok(WindowsSetupPermissions { + permission_profile: selected_config.permissions.permission_profile().clone(), + workspace_roots: selected_config.effective_workspace_roots(), + }) + } + None => Ok(WindowsSetupPermissions { + permission_profile: preset.permission_profile.clone(), + workspace_roots: self.config.effective_workspace_roots(), + }), } } @@ -386,7 +398,7 @@ impl App { serde_json::json!(auto_review_preset.approvals_reviewer.to_string()), )); if previous_approvals_reviewer != auto_review_preset.approvals_reviewer { - permissions_history_label = Some("Auto-review"); + permissions_history_label = Some("Approve for me"); } } else if !effective_enabled { feature_edits.push(crate::config_update::clear_config_value( @@ -394,7 +406,7 @@ impl App { )); feature_config.approvals_reviewer = ApprovalsReviewer::User; if previous_approvals_reviewer != ApprovalsReviewer::User { - permissions_history_label = Some("Default"); + permissions_history_label = Some("Ask for approval"); } } approvals_reviewer_override = Some(feature_config.approvals_reviewer); @@ -407,7 +419,7 @@ impl App { if !self.try_set_approval_policy_on_config( &mut feature_config, auto_review_preset.approval_policy, - "Failed to enable Auto-review", + "Failed to enable Approve for me", "failed to set auto-review approval policy on staged config", ) { continue; @@ -416,7 +428,7 @@ impl App { .try_set_builtin_active_permission_profile_on_config( &mut feature_config, auto_review_preset.active_permission_profile.clone(), - "Failed to enable Auto-review", + "Failed to enable Approve for me", "failed to set auto-review permission profile on staged config", ) else { @@ -534,7 +546,7 @@ impl App { "failed to set auto-review permission profile on chat config" ); self.chat_widget - .add_error_message(format!("Failed to enable Auto-review: {err}")); + .add_error_message(format!("Failed to enable Approve for me: {err}")); } if permission_profile_override.is_some() { self.runtime_permission_profile_override = @@ -806,7 +818,7 @@ impl App { "failed to sync effective approval policy after an overridden write" ); self.chat_widget.add_error_message(format!( - "Failed to refresh overridden Auto-review settings: {err}" + "Failed to refresh overridden Approve for me settings: {err}" )); } else { self.chat_widget.set_approval_policy(policy); @@ -834,7 +846,7 @@ impl App { let Some(permission_profile) = self.try_set_builtin_active_permission_profile_on_config( &mut config, auto_review_preset.active_permission_profile.clone(), - "Failed to refresh overridden Auto-review settings", + "Failed to refresh overridden Approve for me settings", "failed to sync overridden Auto-review permission profile", ) else { return; @@ -852,7 +864,7 @@ impl App { "failed to sync overridden Auto-review permission profile on chat config" ); self.chat_widget.add_error_message(format!( - "Failed to refresh overridden Auto-review settings: {err}" + "Failed to refresh overridden Approve for me settings: {err}" )); return; } diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 5af2c49233..f9683e26ea 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -121,6 +121,9 @@ impl App { } } } + AppEvent::ArchiveCurrentThread => { + return Ok(self.archive_current_thread(app_server).await); + } AppEvent::ForkCurrentSession => { self.session_telemetry.counter( "codex.thread.fork", @@ -866,11 +869,11 @@ impl App { } => { #[cfg(target_os = "windows")] { - let permission_profile = match self - .permission_profile_for_windows_setup(&preset, profile_selection.as_ref()) + let setup_permissions = match self + .windows_setup_permissions(&preset, profile_selection.as_ref()) .await { - Ok(permission_profile) => permission_profile, + Ok(setup_permissions) => setup_permissions, Err(err) => { tracing::warn!( error = %err, @@ -882,8 +885,9 @@ impl App { return Ok(AppRunControl::Continue); } }; - let permission_profile_cwd = self.config.cwd.clone(); - let command_cwd = permission_profile_cwd.clone(); + let permission_profile = setup_permissions.permission_profile; + let workspace_roots = setup_permissions.workspace_roots; + let command_cwd = self.config.cwd.clone(); let env_map: std::collections::HashMap = std::env::vars().collect(); let codex_home = self.config.codex_home.clone(); @@ -908,7 +912,7 @@ impl App { tokio::task::spawn_blocking(move || { let result = crate::legacy_core::windows_sandbox::run_elevated_setup( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &env_map, codex_home.as_path(), @@ -975,11 +979,11 @@ impl App { } => { #[cfg(target_os = "windows")] { - let permission_profile = match self - .permission_profile_for_windows_setup(&preset, profile_selection.as_ref()) + let setup_permissions = match self + .windows_setup_permissions(&preset, profile_selection.as_ref()) .await { - Ok(permission_profile) => permission_profile, + Ok(setup_permissions) => setup_permissions, Err(err) => { tracing::warn!( error = %err, @@ -991,8 +995,9 @@ impl App { return Ok(AppRunControl::Continue); } }; - let permission_profile_cwd = self.config.cwd.clone(); - let command_cwd = permission_profile_cwd.clone(); + let permission_profile = setup_permissions.permission_profile; + let workspace_roots = setup_permissions.workspace_roots; + let command_cwd = self.config.cwd.clone(); let env_map: std::collections::HashMap = std::env::vars().collect(); let codex_home = self.config.codex_home.clone(); @@ -1004,7 +1009,7 @@ impl App { if let Err(err) = crate::legacy_core::windows_sandbox::run_legacy_setup_preflight( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &env_map, codex_home.as_path(), @@ -1042,7 +1047,7 @@ impl App { )); let permission_profile = self.config.permissions.effective_permission_profile(); - let permission_profile_cwd = self.config.cwd.clone(); + let workspace_roots = self.config.effective_workspace_roots(); let command_cwd = self.config.cwd.clone(); let env_map: std::collections::HashMap = std::env::vars().collect(); @@ -1053,7 +1058,7 @@ impl App { let requested_path = PathBuf::from(path); let event = match crate::legacy_core::grant_read_root_non_elevated( &permission_profile, - permission_profile_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &env_map, codex_home.as_path(), @@ -1474,6 +1479,7 @@ impl App { && !self.chat_widget.world_writable_warning_hidden(); if should_check { let cwd = self.config.cwd.clone(); + let workspace_roots = self.config.effective_workspace_roots(); let env_map: std::collections::HashMap = std::env::vars().collect(); let tx = self.app_event_tx.clone(); @@ -1482,6 +1488,7 @@ impl App { self.config.permissions.effective_permission_profile(); Self::spawn_world_writable_scan( cwd, + workspace_roots, env_map, logs_base_dir, permission_profile, @@ -2142,4 +2149,31 @@ impl App { } } } + + pub(super) async fn archive_current_thread( + &mut self, + app_server: &mut AppServerSession, + ) -> AppRunControl { + let Some(thread_id) = self.active_thread_id.or(self.chat_widget.thread_id()) else { + self.chat_widget + .add_error_message("A thread must start before it can be archived.".to_string()); + return AppRunControl::Continue; + }; + if self.side_threads.contains_key(&thread_id) { + self.chat_widget.add_error_message( + "'/archive' is unavailable in side conversations. Press Ctrl+C to return to the main thread first." + .to_string(), + ); + return AppRunControl::Continue; + } + + match app_server.thread_archive(thread_id).await { + Ok(()) => AppRunControl::Exit(ExitReason::UserRequested), + Err(err) => { + self.chat_widget + .add_error_message(format!("Failed to archive current thread: {err}")); + AppRunControl::Continue + } + } + } } diff --git a/codex-rs/tui/src/app/platform_actions.rs b/codex-rs/tui/src/app/platform_actions.rs index d11e410884..f4a708a026 100644 --- a/codex-rs/tui/src/app/platform_actions.rs +++ b/codex-rs/tui/src/app/platform_actions.rs @@ -16,15 +16,16 @@ impl App { #[cfg(target_os = "windows")] pub(super) fn spawn_world_writable_scan( cwd: AbsolutePathBuf, + workspace_roots: Vec, env_map: std::collections::HashMap, logs_base_dir: AbsolutePathBuf, permission_profile: PermissionProfile, tx: AppEventSender, ) { let Ok(permissions) = - codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( &permission_profile, - cwd.as_path(), + workspace_roots.as_slice(), ) else { return; diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 812e20af7a..0fd7e76c23 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -147,6 +147,7 @@ async fn handle_mcp_inventory_result_respects_origin_thread() { app.handle_mcp_inventory_result( Ok(vec![McpServerStatus { name: "docs".to_string(), + server_info: None, tools: HashMap::new(), resources: Vec::new(), resource_templates: Vec::new(), @@ -338,6 +339,7 @@ async fn enqueue_primary_thread_session_replays_turns_before_initial_prompt_subm TurnStatus::Completed, vec![ThreadItem::UserMessage { id: "user-1".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "earlier prompt".to_string(), text_elements: Vec::new(), @@ -1818,7 +1820,7 @@ async fn update_feature_flags_enabling_guardian_selects_auto_review() -> Result< .map(|line| line.to_string()) .collect::>() .join("\n"); - assert!(rendered.contains("Permissions updated to Auto-review")); + assert!(rendered.contains("Permissions updated to Approve for me")); let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; assert!(config.contains("guardian_approval = true")); @@ -1913,7 +1915,7 @@ async fn update_feature_flags_disabling_guardian_clears_review_policy_and_restor .map(|line| line.to_string()) .collect::>() .join("\n"); - assert!(rendered.contains("Permissions updated to Default")); + assert!(rendered.contains("Permissions updated to Ask for approval")); let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; assert!(!config.contains("guardian_approval = true")); @@ -3319,6 +3321,7 @@ async fn side_thread_snapshot_hides_forked_parent_transcript() { TurnStatus::Completed, vec![ThreadItem::UserMessage { id: "parent-user".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "parent prompt should stay hidden".to_string(), text_elements: Vec::new(), @@ -4747,6 +4750,7 @@ async fn replay_thread_snapshot_replays_turn_history_in_order() { items_view: codex_app_server_protocol::TurnItemsView::Full, items: vec![ThreadItem::UserMessage { id: "user-1".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "first prompt".to_string(), text_elements: Vec::new(), @@ -4764,6 +4768,7 @@ async fn replay_thread_snapshot_replays_turn_history_in_order() { items: vec![ ThreadItem::UserMessage { id: "user-2".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "third prompt".to_string(), text_elements: Vec::new(), @@ -4911,6 +4916,7 @@ async fn refreshed_snapshot_session_persists_resumed_turns() { TurnStatus::Completed, vec![ThreadItem::UserMessage { id: "user-1".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "restored prompt".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index b37aee64e6..f1e612dd58 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -209,6 +209,9 @@ pub(crate) enum AppEvent { /// Resume a thread by UUID or thread name inside the running TUI session. ResumeSessionByIdOrName(String), + /// Archive the current active main thread and exit after it succeeds. + ArchiveCurrentThread, + /// Fork the current session into a new thread. ForkCurrentSession, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index aa2d5a645b..e66b5ee8a2 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -46,6 +46,8 @@ use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::Thread; use codex_app_server_protocol::ThreadApproveGuardianDeniedActionParams; use codex_app_server_protocol::ThreadApproveGuardianDeniedActionResponse; +use codex_app_server_protocol::ThreadArchiveParams; +use codex_app_server_protocol::ThreadArchiveResponse; use codex_app_server_protocol::ThreadBackgroundTerminalsCleanParams; use codex_app_server_protocol::ThreadBackgroundTerminalsCleanResponse; use codex_app_server_protocol::ThreadCompactStartParams; @@ -564,6 +566,21 @@ impl AppServerSession { Ok(response.thread) } + pub(crate) async fn thread_archive(&mut self, thread_id: ThreadId) -> Result<()> { + let request_id = self.next_request_id(); + let _: ThreadArchiveResponse = self + .client + .request_typed(ClientRequest::ThreadArchive { + request_id, + params: ThreadArchiveParams { + thread_id: thread_id.to_string(), + }, + }) + .await + .wrap_err("thread/archive failed in TUI")?; + Ok(()) + } + pub(crate) async fn thread_metadata_update_branch( &mut self, thread_id: ThreadId, @@ -668,6 +685,7 @@ impl AppServerSession { request_id, params: TurnStartParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: items, responsesapi_client_metadata: None, additional_context: None, @@ -732,6 +750,7 @@ impl AppServerSession { request_id, params: TurnSteerParams { thread_id: thread_id.to_string(), + client_user_message_id: None, input: items, responsesapi_client_metadata: None, additional_context: None, @@ -2264,6 +2283,7 @@ mod tests { items: vec![ codex_app_server_protocol::ThreadItem::UserMessage { id: "user-1".to_string(), + client_id: None, content: vec![codex_app_server_protocol::UserInput::Text { text: "hello from history".to_string(), text_elements: Vec::new(), @@ -2300,6 +2320,7 @@ mod tests { .into(), active_permission_profile: None, reasoning_effort: None, + initial_turns_page: None, }; let started = started_thread_from_resume_response( diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index e62cab9e86..ec3284866d 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -256,7 +256,6 @@ use std::path::PathBuf; use std::time::Duration; use std::time::Instant; -#[cfg(test)] use ratatui::style::Color; /// If the pasted content exceeds this number of characters, replace it with a @@ -590,6 +589,7 @@ impl ChatComposer { pub fn set_mentions_v2_enabled(&mut self, enabled: bool) { self.mentions_v2_enabled = enabled; + self.history.set_at_mention_restore_enabled(enabled); self.sync_popups(); } @@ -609,11 +609,13 @@ impl ChatComposer { pub(crate) fn take_mention_bindings(&mut self) -> Vec { let elements = self.current_mention_elements(); let mut ordered = Vec::new(); - for (id, mention) in elements { + for (id, sigil, mention) in elements { if let Some(binding) = self.draft.mention_bindings.remove(&id) + && binding.sigil == sigil && binding.mention == mention { ordered.push(MentionBinding { + sigil: binding.sigil, mention: binding.mention, path: binding.path, }); @@ -856,6 +858,10 @@ impl ChatComposer { } } + pub(crate) fn record_replayed_user_message_history(&mut self, entry: HistoryEntry) { + self.history.record_replayed_submission(entry); + } + /// Integrate pasted text into the composer. /// /// Acts as the only place where paste text is integrated, both for: @@ -1195,7 +1201,7 @@ impl ChatComposer { /// /// This is the "fresh draft" path: it clears pending paste payloads and /// mention link targets. Callers restoring a previously submitted draft - /// that must keep `$name -> path` resolution should use + /// that must keep sigiled mention target resolution should use /// [`Self::set_text_content_with_mention_bindings`] instead. pub(crate) fn set_text_content( &mut self, @@ -1649,7 +1655,7 @@ impl ChatComposer { result } - /// Return true if either the slash-command popup or the file-search popup is active. + /// Return true if any popup or history search is active. pub(crate) fn popup_active(&self) -> bool { self.history_search.is_some() || self.popups.active() } @@ -1802,7 +1808,6 @@ impl ChatComposer { KeyEvent { code: KeyCode::Esc, .. } => { - // Hide popup without modifying text, remember token to avoid immediate reopen. if let Some(tok) = Self::current_at_token(&self.draft.textarea) { self.popups.dismissed_file_token = Some(tok); } @@ -1827,24 +1832,17 @@ impl ChatComposer { }; let sel_path = sel.to_string_lossy().to_string(); - // If selected path looks like an image (png/jpeg), attach as image instead of inserting text. - let is_image = Self::is_image_path(&sel_path); - if is_image { - // Determine dimensions; if that fails fall back to normal path insertion. + if Self::is_image_path(&sel_path) { let path_buf = PathBuf::from(&sel_path); match image::image_dimensions(&path_buf) { Ok((width, height)) => { tracing::debug!("selected image dimensions={}x{}", width, height); - // Remove the current @token (mirror logic from insert_selected_path without inserting text) - // using the flat text and byte-offset cursor API. let cursor_offset = self.draft.textarea.cursor(); let text = self.draft.textarea.text(); - // Clamp to a valid char boundary to avoid panics when slicing. let safe_cursor = Self::clamp_to_char_boundary(text, cursor_offset); let before_cursor = &text[..safe_cursor]; let after_cursor = &text[safe_cursor..]; - // Determine token boundaries in the full text. let start_idx = before_cursor .char_indices() .rfind(|(_, c)| c.is_whitespace()) @@ -1861,17 +1859,14 @@ impl ChatComposer { self.draft.textarea.set_cursor(start_idx); self.attach_image(path_buf); - // Add a trailing space to keep typing fluid. self.draft.textarea.insert_str(" "); } Err(err) => { tracing::trace!("image dimensions lookup failed: {err}"); - // Fallback to plain path insertion if metadata read fails. self.insert_selected_path(&sel_path); } } } else { - // Non-image: inserting file path. self.insert_selected_path(&sel_path); } self.popups.active = ActivePopup::None; @@ -1881,6 +1876,7 @@ impl ChatComposer { } } + /// Handle key events when the legacy skill mention popup is visible. fn handle_key_event_with_skill_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) { if self.handle_shortcut_overlay_key(&key_event) { return (InputResult::None, true); @@ -1962,6 +1958,7 @@ impl ChatComposer { return (InputResult::None, true); } self.footer.mode = reset_mode_after_activity(self.footer.mode); + let can_switch_search_mode = self.current_editable_at_token().is_some(); let ActivePopup::MentionV2(popup) = &mut self.popups.active else { unreachable!(); @@ -1969,6 +1966,7 @@ impl ChatComposer { let mut selected: Option = None; let mut close_popup = false; + let mut submit_without_popup = false; let result = match key_event { KeyEvent { @@ -1999,16 +1997,24 @@ impl ChatComposer { modifiers: KeyModifiers::NONE, .. } => { - popup.previous_search_mode(); - (InputResult::None, true) + if can_switch_search_mode { + popup.previous_search_mode(); + (InputResult::None, true) + } else { + self.handle_input_basic(key_event) + } } KeyEvent { code: KeyCode::Right, modifiers: KeyModifiers::NONE, .. } => { - popup.next_search_mode(); - (InputResult::None, true) + if can_switch_search_mode { + popup.next_search_mode(); + (InputResult::None, true) + } else { + self.handle_input_basic(key_event) + } } KeyEvent { code: KeyCode::Esc, .. @@ -2021,14 +2027,19 @@ impl ChatComposer { } KeyEvent { code: KeyCode::Tab, .. + } => { + selected = popup.selected(); + close_popup = true; + (InputResult::None, true) } - | KeyEvent { + KeyEvent { code: KeyCode::Enter, modifiers: KeyModifiers::NONE, .. } => { selected = popup.selected(); close_popup = true; + submit_without_popup = selected.is_none(); (InputResult::None, true) } input => self.handle_input_basic(input), @@ -2046,6 +2057,9 @@ impl ChatComposer { } } self.popups.active = ActivePopup::None; + if submit_without_popup { + return self.handle_key_event_without_popup(key_event); + } } result @@ -2241,14 +2255,14 @@ impl ChatComposer { /// second `@` in `@scope/pkg@latest`), keep treating the surrounding /// whitespace-delimited token as the active token rather than starting a /// new token at that nested prefix. - /// - If the token under the cursor starts with `prefix`, that token is - /// returned without the leading prefix. When `allow_empty` is true, a - /// lone prefix character yields `Some(String::new())` to surface hints. - fn current_prefixed_token( + /// - If the token under the cursor starts with `prefix`, its byte range and + /// text without the leading prefix are returned. When `allow_empty` is + /// true, a lone prefix character yields `Some(String::new())` to surface hints. + fn current_prefixed_token_range( textarea: &TextArea, prefix: char, allow_empty: bool, - ) -> Option { + ) -> Option<(Range, String)> { let cursor_offset = textarea.cursor(); let text = textarea.text(); @@ -2321,15 +2335,17 @@ impl ChatComposer { let left_match = token_left.filter(|t| t.starts_with(prefix)); let right_match = token_right.filter(|t| t.starts_with(prefix)); - let left_prefixed = left_match.map(|t| t[prefix.len_utf8()..].to_string()); - let right_prefixed = right_match.map(|t| t[prefix.len_utf8()..].to_string()); + let left_prefixed = + left_match.map(|t| (start_left..end_left, t[prefix.len_utf8()..].to_string())); + let right_prefixed = + right_match.map(|t| (start_right..end_right, t[prefix.len_utf8()..].to_string())); if at_whitespace { if right_prefixed.is_some() { return right_prefixed; } if token_left.is_some_and(|t| t == prefix_str) { - return allow_empty.then(String::new); + return allow_empty.then(|| (start_left..end_left, String::new())); } return left_prefixed; } @@ -2347,6 +2363,14 @@ impl ChatComposer { left_prefixed.or(right_prefixed) } + fn current_prefixed_token( + textarea: &TextArea, + prefix: char, + allow_empty: bool, + ) -> Option { + Self::current_prefixed_token_range(textarea, prefix, allow_empty).map(|(_, token)| token) + } + /// Extract the `@token` that the cursor is currently positioned on, if any. /// /// The returned string **does not** include the leading `@`. @@ -2354,11 +2378,48 @@ impl ChatComposer { Self::current_prefixed_token(textarea, '@', /*allow_empty*/ false) } + fn current_editable_at_token_with_options(&self, allow_empty: bool) -> Option { + let (range, token) = + Self::current_prefixed_token_range(&self.draft.textarea, '@', allow_empty)?; + if self + .draft + .textarea + .element_id_for_exact_range(range.clone()) + .is_some() + { + return None; + } + + let name_len = token + .as_bytes() + .iter() + .take_while(|byte| is_mention_name_char(**byte)) + .count(); + let mention_end = range.start + '@'.len_utf8() + name_len; + if name_len > 0 + && mention_end < range.end + && ends_plaintext_at_mention(self.draft.textarea.text().as_bytes(), mention_end) + && self + .draft + .textarea + .element_id_for_exact_range(range.start..mention_end) + .is_some() + { + return None; + } + + Some(token) + } + + fn current_editable_at_token(&self) -> Option { + self.current_editable_at_token_with_options(/*allow_empty*/ false) + } + fn current_mentions_v2_token(&self) -> Option { if !self.mentions_v2_enabled { return None; } - Self::current_prefixed_token(&self.draft.textarea, '@', /*allow_empty*/ true) + self.current_editable_at_token_with_options(/*allow_empty*/ true) } fn current_mention_token(&self) -> Option { @@ -2441,12 +2502,13 @@ impl ChatComposer { self.draft.textarea.set_cursor(start_idx); let id = self.draft.textarea.insert_element(insert_text); - if let (Some(path), Some(mention)) = - (path, Self::mention_name_from_insert_text(insert_text)) + if let (Some(path), Some((sigil, mention))) = + (path, Self::mention_token_from_insert_text(insert_text)) { self.draft.mention_bindings.insert( id, ComposerMentionBinding { + sigil, mention, path: path.to_string(), }, @@ -2460,8 +2522,12 @@ impl ChatComposer { self.draft.textarea.set_cursor(new_cursor); } - fn mention_name_from_insert_text(insert_text: &str) -> Option { - let name = insert_text.strip_prefix('$')?; + fn mention_token_from_insert_text(insert_text: &str) -> Option<(char, String)> { + let sigil = insert_text.chars().next()?; + if !matches!(sigil, '$' | '@') { + return None; + } + let name = &insert_text[sigil.len_utf8()..]; if name.is_empty() { return None; } @@ -2470,31 +2536,33 @@ impl ChatComposer { .iter() .all(|byte| is_mention_name_char(*byte)) { - Some(name.to_string()) + Some((sigil, name.to_string())) } else { None } } - fn current_mention_elements(&self) -> Vec<(u64, String)> { + fn current_mention_elements(&self) -> Vec<(u64, char, String)> { self.draft .textarea .text_element_snapshots() .into_iter() .filter_map(|snapshot| { - Self::mention_name_from_insert_text(snapshot.text.as_str()) - .map(|mention| (snapshot.id, mention)) + Self::mention_token_from_insert_text(snapshot.text.as_str()) + .map(|(sigil, mention)| (snapshot.id, sigil, mention)) }) .collect() } fn snapshot_mention_bindings(&self) -> Vec { let mut ordered = Vec::new(); - for (id, mention) in self.current_mention_elements() { + for (id, sigil, mention) in self.current_mention_elements() { if let Some(binding) = self.draft.mention_bindings.get(&id) + && binding.sigil == sigil && binding.mention == mention { ordered.push(MentionBinding { + sigil: binding.sigil, mention: binding.mention.clone(), path: binding.path.clone(), }); @@ -2512,7 +2580,7 @@ impl ChatComposer { let text = self.draft.textarea.text().to_string(); let mut scan_from = 0usize; for binding in mention_bindings { - let token = format!("${}", binding.mention); + let token = format!("{}{}", binding.sigil, binding.mention); let Some(range) = find_next_mention_token_range(text.as_str(), token.as_str(), scan_from) else { @@ -2531,6 +2599,7 @@ impl ChatComposer { self.draft.mention_bindings.insert( id, ComposerMentionBinding { + sigil: binding.sigil, mention: binding.mention, path: binding.path, }, @@ -2540,6 +2609,21 @@ impl ChatComposer { } } + fn plugin_at_mention_highlights(&self) -> Vec<(Range, Style)> { + self.draft + .textarea + .text_element_snapshots() + .into_iter() + .filter_map(|snapshot| { + let binding = self.draft.mention_bindings.get(&snapshot.id)?; + if !binding.path.starts_with("plugin://") || !snapshot.text.starts_with('@') { + return None; + } + Some((snapshot.range, Style::default().fg(Color::Magenta))) + }) + .collect() + } + /// Prepare text for submission/queuing. Returns None if submission should be suppressed. /// On success, clears pending paste payloads because placeholders have been expanded. /// @@ -3411,7 +3495,7 @@ impl ChatComposer { let file_token = if self.mentions_v2_enabled { None } else { - Self::current_at_token(&self.draft.textarea) + self.current_editable_at_token() }; let browsing_history = self .history @@ -3537,10 +3621,8 @@ impl ChatComposer { } } - /// Synchronize `self.file_search_popup` with the current text in the textarea. - /// Note this is only called when the active popup is NOT Command. + /// Synchronize the legacy file-search popup with the current `@` token. fn sync_file_search_popup(&mut self, query: String) { - // If user dismissed popup for this exact query, don't reopen until text changes. if self.popups.dismissed_file_token.as_ref() == Some(&query) { return; } @@ -3901,16 +3983,46 @@ fn is_mention_name_char(byte: u8) -> bool { matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') } +fn ends_plaintext_at_mention(bytes: &[u8], index: usize) -> bool { + bytes.get(index).is_none_or(|byte| { + byte.is_ascii_whitespace() + || *byte == b'.' + && bytes.get(index + 1).is_none_or(|next| { + next.is_ascii_whitespace() + || !next.is_ascii_alphanumeric() && *next != b'_' && *next != b'-' + }) + || !matches!(*byte, b'.' | b'/' | b'\\') + && !byte.is_ascii_alphanumeric() + && *byte != b'_' + && *byte != b'-' + }) +} + +fn starts_plaintext_at_mention(text: &str, index: usize) -> bool { + if index == 0 { + return true; + } + + text.get(..index) + .and_then(|prefix| prefix.chars().next_back()) + .is_some_and(|ch| ch.is_whitespace() || !is_mention_name_char_char(ch)) +} + +fn is_mention_name_char_char(ch: char) -> bool { + ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') +} + fn find_next_mention_token_range(text: &str, token: &str, from: usize) -> Option> { if token.is_empty() || from >= text.len() { return None; } let bytes = text.as_bytes(); let token_bytes = token.as_bytes(); + let sigil = *token_bytes.first()?; let mut index = from; while index < bytes.len() { - if bytes[index] != b'$' { + if bytes[index] != sigil { index += 1; continue; } @@ -3924,10 +4036,24 @@ fn find_next_mention_token_range(text: &str, token: &str, from: usize) -> Option continue; } - if bytes - .get(end) - .is_none_or(|byte| !is_mention_name_char(*byte)) - { + // Fix for restored `@` mentions: rebinding must not attach to embedded substrings such + // as email addresses, while preserving the existing `$` mention matching behavior. + let starts_plaintext_mention = if sigil == b'@' { + starts_plaintext_at_mention(text, index) + } else { + true + }; + // Fix for restored `@` mentions: mirror history encoding's trailing boundary so path-like + // text such as `@sample/pkg` is not rebound as the plain `@sample` mention. + let ends_plaintext_mention = if sigil == b'@' { + ends_plaintext_at_mention(bytes, end) + } else { + bytes + .get(end) + .is_none_or(|byte| !is_mention_name_char(*byte)) + }; + + if starts_plaintext_mention && ends_plaintext_mention { return Some(index..end); } @@ -4286,8 +4412,15 @@ impl ChatComposer { .textarea .render_ref_masked(textarea_rect, buf, &mut state, mask_char); } else { - let highlight_ranges = self.history_search_highlight_ranges(); - if highlight_ranges.is_empty() { + let mut highlights = self.plugin_at_mention_highlights(); + let search_highlight_style = + Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD); + highlights.extend( + self.history_search_highlight_ranges() + .into_iter() + .map(|range| (range, search_highlight_style)), + ); + if highlights.is_empty() { StatefulWidgetRef::render_ref( &(&self.draft.textarea), textarea_rect, @@ -4295,12 +4428,6 @@ impl ChatComposer { &mut state, ); } else { - let highlight_style = - Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD); - let highlights = highlight_ranges - .into_iter() - .map(|range| (range, highlight_style)) - .collect::>(); self.draft.textarea.render_ref_styled_with_highlights( textarea_rect, buf, @@ -4736,6 +4863,142 @@ mod tests { ); } + fn plugin_mention_foreground_color(composer: &ChatComposer) -> Option { + let area = Rect::new(0, 0, 40, 5); + let mut buf = Buffer::empty(area); + composer.render(area, &mut buf); + + let textarea_row = 1; + let row_text = (0..area.width) + .map(|x| { + buf[(x, textarea_row)] + .symbol() + .chars() + .next() + .unwrap_or(' ') + }) + .collect::(); + let mention_x = row_text + .find("@sample") + .expect("expected plugin mention in composer row"); + buf[(mention_x as u16, textarea_row)].style().fg + } + + #[test] + fn plugin_at_mentions_use_plugin_accent_style() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ true, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + composer.set_text_content_with_mention_bindings( + "@sample plugin".to_string(), + Vec::new(), + Vec::new(), + vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + + assert_eq!( + plugin_mention_foreground_color(&composer), + Some(Color::Magenta) + ); + } + + #[test] + fn plugin_at_mentions_render_with_plugin_accent_snapshot() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ true, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + composer.set_text_content_with_mention_bindings( + "@sample plugin".to_string(), + Vec::new(), + Vec::new(), + vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + + let area = Rect::new(0, 0, 40, 5); + let mut buf = Buffer::empty(area); + composer.render(area, &mut buf); + + let textarea_row = 1; + let mut text = String::new(); + let mut magenta = String::new(); + for x in 0..area.width { + let cell = &buf[(x, textarea_row)]; + text.push(cell.symbol().chars().next().unwrap_or(' ')); + magenta.push(if cell.style().fg == Some(Color::Magenta) { + '^' + } else { + ' ' + }); + } + while text.ends_with(' ') { + text.pop(); + } + while magenta.ends_with(' ') { + magenta.pop(); + } + + insta::assert_snapshot!( + "plugin_at_mentions_render_with_plugin_accent", + format!("text: {text}\nmagenta: {magenta}") + ); + } + + #[test] + fn recalled_plugin_at_mentions_keep_plugin_accent_style() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ true, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + composer.set_text_content_with_mention_bindings( + "@sample plugin".to_string(), + Vec::new(), + Vec::new(), + vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + let (result, _) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(matches!(result, InputResult::Submitted { .. })); + + composer.set_text_content(String::new(), Vec::new(), Vec::new()); + let (_, needs_redraw) = + composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + assert!(needs_redraw); + + assert_eq!( + plugin_mention_foreground_color(&composer), + Some(Color::Magenta) + ); + } + #[test] fn status_line_hyperlink_marks_pr_number_cells() { let (tx, _rx) = unbounded_channel::(); @@ -6446,6 +6709,291 @@ mod tests { } } + #[test] + fn set_text_content_rebinds_at_sigiled_mentions() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + let mention_bindings = vec![MentionBinding { + sigil: '@', + mention: "figma".to_string(), + path: "/tmp/user/figma/SKILL.md".to_string(), + }]; + composer.set_text_content_with_mention_bindings( + "@figma please".to_string(), + Vec::new(), + Vec::new(), + mention_bindings.clone(), + ); + + assert_eq!(composer.mention_bindings(), mention_bindings); + } + + #[test] + fn set_text_content_rebinds_matching_sigil_only() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + let mention_bindings = vec![MentionBinding { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }]; + composer.set_text_content_with_mention_bindings( + "@figma then $figma".to_string(), + Vec::new(), + Vec::new(), + mention_bindings.clone(), + ); + + let bound_tokens = composer + .current_mention_elements() + .into_iter() + .map(|(_, sigil, mention)| (sigil, mention)) + .collect::>(); + assert_eq!(bound_tokens, vec![('$', "figma".to_string())]); + assert_eq!(composer.mention_bindings(), mention_bindings); + } + + #[test] + fn set_text_content_rebinds_both_sigil_forms() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + let mention_bindings = vec![ + MentionBinding { + sigil: '@', + mention: "figma".to_string(), + path: "plugin://figma@test".to_string(), + }, + MentionBinding { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }, + ]; + composer.set_text_content_with_mention_bindings( + "@figma then $figma".to_string(), + Vec::new(), + Vec::new(), + mention_bindings.clone(), + ); + + let bound_tokens = composer + .current_mention_elements() + .into_iter() + .map(|(_, sigil, mention)| (sigil, mention)) + .collect::>(); + assert_eq!( + bound_tokens, + vec![('@', "figma".to_string()), ('$', "figma".to_string())] + ); + assert_eq!(composer.mention_bindings(), mention_bindings); + } + + #[test] + fn set_text_content_rebinds_at_mentions_after_email_substrings() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + let text = "foo@sample.com then @sample".to_string(); + let mention_start = text.rfind("@sample").expect("expected bound mention token"); + let mention_range = mention_start..mention_start + "@sample".len(); + let mention_bindings = vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }]; + composer.set_text_content_with_mention_bindings( + text, + Vec::new(), + Vec::new(), + mention_bindings.clone(), + ); + + // Fix coverage: only the plaintext `@sample` should be atomic; the email substring stays editable. + assert_eq!( + composer + .draft + .textarea + .text_element_snapshots() + .into_iter() + .map(|snapshot| snapshot.range) + .collect::>(), + vec![mention_range] + ); + assert_eq!(composer.mention_bindings(), mention_bindings); + } + + #[test] + fn set_text_content_rebinds_at_mentions_after_punctuation() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + let text = "Please ask (@sample)".to_string(); + let mention_start = text.find("@sample").expect("expected bound mention token"); + let mention_range = mention_start..mention_start + "@sample".len(); + let mention_bindings = vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }]; + composer.set_text_content_with_mention_bindings( + text, + Vec::new(), + Vec::new(), + mention_bindings.clone(), + ); + + assert_eq!( + composer + .draft + .textarea + .text_element_snapshots() + .into_iter() + .map(|snapshot| snapshot.range) + .collect::>(), + vec![mention_range] + ); + assert_eq!(composer.mention_bindings(), mention_bindings); + } + + #[test] + fn bound_at_mentions_do_not_block_arrow_navigation() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + composer.set_text_content_with_mention_bindings( + "go @figma now".to_string(), + Vec::new(), + Vec::new(), + vec![MentionBinding { + sigil: '@', + mention: "figma".to_string(), + path: "plugin://figma@debug".to_string(), + }], + ); + composer.draft.textarea.set_cursor("go".len()); + + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(composer.draft.textarea.cursor(), "go".len() + 1); + assert!(matches!(composer.popups.active, ActivePopup::None)); + + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)); + assert_eq!(composer.draft.textarea.cursor(), "go @figma".len()); + assert!(matches!(composer.popups.active, ActivePopup::None)); + + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(composer.draft.textarea.cursor(), "go ".len()); + assert!(matches!(composer.popups.active, ActivePopup::None)); + + let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert_eq!(composer.draft.textarea.cursor(), "go".len()); + assert!(matches!(composer.popups.active, ActivePopup::None)); + } + + #[test] + fn restored_bound_at_mentions_do_not_open_mention_popup() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + for (text, move_cursor_to_end) in [ + ("@sample".to_string(), false), + ("Please ask @sample.".to_string(), true), + ] { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + composer.set_plugin_mentions(Some(vec![PluginCapabilitySummary { + config_name: "sample@test".to_string(), + display_name: "sample".to_string(), + description: None, + has_skills: true, + mcp_server_names: vec!["sample".to_string()], + app_connector_ids: Vec::new(), + }])); + + composer.set_text_content_with_mention_bindings( + text.clone(), + Vec::new(), + Vec::new(), + vec![MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + if move_cursor_to_end { + composer.move_cursor_to_end(); + } + + assert!(matches!(composer.popups.active, ActivePopup::None)); + + let (result, consumed) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(consumed); + match result { + InputResult::Submitted { + text: submitted, .. + } => assert_eq!(submitted, text), + _ => panic!("expected restored bound mention to submit"), + } + } + } + #[test] fn enter_submits_when_file_popup_has_no_selection() { use crossterm::event::KeyCode; @@ -6478,6 +7026,39 @@ mod tests { } } + #[test] + fn enter_submits_when_unified_mention_popup_has_no_selection() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + composer.set_mentions_v2_enabled(/*enabled*/ true); + + let input = "npx -y @kaeawc/auto-mobile@latest"; + composer.draft.textarea.insert_str(input); + composer.draft.textarea.set_cursor(input.len()); + composer.sync_popups(); + + assert!(matches!(composer.popups.active, ActivePopup::MentionV2(_))); + + let (result, consumed) = + composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(consumed); + match result { + InputResult::Submitted { text, .. } => assert_eq!(text, input), + _ => panic!("expected Submitted"), + } + } + /// Behavior: if the ASCII path has a pending first char (flicker suppression) and a non-ASCII /// char arrives next, the pending ASCII char should still be preserved and the overall input /// should submit normally (i.e. we should not misclassify this as a paste burst). @@ -7304,6 +7885,32 @@ mod tests { insta::assert_snapshot!("slash_popup_res", terminal.backend()); } + #[test] + fn slash_popup_archive_for_ar_ui() { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + type_chars_humanlike(&mut composer, &['/', 'a', 'r']); + + let mut terminal = Terminal::new(TestBackend::new(60, 5)).expect("terminal"); + terminal + .draw(|f| composer.render(f.area(), f.buffer_mut())) + .expect("draw composer"); + + insta::assert_snapshot!("slash_popup_ar", terminal.backend()); + } + #[test] fn slash_popup_resume_for_res_logic() { use super::super::command_popup::CommandItem; @@ -8783,6 +9390,7 @@ mod tests { ); let mention_bindings = vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: "/tmp/user/figma/SKILL.md".to_string(), }]; diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/draft_state.rs b/codex-rs/tui/src/bottom_pane/chat_composer/draft_state.rs index f739f10ec9..b219097ee1 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/draft_state.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/draft_state.rs @@ -40,6 +40,7 @@ impl DraftState { #[derive(Clone, Debug)] pub(super) struct ComposerMentionBinding { + pub(super) sigil: char, pub(super) mention: String, pub(super) path: String, } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs index 6a490e81ec..ff6dd9983c 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs @@ -18,7 +18,7 @@ use std::path::PathBuf; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; use crate::bottom_pane::MentionBinding; -use crate::mention_codec::decode_history_mentions; +use crate::mention_codec::decode_history_mentions_with_at_mentions; use codex_protocol::ThreadId; use codex_protocol::user_input::TextElement; @@ -47,7 +47,11 @@ impl HistoryEntry { /// recorded with the full `HistoryEntry` value built by the composer; using `new` for a local /// image or paste submission would make recall lose placeholder ownership. pub(crate) fn new(text: String) -> Self { - let decoded = decode_history_mentions(&text); + Self::new_with_at_mentions(text, /*at_mentions_enabled*/ true) + } + + pub(crate) fn new_with_at_mentions(text: String, at_mentions_enabled: bool) -> Self { + let decoded = decode_history_mentions_with_at_mentions(&text, at_mentions_enabled); Self { text: decoded.text, text_elements: Vec::new(), @@ -57,6 +61,7 @@ impl HistoryEntry { .mentions .into_iter() .map(|mention| MentionBinding { + sigil: mention.sigil, mention: mention.mention, path: mention.path, }) @@ -116,6 +121,8 @@ pub(crate) struct ChatComposerHistory { /// Messages submitted by the user *during this UI session* (newest at END). /// Local entries retain full draft state (text elements, image paths, pending pastes, remote image URLs). local_history: Vec, + /// Local entries seeded from resumed transcript replay. + replay_seeded_history: Vec, /// Cache of persistent history entries fetched on-demand (text-only). fetched_history: HashMap, @@ -123,6 +130,7 @@ pub(crate) struct ChatComposerHistory { /// Current cursor within the combined (persistent + local) history. `None` /// indicates the user is *not* currently browsing history. history_cursor: Option, + pending_navigation_direction: Option, /// The text that was last inserted into the composer as a result of /// history navigation. Used to decide if further Up/Down presses should be @@ -132,6 +140,8 @@ pub(crate) struct ChatComposerHistory { /// Active incremental history search, if Ctrl+R search mode is open. search: Option, + /// Whether persistent history restore should rehydrate `@` tool mentions. + at_mention_restore_enabled: bool, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -222,13 +232,27 @@ impl ChatComposerHistory { persistent_log_id: None, persistent_entry_count: 0, local_history: Vec::new(), + replay_seeded_history: Vec::new(), fetched_history: HashMap::new(), history_cursor: None, + pending_navigation_direction: None, last_history_text: None, search: None, + at_mention_restore_enabled: false, } } + pub fn set_at_mention_restore_enabled(&mut self, enabled: bool) { + if self.at_mention_restore_enabled == enabled { + return; + } + self.at_mention_restore_enabled = enabled; + self.fetched_history.clear(); + self.history_cursor = None; + self.last_history_text = None; + self.search = None; + } + /// Updates persistent history metadata when a new session is configured. /// /// This clears fetched entries, local entries, navigation cursors, and active search state @@ -240,7 +264,9 @@ impl ChatComposerHistory { self.persistent_entry_count = entry_count; self.fetched_history.clear(); self.local_history.clear(); + self.replay_seeded_history.clear(); self.history_cursor = None; + self.pending_navigation_direction = None; self.last_history_text = None; self.search = None; } @@ -250,6 +276,16 @@ impl ChatComposerHistory { /// Empty submissions are ignored, adjacent duplicates are collapsed, and active navigation or /// search state is reset because a new newest entry changes the combined history offset space. pub fn record_local_submission(&mut self, entry: HistoryEntry) { + self.record_local_submission_inner(entry); + } + + pub fn record_replayed_submission(&mut self, entry: HistoryEntry) { + if self.record_local_submission_inner(entry.clone()) { + self.replay_seeded_history.push(entry); + } + } + + fn record_local_submission_inner(&mut self, entry: HistoryEntry) -> bool { if entry.text.is_empty() && entry.text_elements.is_empty() && entry.local_image_paths.is_empty() @@ -257,18 +293,20 @@ impl ChatComposerHistory { && entry.mention_bindings.is_empty() && entry.pending_pastes.is_empty() { - return; + return false; } self.history_cursor = None; + self.pending_navigation_direction = None; self.last_history_text = None; self.search = None; // Avoid inserting a duplicate if identical to the previous entry. if self.local_history.last().is_some_and(|prev| prev == &entry) { - return; + return false; } self.local_history.push(entry); + true } /// Resets normal history navigation so the next Up key resumes from the newest entry. @@ -278,6 +316,7 @@ impl ChatComposerHistory { /// influence later Up/Down recall. pub fn reset_navigation(&mut self) { self.history_cursor = None; + self.pending_navigation_direction = None; self.last_history_text = None; self.search = None; } @@ -340,7 +379,11 @@ impl ChatComposerHistory { }; self.history_cursor = Some(next_idx); - self.populate_history_at_index(next_idx as usize, app_event_tx) + self.populate_history_at_index( + next_idx as usize, + HistorySearchDirection::Older, + app_event_tx, + ) } /// Handles Down by moving toward newer entries or clearing the composer past the newest entry. @@ -364,11 +407,16 @@ impl ChatComposerHistory { match next_idx_opt { Some(idx) => { self.history_cursor = Some(idx); - self.populate_history_at_index(idx as usize, app_event_tx) + self.populate_history_at_index( + idx as usize, + HistorySearchDirection::Newer, + app_event_tx, + ) } None => { // Past newest – clear and exit browsing mode. self.history_cursor = None; + self.pending_navigation_direction = None; self.last_history_text = None; Some(HistoryEntry::new(String::new())) } @@ -393,7 +441,9 @@ impl ChatComposerHistory { return HistoryEntryResponse::Ignored; } - let entry = entry.map(HistoryEntry::new); + let entry = entry.map(|entry| { + HistoryEntry::new_with_at_mentions(entry, self.at_mention_restore_enabled) + }); if let Some(entry) = entry.clone() { self.fetched_history.insert(offset, entry); } @@ -428,9 +478,22 @@ impl ChatComposerHistory { } if self.history_cursor == Some(offset as isize) { + let direction = self.pending_navigation_direction.take(); let Some(entry) = entry else { return HistoryEntryResponse::Ignored; }; + if self.persistent_entry_duplicates_local(&entry) + && let Some(direction) = direction + { + let Some(offset) = self.next_history_offset(offset, direction) else { + return HistoryEntryResponse::Ignored; + }; + self.history_cursor = Some(offset as isize); + return self + .populate_history_at_index(offset, direction, app_event_tx) + .map(HistoryEntryResponse::Found) + .unwrap_or(HistoryEntryResponse::Ignored); + } self.last_history_text = Some(entry.text.clone()); return HistoryEntryResponse::Found(entry); } @@ -708,29 +771,61 @@ impl ChatComposerHistory { fn populate_history_at_index( &mut self, global_idx: usize, + direction: HistorySearchDirection, app_event_tx: &AppEventSender, ) -> Option { - if global_idx >= self.persistent_entry_count { - // Local entry. - if let Some(entry) = self - .local_history - .get(global_idx - self.persistent_entry_count) - .cloned() - { + let mut global_idx = global_idx; + loop { + if let Some(entry) = self.entry_at_cached_offset(global_idx) { + if global_idx < self.persistent_entry_count + && self.persistent_entry_duplicates_local(&entry) + { + let Some(next_idx) = self.next_history_offset(global_idx, direction) else { + self.pending_navigation_direction = None; + return None; + }; + self.history_cursor = Some(next_idx as isize); + global_idx = next_idx; + continue; + } + self.pending_navigation_direction = None; self.last_history_text = Some(entry.text.clone()); return Some(entry); } - } else if let Some(entry) = self.fetched_history.get(&global_idx).cloned() { - self.last_history_text = Some(entry.text.clone()); - return Some(entry); - } else if let (Some(thread_id), Some(log_id)) = (self.thread_id, self.persistent_log_id) { - app_event_tx.send(AppEvent::LookupMessageHistoryEntry { - thread_id, - offset: global_idx, - log_id, - }); + + if global_idx >= self.persistent_entry_count { + return None; + } + + if let (Some(thread_id), Some(log_id)) = (self.thread_id, self.persistent_log_id) { + self.pending_navigation_direction = Some(direction); + app_event_tx.send(AppEvent::LookupMessageHistoryEntry { + thread_id, + offset: global_idx, + log_id, + }); + } + return None; } - None + } + + fn next_history_offset( + &self, + offset: usize, + direction: HistorySearchDirection, + ) -> Option { + match direction { + HistorySearchDirection::Older => offset.checked_sub(1), + HistorySearchDirection::Newer => offset + .checked_add(1) + .filter(|next| *next < self.total_entries()), + } + } + + fn persistent_entry_duplicates_local(&self, entry: &HistoryEntry) -> bool { + self.replay_seeded_history.iter().any(|local_entry| { + local_entry.text == entry.text && local_entry.mention_bindings == entry.mention_bindings + }) } } @@ -840,6 +935,75 @@ mod tests { ); } + #[test] + fn persistent_restore_gates_at_mentions() { + let (tx, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx); + let mut history = ChatComposerHistory::new(); + history.set_metadata(test_thread_id(), /*log_id*/ 42, /*entry_count*/ 1); + + assert!(history.navigate_up(&tx).is_none()); + let disabled = history.on_entry_response( + /*log_id*/ 42, + /*offset*/ 0, + Some("[@sample](plugin://sample@test) and [$figma](app://figma)".to_string()), + &tx, + ); + assert_eq!( + disabled, + HistoryEntryResponse::Found(HistoryEntry { + text: "$sample and $figma".to_string(), + text_elements: Vec::new(), + local_image_paths: Vec::new(), + remote_image_urls: Vec::new(), + mention_bindings: vec![ + MentionBinding { + sigil: '$', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }, + MentionBinding { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }, + ], + pending_pastes: Vec::new(), + }) + ); + + history.set_at_mention_restore_enabled(/*enabled*/ true); + assert!(history.navigate_up(&tx).is_none()); + let enabled = history.on_entry_response( + /*log_id*/ 42, + /*offset*/ 0, + Some("[@sample](plugin://sample@test) and [$figma](app://figma)".to_string()), + &tx, + ); + assert_eq!( + enabled, + HistoryEntryResponse::Found(HistoryEntry { + text: "@sample and $figma".to_string(), + text_elements: Vec::new(), + local_image_paths: Vec::new(), + remote_image_urls: Vec::new(), + mention_bindings: vec![ + MentionBinding { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }, + MentionBinding { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }, + ], + pending_pastes: Vec::new(), + }) + ); + } + #[test] fn navigation_with_async_fetch() { let (tx, mut rx) = unbounded_channel::(); @@ -849,9 +1013,16 @@ mod tests { // Pretend there are 3 persistent entries. let thread_id = test_thread_id(); history.set_metadata(thread_id, /*log_id*/ 1, /*entry_count*/ 3); + history.record_local_submission(HistoryEntry::new("latest".to_string())); - // First Up should request offset 2 (latest) and await async data. + // First Up should recall current-session local history. assert!(history.should_handle_navigation("", /*cursor*/ 0)); + assert_eq!( + Some(HistoryEntry::new("latest".to_string())), + history.navigate_up(&tx) + ); + + // Next Up should request offset 2 and await async data. assert!(history.navigate_up(&tx).is_none()); // don't replace the text yet // Verify that a history lookup request was sent. diff --git a/codex-rs/tui/src/bottom_pane/mentions_v2/search_catalog.rs b/codex-rs/tui/src/bottom_pane/mentions_v2/search_catalog.rs index b1dd7f914b..a555070a86 100644 --- a/codex-rs/tui/src/bottom_pane/mentions_v2/search_catalog.rs +++ b/codex-rs/tui/src/bottom_pane/mentions_v2/search_catalog.rs @@ -50,6 +50,7 @@ fn plugin_candidate(plugin: &PluginCapabilitySummary) -> Candidate { .config_name .split_once('@') .unwrap_or((plugin.config_name.as_str(), "")); + let mention_name = plugin_mention_name(plugin_name, plugin.display_name.as_str()); let mut search_terms = vec![plugin_name.to_string(), plugin.config_name.clone()]; if plugin.display_name != plugin_name { search_terms.push(plugin.display_name.clone()); @@ -64,12 +65,88 @@ fn plugin_candidate(plugin: &PluginCapabilitySummary) -> Candidate { search_terms, mention_type: MentionType::Plugin, selection: Selection::Tool { - insert_text: format!("${plugin_name}"), + insert_text: format!("@{mention_name}"), path: Some(format!("plugin://{}", plugin.config_name)), }, } } +fn plugin_mention_name(plugin_name: &str, display_name: &str) -> String { + let plugin_segments = split_plugin_name_segments(plugin_name); + let display_segments = split_display_name_segments(display_name); + + if plugin_segments.len() == display_segments.len() + && plugin_segments.iter().zip(&display_segments).all( + |((plugin_segment, _), display_segment)| { + plugin_segment.eq_ignore_ascii_case(display_segment.as_str()) + }, + ) + { + let mut result = String::new(); + for ((_, separator), display_segment) in plugin_segments.into_iter().zip(display_segments) { + result.push_str(display_segment.as_str()); + if let Some(separator) = separator { + result.push(separator); + } + } + return result; + } + + title_case_plugin_name(plugin_name) +} + +fn split_plugin_name_segments(plugin_name: &str) -> Vec<(String, Option)> { + let mut segments = Vec::new(); + let mut current = String::new(); + + for ch in plugin_name.chars() { + if matches!(ch, '-' | '_') { + if !current.is_empty() { + segments.push((std::mem::take(&mut current), Some(ch))); + } + } else { + current.push(ch); + } + } + + if !current.is_empty() { + segments.push((current, None)); + } + + segments +} + +fn split_display_name_segments(display_name: &str) -> Vec { + display_name + .split(|ch: char| !ch.is_ascii_alphanumeric()) + .filter(|segment| !segment.is_empty()) + .map(ToString::to_string) + .collect() +} + +fn title_case_plugin_name(plugin_name: &str) -> String { + let mut result = String::with_capacity(plugin_name.len()); + let mut capitalize_next = true; + + for ch in plugin_name.chars() { + if matches!(ch, '-' | '_') { + capitalize_next = true; + result.push(ch); + continue; + } + + if capitalize_next && ch.is_ascii_alphabetic() { + result.push(ch.to_ascii_uppercase()); + capitalize_next = false; + } else { + result.push(ch); + capitalize_next = false; + } + } + + result +} + fn plugin_description(plugin: &PluginCapabilitySummary) -> Option { let capability_labels = plugin_capability_labels(plugin); plugin.description.clone().or_else(|| { @@ -109,3 +186,30 @@ fn optional_skill_description(skill: &SkillMetadata) -> Option { let description = skill_description(skill).trim(); (!description.is_empty()).then(|| description.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn plugin_mention_name_uses_display_segments_when_they_match_plugin_name() { + assert_eq!( + plugin_mention_name("mcp-search", "MCP Search"), + "MCP-Search" + ); + assert_eq!( + plugin_mention_name("google_calendar", "Google Calendar"), + "Google_Calendar" + ); + } + + #[test] + fn plugin_mention_name_falls_back_to_title_cased_plugin_name() { + assert_eq!(plugin_mention_name("sample", "Sample Plugin"), "Sample"); + assert_eq!( + plugin_mention_name("browser-use", "Browser Use"), + "Browser-Use" + ); + } +} diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 1fcc7635c0..fa92914670 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -83,7 +83,9 @@ pub(crate) struct LocalImageAttachment { #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct MentionBinding { - /// Mention token text without the leading `$`. + /// Visible mention sigil (`$` or `@`). + pub(crate) sigil: char, + /// Mention token text without the leading sigil (`$` or `@`). pub(crate) mention: String, /// Canonical mention target (for example `app://...` or absolute SKILL.md path). pub(crate) path: String, @@ -182,6 +184,7 @@ pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::ChatComposerConfig; pub(crate) use chat_composer::InputResult; pub(crate) use chat_composer::QueuedInputAction; +pub(crate) use chat_composer_history::HistoryEntry; use crate::status_indicator_widget::StatusDetailsCapitalization; use crate::status_indicator_widget::StatusIndicatorWidget; @@ -1541,6 +1544,10 @@ impl BottomPane { } } + pub(crate) fn record_replayed_user_message_history(&mut self, entry: HistoryEntry) { + self.composer.record_replayed_user_message_history(entry); + } + pub(crate) fn on_file_search_result(&mut self, query: String, matches: Vec) { self.composer.on_file_search_result(query, matches); self.request_redraw(); diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__plugin_at_mentions_render_with_plugin_accent.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__plugin_at_mentions_render_with_plugin_accent.snap new file mode 100644 index 0000000000..0f6c47dca0 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__plugin_at_mentions_render_with_plugin_accent.snap @@ -0,0 +1,6 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: "format!(\"text: {text}\\nmagenta: {magenta}\")" +--- +text: › @sample plugin +magenta: ^^^^^^^ diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_ar.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_ar.snap new file mode 100644 index 0000000000..5014c35d28 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_ar.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› /ar " +" " +" " +" /archive archive this session and exit " diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index d3e5cf68ef..32c68529d5 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -169,6 +169,8 @@ use codex_terminal_detection::TerminalName; use codex_terminal_detection::terminal_info; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_cli::resume_hint; +use codex_utils_plugins::mention_syntax::PLUGIN_TEXT_MENTION_SIGIL; +use codex_utils_plugins::mention_syntax::TOOL_MENTION_SIGIL; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -274,6 +276,7 @@ use crate::bottom_pane::DOUBLE_PRESS_QUIT_SHORTCUT_ENABLED; use crate::bottom_pane::ExperimentalFeatureItem; use crate::bottom_pane::ExperimentalFeaturesView; use crate::bottom_pane::GoalStatusIndicator; +use crate::bottom_pane::HistoryEntry; use crate::bottom_pane::InputResult; use crate::bottom_pane::LocalImageAttachment; use crate::bottom_pane::McpServerElicitationFormRequest; @@ -464,7 +467,9 @@ use unicode_segmentation::UnicodeSegmentation; const USER_SHELL_COMMAND_HELP_TITLE: &str = "Prefix a command with ! to run it locally"; const USER_SHELL_COMMAND_HELP_HINT: &str = "Example: !ls"; -const AUTO_REVIEW_DESCRIPTION: &str = "Same workspace-write permissions as Default, but eligible `on-request` approvals are routed through the auto-reviewer subagent."; +const ASK_FOR_APPROVAL_LABEL: &str = "Ask for approval"; +const APPROVE_FOR_ME_LABEL: &str = "Approve for me"; +const AUTO_REVIEW_DESCRIPTION: &str = "Only ask for actions detected as potentially unsafe."; const DEFAULT_OPENAI_BASE_URL: &str = "https://api.openai.com/v1"; const DEFAULT_STATUS_LINE_ITEMS: [&str; 2] = ["model-with-reasoning", "current-dir"]; const MAX_AGENT_COPY_HISTORY: usize = 32; @@ -1223,9 +1228,75 @@ impl ChatWidget { fn on_committed_user_message(&mut self, items: &[UserInput], from_replay: bool) { let display = Self::user_message_display_from_inputs(items); if from_replay { - if !self.review.is_review_mode { - self.on_user_message_display(display); + if self.review.is_review_mode { + return; } + let message = display.message.as_str(); + let mention_start = |sigil: char, mention: &str| { + let token = format!("{sigil}{mention}"); + message.match_indices(&token).find_map(|(start, _)| { + let end = start + token.len(); + message + .as_bytes() + .get(end) + .is_none_or(|byte| { + !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-') + }) + .then_some(start) + }) + }; + let mut mention_bindings: Vec = items + .iter() + .filter_map(|item| match item { + UserInput::Skill { name, path } => Some(MentionBinding { + sigil: TOOL_MENTION_SIGIL, + mention: name.clone(), + path: path.to_string_lossy().into_owned(), + }), + UserInput::Mention { name, path } => { + let plugin_id = path.strip_prefix("plugin://"); + let mention = if let Some(plugin_id) = plugin_id { + plugin_id + .split_once('@') + .map(|(plugin_name, _)| plugin_name) + .unwrap_or(plugin_id) + .to_string() + } else if path.starts_with("app://") { + codex_connectors::metadata::connector_mention_slug_from_name(name) + } else { + name.clone() + }; + let sigil = if plugin_id.is_some() + && mention_start(PLUGIN_TEXT_MENTION_SIGIL, &mention).is_some() + { + PLUGIN_TEXT_MENTION_SIGIL + } else { + TOOL_MENTION_SIGIL + }; + Some(MentionBinding { + sigil, + mention, + path: path.clone(), + }) + } + UserInput::Text { .. } + | UserInput::Image { .. } + | UserInput::LocalImage { .. } => None, + }) + .collect(); + mention_bindings.sort_by_key(|binding| { + mention_start(binding.sigil, &binding.mention).unwrap_or(usize::MAX) + }); + self.bottom_pane + .record_replayed_user_message_history(HistoryEntry { + text: display.message.clone(), + text_elements: display.text_elements.clone(), + local_image_paths: display.local_images.clone(), + remote_image_urls: display.remote_image_urls.clone(), + mention_bindings, + pending_pastes: Vec::new(), + }); + self.on_user_message_display(display); return; } diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index 4700ffc0cc..578a35728f 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -363,6 +363,7 @@ impl ChatWidget { let encoded_mentions = mention_bindings .iter() .map(|binding| LinkedMention { + sigil: binding.sigil, mention: binding.mention.clone(), path: binding.path.clone(), }) diff --git a/codex-rs/tui/src/chatwidget/permission_popups.rs b/codex-rs/tui/src/chatwidget/permission_popups.rs index b271422788..c0d492d7aa 100644 --- a/codex-rs/tui/src/chatwidget/permission_popups.rs +++ b/codex-rs/tui/src/chatwidget/permission_popups.rs @@ -56,7 +56,9 @@ impl ChatWidget { continue; } let base_name = if preset.id == "auto" && windows_degraded_sandbox_enabled { - "Default (non-admin sandbox)".to_string() + format!("{ASK_FOR_APPROVAL_LABEL} (non-admin sandbox)") + } else if preset.id == "auto" { + ASK_FOR_APPROVAL_LABEL.to_string() } else { preset.label.to_string() }; @@ -100,7 +102,7 @@ impl ChatWidget { if guardian_approval_enabled { items.push(SelectionItem { - name: "Auto-review".to_string(), + name: APPROVE_FOR_ME_LABEL.to_string(), description: Some(AUTO_REVIEW_DESCRIPTION.to_string()), is_current: current_review_policy == ApprovalsReviewer::AutoReview && Self::preset_matches_current( @@ -111,7 +113,7 @@ impl ChatWidget { ), actions: self.permission_mode_actions( &preset, - "Auto-review".to_string(), + APPROVE_FOR_ME_LABEL.to_string(), ApprovalsReviewer::AutoReview, /*profile_selection*/ None, /*return_to_permissions*/ !include_read_only, diff --git a/codex-rs/tui/src/chatwidget/permissions_menu.rs b/codex-rs/tui/src/chatwidget/permissions_menu.rs index 7c0477116c..c9cb3b108f 100644 --- a/codex-rs/tui/src/chatwidget/permissions_menu.rs +++ b/codex-rs/tui/src/chatwidget/permissions_menu.rs @@ -94,10 +94,10 @@ impl ChatWidget { approval_policy: AskForApproval, approvals_reviewer: ApprovalsReviewer, ) -> SelectionItem { - let label = if approvals_reviewer == ApprovalsReviewer::AutoReview { - "Auto-review" - } else { - preset.label + let label = match (preset.id, approvals_reviewer) { + ("auto", ApprovalsReviewer::AutoReview) => APPROVE_FOR_ME_LABEL, + ("auto", ApprovalsReviewer::User) => ASK_FOR_APPROVAL_LABEL, + _ => preset.label, }; let active_profile_id = self .config diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index b479718304..99833da8a8 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -164,6 +164,35 @@ impl ChatWidget { SlashCommand::New => { self.app_event_tx.send(AppEvent::NewSession); } + SlashCommand::Archive => { + self.bottom_pane.show_selection_view(SelectionViewParams { + title: Some("Archive this session?".to_string()), + subtitle: Some( + "Are you sure? This will archive the current session and exit Codex" + .to_string(), + ), + footer_hint: Some(standard_popup_hint_line()), + items: vec![ + SelectionItem { + name: "No, don't archive".to_string(), + description: Some("Return to the current session".to_string()), + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "Yes, archive and exit".to_string(), + description: Some("Archive this session now".to_string()), + actions: vec![Box::new(|tx| { + tx.send(AppEvent::ArchiveCurrentThread); + })], + dismiss_on_select: true, + ..Default::default() + }, + ], + ..Default::default() + }); + self.request_redraw(); + } SlashCommand::Clear => { self.app_event_tx.send(AppEvent::ClearUi); } @@ -949,6 +978,7 @@ impl ChatWidget { | SlashCommand::TestApproval => QueueDrain::Continue, SlashCommand::Feedback | SlashCommand::New + | SlashCommand::Archive | SlashCommand::Clear | SlashCommand::Resume | SlashCommand::Fork diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap index 52ac576149..bfa5173474 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap @@ -4,11 +4,11 @@ expression: popup --- Update Model Permissions -› 1. Default Codex can read and edit files in the current workspace, and - run commands. Approval is required to access the internet or - edit other files. - 2. Full Access Codex can edit files outside this workspace and access the - internet without asking for approval. Exercise caution when - using. +› 1. Ask for approval Codex can read and edit files in the current workspace, + and run commands. Approval is required to access the + internet or edit other files. + 2. Full Access Codex can edit files outside this workspace and access + the internet without asking for approval. Exercise + caution when using. Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap index 9c512c7781..abd2450bf7 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap @@ -7,7 +7,7 @@ expression: popup › 1. Read Only (current) Codex can read files in the current workspace. Approval is required to edit files or access the internet. - 2. Default Codex can read and edit files in the current + 2. Ask for approval Codex can read and edit files in the current workspace, and run commands. Approval is required to access the internet or edit other files. 3. Full Access Codex can edit files outside this workspace and diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows_degraded.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows_degraded.snap index ecbe5de157..368e732855 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows_degraded.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows_degraded.snap @@ -5,17 +5,17 @@ expression: popup --- Update Model Permissions -› 1. Read Only (current) Codex can read files in the current - workspace. Approval is required to edit - files or access the internet. - 2. Default (non-admin sandbox) Codex can read and edit files in the - current workspace, and run commands. - Approval is required to access the - internet or edit other files. - 3. Full Access Codex can edit files outside this - workspace and access the internet without - asking for approval. Exercise caution - when using. +› 1. Read Only (current) Codex can read files in the current + workspace. Approval is required to + edit files or access the internet. + 2. Ask for approval (non-admin sandbox) Codex can read and edit files in the + current workspace, and run commands. + Approval is required to access the + internet or edit other files. + 3. Full Access Codex can edit files outside this + workspace and access the internet + without asking for approval. Exercise + caution when using. The non-admin sandbox protects your files and prevents network access under most circumstances. However, it carries greater risk if prompt injected. To diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hook_completed_before_reveal_renders_completed_without_running_flash_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hook_completed_before_reveal_renders_completed_without_running_flash_snapshot.snap index b38d4e260a..0dd1aa064e 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hook_completed_before_reveal_renders_completed_without_running_flash_snapshot.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hook_completed_before_reveal_renders_completed_without_running_flash_snapshot.snap @@ -7,3 +7,4 @@ started hidden: history: • SessionStart hook (completed) hook context: session context + second line diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default.snap index 135e5b1bfa..3352c2435a 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default.snap @@ -1,5 +1,5 @@ --- -source: tui/src/chatwidget/tests.rs +source: tui/src/chatwidget/tests/permissions.rs expression: "lines_to_single_string(&cells[0])" --- -• Permissions updated to Default +• Permissions updated to Ask for approval diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default@windows.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default@windows.snap index eb08108564..6e0269a521 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default@windows.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__permissions_selection_history_full_access_to_default@windows.snap @@ -2,4 +2,4 @@ source: tui/src/chatwidget/tests.rs expression: "lines_to_single_string(&cells[0])" --- -• Permissions updated to Default (non-admin sandbox) +• Permissions updated to Ask for approval (non-admin sandbox) diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup.snap index c0a23815a0..5ad5481590 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup.snap @@ -4,17 +4,17 @@ expression: "render_bottom_popup(&chat, 80)" --- Update Model Permissions -› 1. Default (current) Codex can read and edit files in the current - workspace, and run commands. Approval is required to - access the internet or edit other files. - 2. Auto-review Same workspace-write permissions as Default, but - eligible `on-request` approvals are routed through the - auto-reviewer subagent. - 3. Full Access Codex can edit files outside this workspace and access - the internet without asking for approval. Exercise - caution when using. - 4. Read Only Codex can read files in the current workspace. - Approval is required to edit files or access the - internet. +› 1. Ask for approval (current) Codex can read and edit files in the current + workspace, and run commands. Approval is + required to access the internet or edit other + files. + 2. Approve for me Only ask for actions detected as potentially + unsafe. + 3. Full Access Codex can edit files outside this workspace + and access the internet without asking for + approval. Exercise caution when using. + 4. Read Only Codex can read files in the current + workspace. Approval is required to edit files + or access the internet. Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup_with_custom_profiles.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup_with_custom_profiles.snap index 3ca5753795..dac63d4e32 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup_with_custom_profiles.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__profile_permissions_selection_popup_with_custom_profiles.snap @@ -4,12 +4,11 @@ expression: "render_bottom_popup(&chat, 80)" --- Update Model Permissions - 1. Default Codex can read and edit files in the current + 1. Ask for approval Codex can read and edit files in the current workspace, and run commands. Approval is required to access the internet or edit other files. - 2. Auto-review Same workspace-write permissions as Default, but - eligible `on-request` approvals are routed through - the auto-reviewer subagent. + 2. Approve for me Only ask for actions detected as potentially + unsafe. 3. Full Access Codex can edit files outside this workspace and access the internet without asking for approval. Exercise caution when using. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_archive_confirmation_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_archive_confirmation_popup.snap new file mode 100644 index 0000000000..cdc895d7be --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_archive_confirmation_popup.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests/slash_commands.rs +expression: popup +--- + Archive this session? + Are you sure? This will archive the current session and exit Codex + +› 1. No, don't archive Return to the current session + 2. Yes, archive and exit Archive this session now + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap index 250d56ff48..28a7863858 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_surface_previews_hardcoded_only.snap @@ -2,5 +2,5 @@ source: tui/src/chatwidget/tests/status_surface_previews.rs expression: snapshot --- -status line: my-project · feat/awesome-feature · thread title · Read Only · on-request +status line: my-project · feat/awesome-feature · thread title · Read Only · Ask for approval terminal title: thread title | feat/awesome-feature | Tasks 0/0 diff --git a/codex-rs/tui/src/chatwidget/status_surfaces.rs b/codex-rs/tui/src/chatwidget/status_surfaces.rs index 2b2b7d52df..6a3bbbc07b 100644 --- a/codex-rs/tui/src/chatwidget/status_surfaces.rs +++ b/codex-rs/tui/src/chatwidget/status_surfaces.rs @@ -1016,13 +1016,14 @@ fn permissions_display(config: &Config) -> String { fn approval_mode_display(config: &Config) -> String { let approval_policy = AskForApproval::from(config.permissions.approval_policy.value()); - if approval_policy == AskForApproval::OnRequest - && config.approvals_reviewer == ApprovalsReviewer::AutoReview - { - "auto-review".to_string() - } else { - config.permissions.approval_policy.value().to_string() + if approval_policy == AskForApproval::OnRequest { + return match config.approvals_reviewer { + ApprovalsReviewer::AutoReview => "Approve for me".to_string(), + ApprovalsReviewer::User => "Ask for approval".to_string(), + }; } + + config.permissions.approval_policy.value().to_string() } fn parse_items_with_invalids(ids: impl IntoIterator) -> (Vec, Vec) diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index c8d45d2a59..f4fcc85e43 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -283,6 +283,7 @@ async fn live_app_server_user_message_item_completed_does_not_duplicate_rendered completed_at_ms: 0, item: AppServerThreadItem::UserMessage { id: "user-1".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "Hi, are you there?".to_string(), text_elements: Vec::new(), diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index 23487af437..27ae4daff2 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -570,6 +570,7 @@ async fn submission_prefers_selected_duplicate_skill_path() { Vec::new(), Vec::new(), vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: user_skill_path.to_string_lossy().into_owned(), }], @@ -605,6 +606,7 @@ async fn blocked_image_restore_preserves_mention_bindings() { path: PathBuf::from("/tmp/blocked.png"), }]; let mention_bindings = vec![MentionBinding { + sigil: '$', mention: "file".to_string(), path: "/tmp/skills/file/SKILL.md".to_string(), }]; @@ -1236,6 +1238,7 @@ async fn submit_user_message_ignores_inaccessible_app_mentions_from_bindings() { remote_image_urls: Vec::new(), text_elements: Vec::new(), mention_bindings: vec![MentionBinding { + sigil: '$', mention: "arabica-uae".to_string(), path: "app://arabica_uae".to_string(), }], diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 63487f18b9..c63b617ab3 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -722,6 +722,7 @@ pub(super) fn replay_user_message_inputs( chat.replay_thread_item( AppServerThreadItem::UserMessage { id: item_id.to_string(), + client_id: None, content, }, "turn-1".to_string(), @@ -946,6 +947,7 @@ pub(super) fn complete_user_message_for_inputs( completed_at_ms: 0, item: AppServerThreadItem::UserMessage { id: item_id.to_string(), + client_id: None, content, }, }), diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index 58f99231f3..e6b9d4ede0 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -1,4 +1,5 @@ use super::*; +use crate::app_event::HistoryLookupResponse; use codex_app_server_protocol::NetworkAccess; use codex_app_server_protocol::SandboxPolicy; use codex_protocol::models::ManagedFileSystemPermissions; @@ -74,6 +75,120 @@ async fn resumed_initial_messages_render_history() { ); } +#[tokio::test] +async fn replayed_user_messages_seed_composer_history() { + let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + chat.bottom_pane.set_history_metadata( + ThreadId::new(), + /*log_id*/ 1, + /*entry_count*/ 3, + ); + + let mut replay_mention = |id: &str, text: &str, name: &str, path: &str| { + replay_user_message_inputs( + &mut chat, + id, + vec![ + AppServerUserInput::Text { + text: text.to_string(), + text_elements: Vec::new(), + }, + AppServerUserInput::Mention { + name: name.to_string(), + path: path.to_string(), + }, + ], + ReplayKind::ResumeInitialMessages, + ); + }; + replay_mention( + "user-1", + "use $sample", + "Sample Plugin", + "plugin://sample@test", + ); + replay_mention( + "user-2", + "use $google-calendar", + "Google Calendar", + "app://google_calendar", + ); + drain_insert_history(&mut rx); + + chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + assert_eq!(chat.bottom_pane.composer_text(), "use $google-calendar"); + assert_eq!( + chat.bottom_pane.take_mention_bindings(), + vec![MentionBinding { + sigil: '$', + mention: "google-calendar".to_string(), + path: "app://google_calendar".to_string(), + }] + ); + + chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + assert_eq!(chat.bottom_pane.composer_text(), "use $sample"); + assert_eq!( + chat.bottom_pane.take_mention_bindings(), + vec![MentionBinding { + sigil: '$', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }] + ); + + let mut next_lookup_offset = || { + let AppEvent::LookupMessageHistoryEntry { offset, .. } = + rx.try_recv().expect("expected lookup") + else { + panic!("unexpected event variant"); + }; + offset + }; + let response = |offset, entry: &str| HistoryLookupResponse { + offset, + log_id: 1, + entry: Some(entry.to_string()), + }; + + chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + chat.handle_history_entry_response(response( + next_lookup_offset(), + "use [$google-calendar](app://google_calendar)", + )); + + assert_eq!(next_lookup_offset(), 1); + chat.handle_history_entry_response(response(1, "use [$sample](plugin://sample@test)")); + + assert_eq!(next_lookup_offset(), 0); + chat.handle_history_entry_response(response(0, "/rename smoke-1")); + assert_eq!(chat.bottom_pane.composer_text(), "/rename smoke-1"); +} + +#[tokio::test] +async fn replayed_review_prompt_does_not_seed_composer_history() { + let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.replay_thread_item( + AppServerThreadItem::EnteredReviewMode { + id: "review-start".to_string(), + review: "changes against main".to_string(), + }, + "turn-1".to_string(), + ReplayKind::ResumeInitialMessages, + ); + replay_user_message_text( + &mut chat, + "review-prompt", + "Review the code changes against the base branch 'main'.", + ReplayKind::ResumeInitialMessages, + ); + drain_insert_history(&mut rx); + + chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); + assert_eq!(chat.bottom_pane.composer_text(), ""); +} + #[tokio::test] async fn replayed_user_message_preserves_text_elements_and_local_images() { let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/tests/permissions.rs b/codex-rs/tui/src/chatwidget/tests/permissions.rs index f79fe3defc..20d600b303 100644 --- a/codex-rs/tui/src/chatwidget/tests/permissions.rs +++ b/codex-rs/tui/src/chatwidget/tests/permissions.rs @@ -143,7 +143,7 @@ async fn profile_permissions_selection_emits_named_profile_event_only() { approval_policy: Some(AskForApproval::OnRequest), approvals_reviewer: Some(ApprovalsReviewer::User), display_label, - }) if profile_id == ":workspace" && display_label == "Default" + }) if profile_id == ":workspace" && display_label == "Ask for approval" )); } @@ -208,7 +208,7 @@ async fn profile_permissions_selection_emits_auto_review_mode_event() { approval_policy: Some(AskForApproval::OnRequest), approvals_reviewer: Some(ApprovalsReviewer::AutoReview), display_label, - }) if profile_id == ":workspace" && display_label == "Auto-review" + }) if profile_id == ":workspace" && display_label == "Approve for me" )); } @@ -256,7 +256,7 @@ async fn approvals_selection_popup_snapshot_windows_degraded_sandbox() { let popup = render_bottom_popup(&chat, /*width*/ 80); assert!( - popup.contains("Default (non-admin sandbox)"), + popup.contains("Ask for approval (non-admin sandbox)"), "expected degraded sandbox label in approvals popup: {popup}" ); assert!( @@ -285,7 +285,7 @@ async fn preset_matching_accepts_workspace_write_with_extra_roots() { cwd.as_path(), &preset ), - "WorkspaceWrite with extra roots should still match the Default preset" + "WorkspaceWrite with extra roots should still match the Ask for approval preset" ); assert!( !ChatWidget::preset_matches_current( @@ -629,7 +629,7 @@ async fn permissions_selection_history_snapshot_full_access_to_default() { chat.open_permissions_popup(); let popup = render_bottom_popup(&chat, /*width*/ 120); chat.handle_key_event(KeyEvent::from(KeyCode::Up)); - if popup.contains("Auto-review") { + if popup.contains("Approve for me") { chat.handle_key_event(KeyEvent::from(KeyCode::Up)); } chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); @@ -699,8 +699,8 @@ async fn permissions_selection_hides_auto_review_when_feature_disabled() { let popup = render_bottom_popup(&chat, /*width*/ 120); assert!( - !popup.contains("Auto-review"), - "expected Auto-review to stay hidden until the feature is enabled: {popup}" + !popup.contains("Approve for me"), + "expected Approve for me to stay hidden until the feature is enabled: {popup}" ); } @@ -730,8 +730,8 @@ async fn permissions_selection_hides_auto_review_when_feature_disabled_even_if_a let popup = render_bottom_popup(&chat, /*width*/ 120); assert!( - !popup.contains("Auto-review"), - "expected Auto-review to stay hidden when the feature is disabled: {popup}" + !popup.contains("Approve for me"), + "expected Approve for me to stay hidden when the feature is disabled: {popup}" ); } @@ -776,8 +776,8 @@ async fn permissions_selection_marks_auto_review_current_after_session_configure let popup = render_bottom_popup(&chat, /*width*/ 120); assert!( - popup.contains("Auto-review (current)"), - "expected Auto-review to be current after SessionConfigured sync: {popup}" + popup.contains("Approve for me (current)"), + "expected Approve for me to be current after SessionConfigured sync: {popup}" ); } @@ -826,8 +826,8 @@ async fn permissions_selection_marks_auto_review_current_with_custom_workspace_w let popup = render_bottom_popup(&chat, /*width*/ 120); assert!( - popup.contains("Auto-review (current)"), - "expected Auto-review to be current even with custom workspace-write details: {popup}" + popup.contains("Approve for me (current)"), + "expected Approve for me to be current even with custom workspace-write details: {popup}" ); } @@ -861,7 +861,7 @@ async fn permissions_selection_can_disable_auto_review() { event, AppEvent::UpdateApprovalsReviewer(ApprovalsReviewer::User) )), - "expected selecting Default from Auto-review to switch back to manual approval review: {events:?}" + "expected selecting Ask for approval from Approve for me to switch back to manual approval review: {events:?}" ); assert!( !events @@ -906,8 +906,8 @@ async fn permissions_selection_sends_approvals_reviewer_in_override_turn_context assert!( popup .lines() - .any(|line| line.contains("Auto-review") && line.contains('›')), - "expected one Down from Default to select Auto-review: {popup}" + .any(|line| line.contains("Approve for me") && line.contains('›')), + "expected one Down from Ask for approval to select Approve for me: {popup}" ); chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); diff --git a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs index 5fc2fa2ce9..74cd527038 100644 --- a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs +++ b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs @@ -1244,6 +1244,7 @@ async fn submit_user_message_emits_structured_plugin_mentions_from_bindings() { remote_image_urls: Vec::new(), text_elements: Vec::new(), mention_bindings: vec![MentionBinding { + sigil: '$', mention: "sample".to_string(), path: "plugin://sample@test".to_string(), }], diff --git a/codex-rs/tui/src/chatwidget/tests/review_mode.rs b/codex-rs/tui/src/chatwidget/tests/review_mode.rs index 48bc341f6b..faf8636ad8 100644 --- a/codex-rs/tui/src/chatwidget/tests/review_mode.rs +++ b/codex-rs/tui/src/chatwidget/tests/review_mode.rs @@ -182,6 +182,7 @@ async fn live_app_server_review_prompt_item_is_not_rendered() { completed_at_ms: 0, item: AppServerThreadItem::UserMessage { id: "review-prompt".to_string(), + client_id: None, content: vec![AppServerUserInput::Text { text: "Review the code changes against the base branch 'main'.".to_string(), text_elements: Vec::new(), @@ -875,6 +876,7 @@ async fn manual_interrupt_restores_pending_steer_mention_bindings_to_composer() chat.on_agent_message_delta("Final answer line\n".to_string()); let mention_bindings = vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: "/tmp/skills/figma/SKILL.md".to_string(), }]; diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 0346b97069..4f425c25c9 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -656,6 +656,7 @@ async fn goal_slash_command_uses_plain_text_for_mentions() { Vec::new(), Vec::new(), vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: "app://figma".to_string(), }], @@ -917,6 +918,7 @@ fn merged_history_record_preserves_raw_text_and_rebased_elements() { remote_image_urls: Vec::new(), text_elements: vec![TextElement::new((4..10).into(), Some("$figma".to_string()))], mention_bindings: vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: "app://figma".to_string(), }], @@ -1034,6 +1036,7 @@ async fn interrupted_merged_message_history_encodes_mentions_once() { Vec::new(), Vec::new(), vec![MentionBinding { + sigil: '$', mention: "figma".to_string(), path: "app://figma".to_string(), }], @@ -1724,6 +1727,27 @@ async fn slash_clear_is_disabled_while_task_running() { assert!(rx.try_recv().is_err(), "expected no follow-up events"); } +#[tokio::test] +async fn slash_archive_is_disabled_while_task_running() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.bottom_pane.set_task_running(/*running*/ true); + + chat.dispatch_command(SlashCommand::Archive); + + let event = rx.try_recv().expect("expected disabled command error"); + match event { + AppEvent::InsertHistoryCell(cell) => { + let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80)); + assert!( + rendered.contains("'/archive' is disabled while a task is in progress."), + "expected /archive task-running error, got {rendered:?}" + ); + } + other => panic!("expected InsertHistoryCell error, got {other:?}"), + } + assert!(rx.try_recv().is_err(), "expected no follow-up events"); +} + #[tokio::test] async fn slash_memory_drop_reports_stubbed_feature() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -1843,6 +1867,24 @@ async fn slash_resume_opens_picker() { assert_matches!(rx.try_recv(), Ok(AppEvent::OpenResumePicker)); } +#[tokio::test] +async fn slash_archive_confirmation_requests_current_thread_archive() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.dispatch_command(SlashCommand::Archive); + + assert!(chat.bottom_pane.has_active_view()); + assert_matches!(rx.try_recv(), Err(TryRecvError::Empty)); + + let popup = render_bottom_popup(&chat, /*width*/ 80); + assert_chatwidget_snapshot!("slash_archive_confirmation_popup", popup); + + chat.handle_key_event(KeyEvent::from(KeyCode::Down)); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + assert_matches!(rx.try_recv(), Ok(AppEvent::ArchiveCurrentThread)); +} + #[tokio::test] async fn slash_resume_with_arg_requests_named_session() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index acb1df6c5a..45f9bbca53 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -3381,7 +3381,7 @@ async fn hook_completed_before_reveal_renders_completed_without_running_flash() codex_app_server_protocol::HookRunStatus::Completed, vec![codex_app_server_protocol::HookOutputEntry { kind: codex_app_server_protocol::HookOutputEntryKind::Context, - text: "session context".to_string(), + text: "session context\nsecond line".to_string(), }], ), ); diff --git a/codex-rs/tui/src/chatwidget/user_messages.rs b/codex-rs/tui/src/chatwidget/user_messages.rs index cdcf650cb1..80a36b5815 100644 --- a/codex-rs/tui/src/chatwidget/user_messages.rs +++ b/codex-rs/tui/src/chatwidget/user_messages.rs @@ -578,6 +578,7 @@ impl ChatWidget { UserInput::Text { text, text_elements: current_text_elements, + .. } => append_text_with_rebased_elements( &mut message, &mut text_elements, diff --git a/codex-rs/tui/src/chatwidget/windows_sandbox_prompts.rs b/codex-rs/tui/src/chatwidget/windows_sandbox_prompts.rs index 3b8dfce200..ebeb23429c 100644 --- a/codex-rs/tui/src/chatwidget/windows_sandbox_prompts.rs +++ b/codex-rs/tui/src/chatwidget/windows_sandbox_prompts.rs @@ -14,12 +14,13 @@ impl ChatWidget { return None; } let cwd = self.config.cwd.clone(); + let workspace_roots = self.config.effective_workspace_roots(); let env_map: std::collections::HashMap = std::env::vars().collect(); let permission_profile = self.config.permissions.effective_permission_profile(); let Ok(permissions) = - codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + codex_windows_sandbox::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( &permission_profile, - cwd.as_path(), + workspace_roots.as_slice(), ) else { return None; diff --git a/codex-rs/tui/src/debug_config.rs b/codex-rs/tui/src/debug_config.rs index 4c40e04455..b1f5608b89 100644 --- a/codex-rs/tui/src/debug_config.rs +++ b/codex-rs/tui/src/debug_config.rs @@ -518,7 +518,7 @@ fn format_network_unix_socket_permission( ) -> &'static str { match permission { NetworkUnixSocketPermissionToml::Allow => "allow", - NetworkUnixSocketPermissionToml::None => "none", + NetworkUnixSocketPermissionToml::Deny => "deny", } } @@ -837,7 +837,7 @@ mod tests { ), ( "/tmp/blocked.sock".to_string(), - NetworkUnixSocketPermissionToml::None, + NetworkUnixSocketPermissionToml::Deny, ), ]), }), @@ -854,7 +854,7 @@ mod tests { let rendered = render_to_text(&render_debug_config_lines(&stack)); assert!(rendered.contains( - "experimental_network: unix_sockets={/tmp/blocked.sock=none, /tmp/codex.sock=allow} (source: cloud requirements)" + "experimental_network: unix_sockets={/tmp/blocked.sock=deny, /tmp/codex.sock=allow} (source: cloud requirements)" )); } diff --git a/codex-rs/tui/src/get_git_diff.rs b/codex-rs/tui/src/get_git_diff.rs index a7b4b668fb..7f55450707 100644 --- a/codex-rs/tui/src/get_git_diff.rs +++ b/codex-rs/tui/src/get_git_diff.rs @@ -13,6 +13,13 @@ use crate::workspace_command::WorkspaceCommandExecutor; use crate::workspace_command::WorkspaceCommandOutput; const DIFF_COMMAND_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30); +const DISABLE_FSMONITOR_CONFIG: &str = "core.fsmonitor=false"; +const DISABLE_HOOKS_CONFIG: &str = if cfg!(windows) { + "core.hooksPath=NUL" +} else { + "core.hooksPath=/dev/null" +}; +const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|process)$"; /// Return value of [`get_git_diff`]. /// @@ -27,9 +34,22 @@ pub(crate) async fn get_git_diff( return Ok((false, String::new())); } - // Run tracked diff and untracked file listing in parallel. + // Keep `/diff` informational: repository configuration must not select executable diff helpers. + let diff_config_overrides = diff_filter_config_overrides(runner, cwd).await?; let (tracked_diff_res, untracked_output_res) = tokio::join!( - run_git_capture_diff(runner, cwd, &["diff", "--color"]), + run_git_capture_diff( + runner, + cwd, + &diff_config_overrides, + &[ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + ] + ), run_git_capture_stdout(runner, cwd, &["ls-files", "--others", "--exclude-standard"]), ); let tracked_diff = tracked_diff_res?; @@ -48,8 +68,19 @@ pub(crate) async fn get_git_diff( .map(str::trim) .filter(|s| !s.is_empty()) { - let args = ["diff", "--color", "--no-index", "--", null_path, file]; - let diff = run_git_capture_diff(runner, cwd, &args).await?; + let args = [ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + "--no-index", + "--", + null_path, + file, + ]; + let diff = run_git_capture_diff(runner, cwd, &diff_config_overrides, &args).await?; untracked_diff.push_str(&diff); } @@ -63,7 +94,7 @@ async fn run_git_capture_stdout( cwd: &Path, args: &[&str], ) -> Result { - let output = run_git_command(runner, cwd, args).await?; + let output = run_git_command(runner, cwd, &[], args).await?; if output.success() { Ok(output.stdout) } else { @@ -79,9 +110,10 @@ async fn run_git_capture_stdout( async fn run_git_capture_diff( runner: &dyn WorkspaceCommandExecutor, cwd: &Path, + config_overrides: &[(String, String)], args: &[&str], ) -> Result { - let output = run_git_command(runner, cwd, args).await?; + let output = run_git_command(runner, cwd, config_overrides, args).await?; if output.success() || output.exit_code == 1 { Ok(output.stdout) } else { @@ -92,32 +124,88 @@ async fn run_git_capture_diff( } } +/// Return Git configuration overrides that prevent configured filter drivers +/// from executing while generating diffs. +async fn diff_filter_config_overrides( + runner: &dyn WorkspaceCommandExecutor, + cwd: &Path, +) -> Result, String> { + let args = [ + "config", + "--null", + "--name-only", + "--get-regexp", + EXECUTABLE_FILTER_CONFIG_PATTERN, + ]; + let output = run_git_command(runner, cwd, &[], &args).await?; + if output.exit_code != 0 && output.exit_code != 1 { + return Err(format!( + "git {:?} failed with status {}", + args, output.exit_code + )); + } + + let mut drivers = output + .stdout + .split('\0') + .filter_map(|key| { + key.strip_suffix(".clean") + .or_else(|| key.strip_suffix(".process")) + }) + .map(str::to_string) + .collect::>(); + drivers.sort(); + drivers.dedup(); + + Ok(drivers + .into_iter() + .flat_map(|driver| { + [ + (format!("{driver}.clean"), String::new()), + (format!("{driver}.process"), String::new()), + (format!("{driver}.required"), "false".to_string()), + ] + }) + .collect()) +} + /// Determine if the current directory is inside a Git repository. async fn inside_git_repo( runner: &dyn WorkspaceCommandExecutor, cwd: &Path, ) -> Result { - let output = run_git_command(runner, cwd, &["rev-parse", "--is-inside-work-tree"]).await?; + let output = run_git_command(runner, cwd, &[], &["rev-parse", "--is-inside-work-tree"]).await?; Ok(output.success()) } async fn run_git_command( runner: &dyn WorkspaceCommandExecutor, cwd: &Path, + config_overrides: &[(String, String)], args: &[&str], ) -> Result { - let mut argv = Vec::with_capacity(args.len() + 1); + let mut argv = Vec::with_capacity(args.len() + 5); argv.push("git".to_string()); + argv.extend([ + "-c".to_string(), + DISABLE_FSMONITOR_CONFIG.to_string(), + "-c".to_string(), + DISABLE_HOOKS_CONFIG.to_string(), + ]); argv.extend(args.iter().map(|arg| (*arg).to_string())); - runner - .run( - WorkspaceCommand::new(argv) - .cwd(cwd.to_path_buf()) - .timeout(DIFF_COMMAND_TIMEOUT) - .disable_output_cap(), - ) - .await - .map_err(|err| err.to_string()) + let mut command = WorkspaceCommand::new(argv) + .cwd(cwd.to_path_buf()) + .timeout(DIFF_COMMAND_TIMEOUT) + .disable_output_cap(); + if !config_overrides.is_empty() { + command = command.env("GIT_CONFIG_COUNT", config_overrides.len().to_string()); + for (index, (key, value)) in config_overrides.iter().enumerate() { + command = command + .env(format!("GIT_CONFIG_KEY_{index}"), key) + .env(format!("GIT_CONFIG_VALUE_{index}"), value); + } + } + runner.run(command).await.map_err(|err| err.to_string()) } #[cfg(test)] @@ -125,17 +213,24 @@ mod tests { use super::*; use crate::workspace_command::WorkspaceCommandError; use pretty_assertions::assert_eq; + use std::collections::HashMap; use std::collections::VecDeque; + #[cfg(unix)] + use std::fs; use std::future::Future; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use std::pin::Pin; + #[cfg(unix)] + use std::process::Command as ProcessCommand; use std::sync::Mutex; #[tokio::test] async fn get_git_diff_returns_not_git_for_non_git_cwd() { let cwd = PathBuf::from("/workspace"); let runner = FakeRunner::new(vec![response( - &["git", "rev-parse", "--is-inside-work-tree"], + git_command(&["rev-parse", "--is-inside-work-tree"]), /*exit_code*/ 128, "", )]); @@ -145,40 +240,61 @@ mod tests { assert_eq!(result, Ok((false, String::new()))); assert_commands( &runner.commands(), - &[&["git", "rev-parse", "--is-inside-work-tree"]], + &[git_command(&["rev-parse", "--is-inside-work-tree"])], &cwd, ); } #[tokio::test] - async fn get_git_diff_concatenates_tracked_and_untracked_diffs() { + async fn get_git_diff_disables_helpers_for_tracked_and_untracked_diffs() { let cwd = PathBuf::from("/workspace"); let runner = FakeRunner::new(vec![ response( - &["git", "rev-parse", "--is-inside-work-tree"], + git_command(&["rev-parse", "--is-inside-work-tree"]), /*exit_code*/ 0, "true\n", ), response( - &["git", "diff", "--color"], + git_command(&[ + "config", + "--null", + "--name-only", + "--get-regexp", + EXECUTABLE_FILTER_CONFIG_PATTERN, + ]), + /*exit_code*/ 0, + "filter.evil.clean\0filter.evil.process\0", + ), + response( + git_command(&[ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + ]), /*exit_code*/ 1, "tracked\n", ), response( - &["git", "ls-files", "--others", "--exclude-standard"], + git_command(&["ls-files", "--others", "--exclude-standard"]), /*exit_code*/ 0, "new.txt\n", ), response( - &[ - "git", + git_command(&[ "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", "--color", "--no-index", "--", null_device(), "new.txt", - ], + ]), /*exit_code*/ 1, "untracked\n", ), @@ -187,24 +303,44 @@ mod tests { let result = get_git_diff(&runner, &cwd).await; assert_eq!(result, Ok((true, "tracked\nuntracked\n".to_string()))); + let commands = runner.commands(); assert_commands( - &runner.commands(), + &commands, &[ - &["git", "rev-parse", "--is-inside-work-tree"], - &["git", "diff", "--color"], - &["git", "ls-files", "--others", "--exclude-standard"], - &[ - "git", + git_command(&["rev-parse", "--is-inside-work-tree"]), + git_command(&[ + "config", + "--null", + "--name-only", + "--get-regexp", + EXECUTABLE_FILTER_CONFIG_PATTERN, + ]), + git_command(&[ "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + ]), + git_command(&["ls-files", "--others", "--exclude-standard"]), + git_command(&[ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", "--color", "--no-index", "--", null_device(), "new.txt", - ], + ]), ], &cwd, ); + assert_eq!(commands[2].env, filter_override_env("filter.evil")); + assert_eq!(commands[4].env, filter_override_env("filter.evil")); } #[tokio::test] @@ -212,17 +348,35 @@ mod tests { let cwd = PathBuf::from("/workspace"); let runner = FakeRunner::new(vec![ response( - &["git", "rev-parse", "--is-inside-work-tree"], + git_command(&["rev-parse", "--is-inside-work-tree"]), /*exit_code*/ 0, "true\n", ), response( - &["git", "diff", "--color"], + git_command(&[ + "config", + "--null", + "--name-only", + "--get-regexp", + EXECUTABLE_FILTER_CONFIG_PATTERN, + ]), + /*exit_code*/ 1, + "", + ), + response( + git_command(&[ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + ]), /*exit_code*/ 1, "tracked\n", ), response( - &["git", "ls-files", "--others", "--exclude-standard"], + git_command(&["ls-files", "--others", "--exclude-standard"]), /*exit_code*/ 0, "", ), @@ -238,13 +392,35 @@ mod tests { let cwd = PathBuf::from("/workspace"); let runner = FakeRunner::new(vec![ response( - &["git", "rev-parse", "--is-inside-work-tree"], + git_command(&["rev-parse", "--is-inside-work-tree"]), /*exit_code*/ 0, "true\n", ), - response(&["git", "diff", "--color"], /*exit_code*/ 2, ""), response( - &["git", "ls-files", "--others", "--exclude-standard"], + git_command(&[ + "config", + "--null", + "--name-only", + "--get-regexp", + EXECUTABLE_FILTER_CONFIG_PATTERN, + ]), + /*exit_code*/ 1, + "", + ), + response( + git_command(&[ + "diff", + "--no-textconv", + "--no-ext-diff", + "--submodule=short", + "--ignore-submodules=dirty", + "--color", + ]), + /*exit_code*/ 2, + "", + ), + response( + git_command(&["ls-files", "--others", "--exclude-standard"]), /*exit_code*/ 0, "", ), @@ -255,14 +431,180 @@ mod tests { .expect_err("unexpected git diff status should fail"); assert!( - error.contains("git [\"diff\", \"--color\"] failed with status 2"), + error.contains( + "git [\"diff\", \"--no-textconv\", \"--no-ext-diff\", \"--submodule=short\", \"--ignore-submodules=dirty\", \"--color\"] failed with status 2" + ), "unexpected error: {error}", ); } - fn response(argv: &[&str], exit_code: i32, stdout: &str) -> FakeResponse { + #[cfg(unix)] + #[tokio::test] + async fn get_git_diff_does_not_execute_configured_filters_fsmonitor_or_hooks() { + let tempdir = tempfile::tempdir().expect("create temp directory"); + let repo = tempdir.path().join("repo"); + fs::create_dir(&repo).expect("create test repository directory"); + run_git_setup(&repo, &["init", "-q"]); + run_git_setup(&repo, &["config", "user.name", "test"]); + run_git_setup(&repo, &["config", "user.email", "test@example.com"]); + fs::write(repo.join(".gitattributes"), "*.txt filter=x=y\n").expect("write attributes"); + fs::write(repo.join("tracked.txt"), "before\n").expect("write tracked file"); + fs::write(repo.join("unchanged.txt"), "unchanged\n").expect("write unchanged file"); + run_git_setup( + &repo, + &["add", ".gitattributes", "tracked.txt", "unchanged.txt"], + ); + run_git_setup(&repo, &["commit", "-qm", "initial"]); + + let filter_helper = tempdir.path().join("filter-helper.sh"); + let fsmonitor_helper = tempdir.path().join("fsmonitor-helper.sh"); + let hooks_dir = tempdir.path().join("hooks"); + let hook_helper = hooks_dir.join("post-index-change"); + fs::create_dir(&hooks_dir).expect("create hooks directory"); + write_marker_helper(&filter_helper); + write_marker_helper(&fsmonitor_helper); + write_marker_helper(&hook_helper); + run_git_setup( + &repo, + &[ + "config", + "filter.x=y.clean", + filter_helper.to_str().expect("filter helper path"), + ], + ); + run_git_setup( + &repo, + &[ + "config", + "filter.x=y.process", + filter_helper.to_str().expect("filter helper path"), + ], + ); + run_git_setup(&repo, &["config", "filter.x=y.required", "true"]); + run_git_setup( + &repo, + &[ + "config", + "core.fsmonitor", + fsmonitor_helper.to_str().expect("fsmonitor helper path"), + ], + ); + run_git_setup( + &repo, + &[ + "config", + "core.hooksPath", + hooks_dir.to_str().expect("hooks directory path"), + ], + ); + std::thread::sleep(Duration::from_secs(/*secs*/ 1)); + fs::write(repo.join("unchanged.txt"), "unchanged\n").expect("refresh unchanged file"); + fs::write(repo.join("tracked.txt"), "after\n").expect("modify tracked file"); + + let result = get_git_diff(&LocalRunner, &repo) + .await + .expect("generate diff without invoking helpers"); + + assert!(result.1.contains("before")); + assert!(result.1.contains("after")); + assert!(!filter_helper.with_extension("sh.ran").exists()); + assert!(!fsmonitor_helper.with_extension("sh.ran").exists()); + assert!(!hook_helper.with_extension("sh.ran").exists()); + } + + #[cfg(unix)] + #[tokio::test] + async fn get_git_diff_does_not_execute_helpers_while_checking_dirty_submodules() { + let tempdir = tempfile::tempdir().expect("create temp directory"); + let child = tempdir.path().join("child"); + let repo = tempdir.path().join("repo"); + fs::create_dir(&child).expect("create child repository directory"); + fs::create_dir(&repo).expect("create parent repository directory"); + run_git_setup(&child, &["init", "-q"]); + run_git_setup(&child, &["config", "user.name", "test"]); + run_git_setup(&child, &["config", "user.email", "test@example.com"]); + fs::write(child.join(".gitattributes"), "*.txt filter=evil\n") + .expect("write child attributes"); + fs::write(child.join("tracked.txt"), "before\n").expect("write child tracked file"); + run_git_setup(&child, &["add", ".gitattributes", "tracked.txt"]); + run_git_setup(&child, &["commit", "-qm", "initial"]); + + run_git_setup(&repo, &["init", "-q"]); + run_git_setup(&repo, &["config", "user.name", "test"]); + run_git_setup(&repo, &["config", "user.email", "test@example.com"]); + run_git_setup( + &repo, + &[ + "-c", + "protocol.file.allow=always", + "submodule", + "add", + "-q", + child.to_str().expect("child repository path"), + "child", + ], + ); + run_git_setup(&repo, &["commit", "-qm", "add submodule"]); + + let helper = tempdir.path().join("submodule-helper.sh"); + write_marker_helper(&helper); + let checkout = repo.join("child"); + run_git_setup( + &checkout, + &[ + "config", + "filter.evil.clean", + helper.to_str().expect("submodule helper path"), + ], + ); + run_git_setup(&checkout, &["config", "filter.evil.required", "true"]); + std::thread::sleep(Duration::from_secs(/*secs*/ 1)); + fs::write(checkout.join("tracked.txt"), "before\n").expect("refresh child tracked file"); + + let result = get_git_diff(&LocalRunner, &repo) + .await + .expect("generate diff without inspecting submodule worktrees"); + + assert!(result.1.is_empty()); + assert!(!helper.with_extension("sh.ran").exists()); + } + + fn git_command(args: &[&str]) -> Vec { + let mut argv = vec![ + "git".to_string(), + "-c".to_string(), + DISABLE_FSMONITOR_CONFIG.to_string(), + "-c".to_string(), + DISABLE_HOOKS_CONFIG.to_string(), + ]; + argv.extend(args.iter().map(|arg| (*arg).to_string())); + argv + } + + fn filter_override_env(driver: &str) -> HashMap> { + HashMap::from([ + ("GIT_CONFIG_COUNT".to_string(), Some("3".to_string())), + ( + "GIT_CONFIG_KEY_0".to_string(), + Some(format!("{driver}.clean")), + ), + ("GIT_CONFIG_VALUE_0".to_string(), Some(String::new())), + ( + "GIT_CONFIG_KEY_1".to_string(), + Some(format!("{driver}.process")), + ), + ("GIT_CONFIG_VALUE_1".to_string(), Some(String::new())), + ( + "GIT_CONFIG_KEY_2".to_string(), + Some(format!("{driver}.required")), + ), + ("GIT_CONFIG_VALUE_2".to_string(), Some("false".to_string())), + ]) + } + + fn response(argv: Vec, exit_code: i32, stdout: &str) -> FakeResponse { FakeResponse { - argv: argv.iter().map(|arg| (*arg).to_string()).collect(), + argv, output: WorkspaceCommandOutput { exit_code, stdout: stdout.to_string(), @@ -275,15 +617,32 @@ mod tests { if cfg!(windows) { "NUL" } else { "/dev/null" } } - fn assert_commands(commands: &[WorkspaceCommand], expected: &[&[&str]], cwd: &Path) { + #[cfg(unix)] + fn run_git_setup(cwd: &Path, args: &[&str]) { + let status = ProcessCommand::new("git") + .args(args) + .current_dir(cwd) + .status() + .expect("run git setup command"); + assert!(status.success(), "git setup command failed: {args:?}"); + } + + #[cfg(unix)] + fn write_marker_helper(path: &Path) { + fs::write(path, "#!/bin/sh\nprintf ran >> \"$0.ran\"\nexit 1\n") + .expect("write helper script"); + let mut permissions = fs::metadata(path) + .expect("read helper metadata") + .permissions(); + permissions.set_mode(/*mode*/ 0o755); + fs::set_permissions(path, permissions).expect("make helper executable"); + } + + fn assert_commands(commands: &[WorkspaceCommand], expected: &[Vec], cwd: &Path) { let actual: Vec> = commands .iter() .map(|command| command.argv.clone()) .collect(); - let expected: Vec> = expected - .iter() - .map(|argv| argv.iter().map(|arg| (*arg).to_string()).collect()) - .collect(); assert_eq!(actual, expected); for command in commands { @@ -336,4 +695,44 @@ mod tests { }) } } + + #[cfg(unix)] + struct LocalRunner; + + #[cfg(unix)] + impl WorkspaceCommandExecutor for LocalRunner { + fn run( + &self, + command: WorkspaceCommand, + ) -> Pin< + Box< + dyn Future> + + Send + + '_, + >, + > { + Box::pin(async move { + let mut process = ProcessCommand::new(&command.argv[0]); + process + .args(&command.argv[1..]) + .current_dir(command.cwd.expect("test command cwd")); + for (key, value) in command.env { + match value { + Some(value) => { + process.env(key, value); + } + None => { + process.env_remove(key); + } + } + } + let output = process.output().expect("run test command"); + Ok(WorkspaceCommandOutput { + exit_code: output.status.code().expect("test command exit code"), + stdout: String::from_utf8(output.stdout).expect("utf8 stdout"), + stderr: String::from_utf8(output.stderr).expect("utf8 stderr"), + }) + }) + } + } } diff --git a/codex-rs/tui/src/history_cell/hook_cell.rs b/codex-rs/tui/src/history_cell/hook_cell.rs index 6a4e8498d9..c3214aeb16 100644 --- a/codex-rs/tui/src/history_cell/hook_cell.rs +++ b/codex-rs/tui/src/history_cell/hook_cell.rs @@ -48,6 +48,9 @@ const HOOK_RUN_REVEAL_DELAY: Duration = Duration::from_millis(300); /// enough to read instead of removing it immediately when the success event arrives. const QUIET_HOOK_MIN_VISIBLE: Duration = Duration::from_millis(600); +const HOOK_OUTPUT_INDENT: &str = " "; +const HOOK_OUTPUT_BODY_INDENT: &str = " "; + #[derive(Debug)] struct HookRunCell { /// Stable protocol id used to match begin/end updates for the same hook invocation. @@ -443,10 +446,18 @@ impl HookRunCell { .into(), ); for entry in entries { - // Output entries are already short hook-authored strings; keep their prefixes - // explicit so warnings/stops/errors remain easy to scan in history. - lines - .push(format!(" {}{}", hook_output_prefix(entry.kind), entry.text).into()); + let prefix = hook_output_prefix(entry.kind); + let mut output_lines = entry.text.split('\n'); + if let Some(first_line) = output_lines.next() { + lines.push(format!("{HOOK_OUTPUT_INDENT}{prefix}{first_line}").into()); + } + for line in output_lines { + if line.is_empty() { + lines.push("".into()); + } else { + lines.push(format!("{HOOK_OUTPUT_BODY_INDENT}{line}").into()); + } + } } } HookRunState::PendingReveal { .. } => {} @@ -748,6 +759,50 @@ mod tests { assert!(bullet.style.add_modifier.contains(Modifier::BOLD)); } + #[test] + fn completed_hook_multiline_context_preserves_display_and_raw_lines() { + let cell = completed_hook_cell( + HookEventName::SessionStart, + HookRunStatus::Completed, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Context, + text: "## Working Memory Recall\n\nSource: Codex compaction\nScope: Durable workspace memory" + .to_string(), + }], + ); + let expected = vec![ + "• SessionStart hook (completed)".to_string(), + " hook context: ## Working Memory Recall".to_string(), + "".to_string(), + " Source: Codex compaction".to_string(), + " Scope: Durable workspace memory".to_string(), + ]; + + assert_eq!(line_texts(&cell.display_lines(/*width*/ 80)), expected); + assert_eq!(line_texts(&cell.raw_lines()), expected); + } + + #[test] + fn completed_hook_multiline_warning_prefixes_first_line_only() { + let cell = completed_hook_cell( + HookEventName::PostToolUse, + HookRunStatus::Completed, + vec![HookOutputEntry { + kind: HookOutputEntryKind::Warning, + text: "Heads up\nReview generated files".to_string(), + }], + ); + + assert_eq!( + line_texts(&cell.display_lines(/*width*/ 80)), + vec![ + "• PostToolUse hook (completed)".to_string(), + " warning: Heads up".to_string(), + " Review generated files".to_string(), + ] + ); + } + #[test] fn pending_hook_does_not_animate_transcript() { let cell = @@ -790,12 +845,7 @@ mod tests { let rendered: Vec = cell .display_lines(/*width*/ 80) .iter() - .map(|line| { - line.spans - .iter() - .map(|span| span.content.as_ref()) - .collect::() - }) + .map(line_text) .collect(); assert_eq!( @@ -804,6 +854,32 @@ mod tests { ); } + fn completed_hook_cell( + event_name: HookEventName, + status: HookRunStatus, + entries: Vec, + ) -> HookCell { + let mut run = hook_run_summary("hook-1"); + run.event_name = event_name; + run.status = status; + run.status_message = None; + run.completed_at = Some(2); + run.duration_ms = Some(1); + run.entries = entries; + HookCell::new_completed(run, /*animations_enabled*/ false) + } + + fn line_texts(lines: &[Line<'_>]) -> Vec { + lines.iter().map(line_text).collect() + } + + fn line_text(line: &Line<'_>) -> String { + line.spans + .iter() + .map(|span| span.content.as_ref()) + .collect::() + } + fn hook_run_summary(id: &str) -> HookRunSummary { HookRunSummary { id: id.to_string(), diff --git a/codex-rs/tui/src/history_cell/search.rs b/codex-rs/tui/src/history_cell/search.rs index d75ac50fdc..5373f68ec2 100644 --- a/codex-rs/tui/src/history_cell/search.rs +++ b/codex-rs/tui/src/history_cell/search.rs @@ -4,7 +4,7 @@ use super::*; fn web_search_header(completed: bool) -> &'static str { if completed { - "Searched" + "Searched the web" } else { "Searching the web" } @@ -104,7 +104,8 @@ impl HistoryCell for WebSearchCell { let text: Text<'static> = if detail.is_empty() { Line::from(vec![header.bold()]).into() } else { - Line::from(vec![header.bold(), " ".into(), detail.into()]).into() + let separator = if self.completed { " for " } else { " " }; + Line::from(vec![header.bold(), separator.into(), detail.into()]).into() }; PrefixedWrappedHistoryCell::new(text, vec![bullet, " ".into()], " ").display_lines(width) } @@ -115,7 +116,8 @@ impl HistoryCell for WebSearchCell { if detail.is_empty() { vec![Line::from(header)] } else { - vec![Line::from(format!("{header} {detail}"))] + let separator = if self.completed { " for " } else { " " }; + vec![Line::from(format!("{header}{separator}{detail}"))] } } } diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_snapshot.snap index e119420f18..2a4e8b3abb 100644 --- a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_snapshot.snap +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_snapshot.snap @@ -2,5 +2,5 @@ source: tui/src/history_cell.rs expression: rendered --- -• Searched example search query with several generic words to - exercise wrapping +• Searched the web for example search query with several generic + words to exercise wrapping diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_transcript_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_transcript_snapshot.snap index e119420f18..2a4e8b3abb 100644 --- a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_transcript_snapshot.snap +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_transcript_snapshot.snap @@ -2,5 +2,5 @@ source: tui/src/history_cell.rs expression: rendered --- -• Searched example search query with several generic words to - exercise wrapping +• Searched the web for example search query with several generic + words to exercise wrapping diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_without_detail_snapshot.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_without_detail_snapshot.snap new file mode 100644 index 0000000000..ffda6cb13f --- /dev/null +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__tests__web_search_history_cell_without_detail_snapshot.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/history_cell.rs +expression: rendered +--- +• Searched the web diff --git a/codex-rs/tui/src/history_cell/tests.rs b/codex-rs/tui/src/history_cell/tests.rs index b4674cec8a..63a04d19d4 100644 --- a/codex-rs/tui/src/history_cell/tests.rs +++ b/codex-rs/tui/src/history_cell/tests.rs @@ -843,6 +843,7 @@ async fn mcp_tools_output_lists_tools_for_hyphenated_server_names() { fn mcp_tools_output_from_statuses_renders_status_only_servers() { let statuses = vec![McpServerStatus { name: "plugin_docs".to_string(), + server_info: None, tools: HashMap::from([( "lookup".to_string(), Tool { @@ -872,6 +873,7 @@ fn mcp_tools_output_from_statuses_renders_status_only_servers() { fn mcp_tools_output_from_statuses_renders_verbose_inventory() { let statuses = vec![McpServerStatus { name: "plugin_docs".to_string(), + server_info: None, tools: HashMap::from([( "lookup".to_string(), Tool { @@ -1082,6 +1084,14 @@ fn standalone_windows_update_available_history_cell_snapshot() { insta::assert_snapshot!(rendered); } +#[test] +fn web_search_history_cell_without_detail_snapshot() { + let cell = new_web_search_call("call-1".to_string(), String::new(), WebSearchAction::Other); + let rendered = render_lines(&cell.display_lines(/*width*/ 64)).join("\n"); + + insta::assert_snapshot!(rendered); +} + #[test] fn web_search_history_cell_wraps_with_indented_continuation() { let query = "example search query with several generic words to exercise wrapping".to_string(); @@ -1098,8 +1108,8 @@ fn web_search_history_cell_wraps_with_indented_continuation() { assert_eq!( rendered, vec![ - "• Searched example search query with several generic words to".to_string(), - " exercise wrapping".to_string(), + "• Searched the web for example search query with several generic".to_string(), + " words to exercise wrapping".to_string(), ] ); } @@ -1117,7 +1127,10 @@ fn web_search_history_cell_short_query_does_not_wrap() { ); let rendered = render_lines(&cell.display_lines(/*width*/ 64)); - assert_eq!(rendered, vec!["• Searched short query".to_string()]); + assert_eq!( + rendered, + vec!["• Searched the web for short query".to_string()] + ); } #[test] diff --git a/codex-rs/tui/src/mention_codec.rs b/codex-rs/tui/src/mention_codec.rs index f6cd38bd4f..520a6712ea 100644 --- a/codex-rs/tui/src/mention_codec.rs +++ b/codex-rs/tui/src/mention_codec.rs @@ -6,6 +6,7 @@ use codex_utils_plugins::mention_syntax::TOOL_MENTION_SIGIL; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct LinkedMention { + pub(crate) sigil: char, pub(crate) mention: String, pub(crate) path: String, } @@ -22,10 +23,16 @@ pub(crate) fn encode_history_mentions(text: &str, mentions: &[LinkedMention]) -> return text.to_string(); } - let mut mentions_by_name: HashMap<&str, VecDeque<&str>> = HashMap::new(); + let mut mentions_by_token: HashMap<(char, &str), VecDeque<&str>> = HashMap::new(); for mention in mentions { - mentions_by_name - .entry(mention.mention.as_str()) + if !matches!( + mention.sigil, + TOOL_MENTION_SIGIL | PLUGIN_TEXT_MENTION_SIGIL + ) { + continue; + } + mentions_by_token + .entry((mention.sigil, mention.mention.as_str())) .or_default() .push_back(mention.path.as_str()); } @@ -35,28 +42,38 @@ pub(crate) fn encode_history_mentions(text: &str, mentions: &[LinkedMention]) -> let mut index = 0usize; while index < bytes.len() { - if bytes[index] == TOOL_MENTION_SIGIL as u8 { - let name_start = index + 1; - if let Some(first) = bytes.get(name_start) - && is_mention_name_char(*first) - { - let mut name_end = name_start + 1; - while let Some(next) = bytes.get(name_end) - && is_mention_name_char(*next) + if matches!( + bytes[index], + byte if byte == TOOL_MENTION_SIGIL as u8 || byte == PLUGIN_TEXT_MENTION_SIGIL as u8 + ) { + let sigil = bytes[index] as char; + if sigil == TOOL_MENTION_SIGIL || starts_plaintext_mention(text, index) { + let name_start = index + 1; + if let Some(first) = bytes.get(name_start) + && is_mention_name_char(*first) { - name_end += 1; - } + let mut name_end = name_start + 1; + while let Some(next) = bytes.get(name_end) + && is_mention_name_char(*next) + { + name_end += 1; + } - let name = &text[name_start..name_end]; - if let Some(path) = mentions_by_name.get_mut(name).and_then(VecDeque::pop_front) { - out.push('['); - out.push(TOOL_MENTION_SIGIL); - out.push_str(name); - out.push_str("]("); - out.push_str(path); - out.push(')'); - index = name_end; - continue; + let name = &text[name_start..name_end]; + if (sigil == TOOL_MENTION_SIGIL || ends_plaintext_mention(bytes, name_end)) + && let Some(path) = mentions_by_token + .get_mut(&(sigil, name)) + .and_then(VecDeque::pop_front) + { + out.push('['); + out.push(sigil); + out.push_str(name); + out.push_str("]("); + out.push_str(path); + out.push(')'); + index = name_end; + continue; + } } } } @@ -71,7 +88,10 @@ pub(crate) fn encode_history_mentions(text: &str, mentions: &[LinkedMention]) -> out } -pub(crate) fn decode_history_mentions(text: &str) -> DecodedHistoryText { +pub(crate) fn decode_history_mentions_with_at_mentions( + text: &str, + at_mentions_enabled: bool, +) -> DecodedHistoryText { let bytes = text.as_bytes(); let mut out = String::with_capacity(text.len()); let mut mentions = Vec::new(); @@ -79,11 +99,13 @@ pub(crate) fn decode_history_mentions(text: &str) -> DecodedHistoryText { while index < bytes.len() { if bytes[index] == b'[' - && let Some((name, path, end_index)) = parse_history_linked_mention(text, bytes, index) + && let Some((sigil, name, path, end_index)) = + parse_history_linked_mention(text, bytes, index, at_mentions_enabled) { - out.push(TOOL_MENTION_SIGIL); + out.push(sigil); out.push_str(name); mentions.push(LinkedMention { + sigil, mention: name.to_string(), path: path.to_string(), }); @@ -108,22 +130,32 @@ fn parse_history_linked_mention<'a>( text: &'a str, text_bytes: &[u8], start: usize, -) -> Option<(&'a str, &'a str, usize)> { - // TUI writes `$name`, but may read plugin `[@name](plugin://...)` links from other clients. - if let Some(mention @ (name, path, _)) = + at_mentions_enabled: bool, +) -> Option<(char, &'a str, &'a str, usize)> { + // TUI historically wrote `$name`, but selected unified `@` mentions should preserve `@` on + // history round-trip for any canonical tool path. + if let Some((name, path, end_index)) = parse_linked_tool_mention(text, text_bytes, start, TOOL_MENTION_SIGIL) && !is_common_env_var(name) && is_tool_path(path) { - return Some(mention); + return Some((TOOL_MENTION_SIGIL, name, path, end_index)); } - if let Some(mention @ (name, path, _)) = + if at_mentions_enabled { + if let Some((name, path, end_index)) = + parse_linked_tool_mention(text, text_bytes, start, PLUGIN_TEXT_MENTION_SIGIL) + && !is_common_env_var(name) + && is_tool_path(path) + { + return Some((PLUGIN_TEXT_MENTION_SIGIL, name, path, end_index)); + } + } else if let Some((name, path, end_index)) = parse_linked_tool_mention(text, text_bytes, start, PLUGIN_TEXT_MENTION_SIGIL) && !is_common_env_var(name) && path.starts_with("plugin://") { - return Some(mention); + return Some((TOOL_MENTION_SIGIL, name, path, end_index)); } None @@ -190,6 +222,35 @@ fn is_mention_name_char(byte: u8) -> bool { matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-') } +fn starts_plaintext_mention(text: &str, index: usize) -> bool { + if index == 0 { + return true; + } + + text.get(..index) + .and_then(|prefix| prefix.chars().next_back()) + .is_some_and(|ch| ch.is_whitespace() || !is_mention_name_char_char(ch)) +} + +fn ends_plaintext_mention(text_bytes: &[u8], index: usize) -> bool { + text_bytes.get(index).is_none_or(|byte| { + byte.is_ascii_whitespace() + || *byte == b'.' + && text_bytes.get(index + 1).is_none_or(|next| { + next.is_ascii_whitespace() + || !next.is_ascii_alphanumeric() && *next != b'_' && *next != b'-' + }) + || !matches!(*byte, b'.' | b'/' | b'\\') + && !byte.is_ascii_alphanumeric() + && *byte != b'_' + && *byte != b'-' + }) +} + +fn is_mention_name_char_char(ch: char) -> bool { + ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') +} + fn is_common_env_var(name: &str) -> bool { let upper = name.to_ascii_uppercase(); matches!( @@ -226,22 +287,26 @@ mod tests { #[test] fn decode_history_mentions_restores_visible_tokens() { - let decoded = decode_history_mentions( + let decoded = decode_history_mentions_with_at_mentions( "Use [$figma](app://figma-1), [$sample](plugin://sample@test), and [$figma](/tmp/figma/SKILL.md).", + /*at_mentions_enabled*/ true, ); assert_eq!(decoded.text, "Use $figma, $sample, and $figma."); assert_eq!( decoded.mentions, vec![ LinkedMention { + sigil: '$', mention: "figma".to_string(), path: "app://figma-1".to_string(), }, LinkedMention { + sigil: '$', mention: "sample".to_string(), path: "plugin://sample@test".to_string(), }, LinkedMention { + sigil: '$', mention: "figma".to_string(), path: "/tmp/figma/SKILL.md".to_string(), }, @@ -251,18 +316,21 @@ mod tests { #[test] fn decode_history_mentions_restores_plugin_links_with_at_sigil() { - let decoded = decode_history_mentions( + let decoded = decode_history_mentions_with_at_mentions( "Use [@sample](plugin://sample@test) and [$figma](app://figma-1).", + /*at_mentions_enabled*/ true, ); - assert_eq!(decoded.text, "Use $sample and $figma."); + assert_eq!(decoded.text, "Use @sample and $figma."); assert_eq!( decoded.mentions, vec![ LinkedMention { + sigil: '@', mention: "sample".to_string(), path: "plugin://sample@test".to_string(), }, LinkedMention { + sigil: '$', mention: "figma".to_string(), path: "app://figma-1".to_string(), }, @@ -271,13 +339,58 @@ mod tests { } #[test] - fn decode_history_mentions_ignores_at_sigil_for_non_plugin_paths() { - let decoded = decode_history_mentions("Use [@figma](app://figma-1)."); + fn decode_history_mentions_without_at_mentions_uses_legacy_plugin_fallback() { + let decoded = decode_history_mentions_with_at_mentions( + "Use [@sample](plugin://sample@test) and [$figma](app://figma-1).", + /*at_mentions_enabled*/ false, + ); + assert_eq!(decoded.text, "Use $sample and $figma."); + assert_eq!( + decoded.mentions, + vec![ + LinkedMention { + sigil: '$', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }, + LinkedMention { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma-1".to_string(), + }, + ] + ); + } + + #[test] + fn decode_history_mentions_without_at_mentions_ignores_at_non_plugin_paths() { + let decoded = decode_history_mentions_with_at_mentions( + "Use [@figma](app://figma-1).", + /*at_mentions_enabled*/ false, + ); assert_eq!(decoded.text, "Use [@figma](app://figma-1)."); assert_eq!(decoded.mentions, Vec::::new()); } + #[test] + fn decode_history_mentions_restores_at_sigil_for_tool_paths() { + let decoded = decode_history_mentions_with_at_mentions( + "Use [@figma](app://figma-1).", + /*at_mentions_enabled*/ true, + ); + + assert_eq!(decoded.text, "Use @figma."); + assert_eq!( + decoded.mentions, + vec![LinkedMention { + sigil: '@', + mention: "figma".to_string(), + path: "app://figma-1".to_string(), + }] + ); + } + #[test] fn encode_history_mentions_links_bound_mentions_in_order() { let text = "$figma then $sample then $figma then $other"; @@ -285,14 +398,17 @@ mod tests { text, &[ LinkedMention { + sigil: '$', mention: "figma".to_string(), path: "app://figma-app".to_string(), }, LinkedMention { + sigil: '$', mention: "sample".to_string(), path: "plugin://sample@test".to_string(), }, LinkedMention { + sigil: '$', mention: "figma".to_string(), path: "/tmp/figma/SKILL.md".to_string(), }, @@ -303,4 +419,161 @@ mod tests { "[$figma](app://figma-app) then [$sample](plugin://sample@test) then [$figma](/tmp/figma/SKILL.md) then $other" ); } + + #[test] + fn encode_history_mentions_links_dollar_mentions_after_punctuation() { + let encoded = encode_history_mentions( + "($figma)", + &[LinkedMention { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }], + ); + assert_eq!(encoded, "([$figma](app://figma))"); + } + + #[test] + fn encode_history_mentions_links_dollar_mentions_with_path_like_suffixes() { + let mention = LinkedMention { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }; + + assert_eq!( + encode_history_mentions("$figma/docs", std::slice::from_ref(&mention)), + "[$figma](app://figma)/docs" + ); + assert_eq!( + encode_history_mentions("$figma.suffix", std::slice::from_ref(&mention)), + "[$figma](app://figma).suffix" + ); + assert_eq!( + encode_history_mentions("$figma\\docs", &[mention]), + "[$figma](app://figma)\\docs" + ); + } + + #[test] + fn encode_history_mentions_preserves_at_sigils() { + let text = "@figma then @sample then $other"; + let encoded = encode_history_mentions( + text, + &[ + LinkedMention { + sigil: '@', + mention: "figma".to_string(), + path: "/tmp/figma/SKILL.md".to_string(), + }, + LinkedMention { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }, + ], + ); + assert_eq!( + encoded, + "[@figma](/tmp/figma/SKILL.md) then [@sample](plugin://sample@test) then $other" + ); + } + + #[test] + fn encode_history_mentions_links_both_sigils_for_same_name() { + let text = "@figma then $figma"; + let encoded = encode_history_mentions( + text, + &[ + LinkedMention { + sigil: '@', + mention: "figma".to_string(), + path: "plugin://figma@test".to_string(), + }, + LinkedMention { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma".to_string(), + }, + ], + ); + assert_eq!( + encoded, + "[@figma](plugin://figma@test) then [$figma](app://figma)" + ); + } + + #[test] + fn encode_history_mentions_does_not_let_at_token_steal_later_tool_binding() { + let text = "@figma then $figma"; + let encoded = encode_history_mentions( + text, + &[LinkedMention { + sigil: '$', + mention: "figma".to_string(), + path: "app://figma-app".to_string(), + }], + ); + assert_eq!(encoded, "@figma then [$figma](app://figma-app)"); + } + + #[test] + fn encode_history_mentions_links_at_mentions_after_unicode_whitespace() { + // Fix coverage: full-width space should remain a valid plaintext boundary for `@` links. + let text = "foo @sample"; + let encoded = encode_history_mentions( + text, + &[LinkedMention { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + assert_eq!(encoded, "foo [@sample](plugin://sample@test)"); + } + + #[test] + fn encode_history_mentions_links_sentence_ending_at_mentions() { + let text = "Please ask @figma."; + let encoded = encode_history_mentions( + text, + &[LinkedMention { + sigil: '@', + mention: "figma".to_string(), + path: "/tmp/figma/SKILL.md".to_string(), + }], + ); + assert_eq!(encoded, "Please ask [@figma](/tmp/figma/SKILL.md)."); + } + + #[test] + fn encode_history_mentions_links_parenthesized_at_mentions() { + let text = "Please ask (@figma)"; + let encoded = encode_history_mentions( + text, + &[LinkedMention { + sigil: '@', + mention: "figma".to_string(), + path: "plugin://figma@test".to_string(), + }], + ); + assert_eq!(encoded, "Please ask ([@figma](plugin://figma@test))"); + } + + #[test] + fn encode_history_mentions_skips_embedded_at_substrings() { + let text = "foo@sample.com npx @sample/pkg then @sample"; + let encoded = encode_history_mentions( + text, + &[LinkedMention { + sigil: '@', + mention: "sample".to_string(), + path: "plugin://sample@test".to_string(), + }], + ); + assert_eq!( + encoded, + "foo@sample.com npx @sample/pkg then [@sample](plugin://sample@test)" + ); + } } diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 6e8b65decd..2d8619d539 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -5781,6 +5781,7 @@ session_picker_view = "dense" items: vec![ ThreadItem::UserMessage { id: String::from("user-1"), + client_id: None, content: vec![codex_app_server_protocol::UserInput::Text { text: String::from("hello from user"), text_elements: Vec::new(), diff --git a/codex-rs/tui/src/resume_picker/transcript.rs b/codex-rs/tui/src/resume_picker/transcript.rs index 5dbc7707c2..abf13bd144 100644 --- a/codex-rs/tui/src/resume_picker/transcript.rs +++ b/codex-rs/tui/src/resume_picker/transcript.rs @@ -45,9 +45,14 @@ pub(crate) fn thread_to_transcript_cells( let mut cells: TranscriptCells = Vec::new(); for item in thread.turns.iter().flat_map(|turn| turn.items.iter()) { match item { - ThreadItem::UserMessage { id, content } => { + ThreadItem::UserMessage { + id, + client_id, + content, + } => { let item = UserMessageItem { id: id.clone(), + client_id: client_id.clone(), content: content .iter() .cloned() diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 4a43409296..3fccdf5967 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -30,6 +30,7 @@ pub enum SlashCommand { Review, Rename, New, + Archive, Resume, Fork, Init, @@ -86,6 +87,7 @@ impl SlashCommand { SlashCommand::Review => "review my current changes and find issues", SlashCommand::Rename => "rename the current thread", SlashCommand::Resume => "resume a saved chat", + SlashCommand::Archive => "archive this session and exit", SlashCommand::Clear => "clear the terminal and start a new chat", SlashCommand::Fork => "fork the current chat", SlashCommand::Quit | SlashCommand::Exit => "exit Codex", @@ -180,6 +182,7 @@ impl SlashCommand { pub fn available_during_task(self) -> bool { match self { SlashCommand::New + | SlashCommand::Archive | SlashCommand::Resume | SlashCommand::Fork | SlashCommand::Init diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index 8da9166a3b..0117508ae5 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -682,13 +682,14 @@ fn status_approval_label( approvals_reviewer: ApprovalsReviewer, approval: &str, ) -> String { - if approval_policy == AskForApproval::OnRequest - && approvals_reviewer == ApprovalsReviewer::AutoReview - { - "auto-review".to_string() - } else { - approval.to_string() + if approval_policy == AskForApproval::OnRequest { + return match approvals_reviewer { + ApprovalsReviewer::AutoReview => "Approve for me".to_string(), + ApprovalsReviewer::User => "Ask for approval".to_string(), + }; } + + approval.to_string() } impl HistoryCell for StatusHistoryCell { diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap index 6293c0d742..c7d89b17aa 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap @@ -4,20 +4,20 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 1.05K total (700 input + 350 output) │ -│ Context window: 100% left (1.45K used / 272K) │ -│ 5h limit: [████████░░░░░░░░░░░░] 40% left (resets 11:32) │ -│ Weekly limit: [█████████████░░░░░░░] 65% left (resets 11:52) │ -│ Warning: limits may be stale - start new turn to refresh. │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 1.05K total (700 input + 350 output) │ +│ Context window: 100% left (1.45K used / 272K) │ +│ 5h limit: [████████░░░░░░░░░░░░] 40% left (resets 11:32) │ +│ Weekly limit: [█████████████░░░░░░░] 65% left (resets 11:52) │ +│ Warning: limits may be stale - start new turn to refresh. │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap index 0c8dae72cf..48fa575d1f 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap @@ -4,20 +4,20 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 2K total (1.4K input + 600 output) │ -│ Context window: 100% left (2.2K used / 272K) │ -│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 09:25) │ -│ Weekly limit: [██████████████░░░░░░] 70% left (resets 09:55) │ -│ Credits: 38 credits │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 2K total (1.4K input + 600 output) │ +│ Context window: 100% left (2.2K used / 272K) │ +│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 09:25) │ +│ Weekly limit: [██████████████░░░░░░] 70% left (resets 09:55) │ +│ Credits: 38 credits │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap index f884d006ab..152575179e 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_forked_from.snap @@ -4,20 +4,20 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ Session: 0f0f3c13-6cf9-4aa4-8b80-7d49c2f1be2e │ -│ Forked from: e9f18a88-8081-4e51-9d4e-8af5cde2d8dd │ -│ │ -│ Token usage: 1.2K total (800 input + 400 output) │ -│ Context window: 100% left (1.2K used / 272K) │ -│ Limits: data not available yet │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ Session: 0f0f3c13-6cf9-4aa4-8b80-7d49c2f1be2e │ +│ Forked from: e9f18a88-8081-4e51-9d4e-8af5cde2d8dd │ +│ │ +│ Token usage: 1.2K total (800 input + 400 output) │ +│ Context window: 100% left (1.2K used / 272K) │ +│ Limits: data not available yet │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap index fc691f6bf7..7a4f58a823 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap @@ -4,18 +4,18 @@ expression: sanitized --- /status -╭────────────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 1.2K total (800 input + 400 output) │ -│ Context window: 100% left (1.2K used / 272K) │ -│ Monthly limit: [██████████████████░░] 88% left (resets 07:08 on 7 May) │ -╰────────────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 1.2K total (800 input + 400 output) │ +│ Context window: 100% left (1.2K used / 272K) │ +│ Monthly limit: [██████████████████░░] 88% left (resets 07:08 on 7 May) │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap index 8719230212..96b2ed1648 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap @@ -12,7 +12,7 @@ expression: sanitized │ │ │ Model: gpt-5.1-codex-max (reasoning high, summaries detailed) │ │ Directory: [[workspace]] │ -│ Permissions: Workspace (on-request) │ +│ Permissions: Workspace (Ask for approval) │ │ Agents.md: │ │ │ │ Token usage: 1.9K total (1K input + 900 output) │ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap index a57c34bdf1..4604b26f7e 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_active_user_defined_profile.snap @@ -12,7 +12,7 @@ expression: sanitized │ │ │ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ │ Directory: [[workspace]] │ -│ Permissions: Profile locked (read-only, on-request) │ +│ Permissions: Profile locked (read-only, Ask for approval) │ │ Agents.md: │ │ │ │ Token usage: 0 total (0 input + 0 output) │ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap index f1ceb21ab0..c739d55075 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_auto_review_permissions.snap @@ -12,7 +12,7 @@ expression: sanitized │ │ │ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ │ Directory: [[workspace]] │ -│ Permissions: Workspace (auto-review) │ +│ Permissions: Workspace (Approve for me) │ │ Agents.md: │ │ │ │ Token usage: 0 total (0 input + 0 output) │ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap index 79344df582..533be27976 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap @@ -4,18 +4,18 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 used / 272K) │ -│ Limits: data not available yet │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 750 total (500 input + 250 output) │ +│ Context window: 100% left (750 used / 272K) │ +│ Limits: data not available yet │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap index f633cd7f6c..631982bcf9 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_refreshing_limits_notice.snap @@ -4,19 +4,19 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 used / 272K) │ -│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 08:24) │ -│ Weekly limit: [██████████████░░░░░░] 70% left (resets 08:54) │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 750 total (500 input + 250 output) │ +│ Context window: 100% left (750 used / 272K) │ +│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 08:24) │ +│ Weekly limit: [██████████████░░░░░░] 70% left (resets 08:54) │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap index dc52e22ec4..8facd56275 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap @@ -4,20 +4,20 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 1.9K total (1K input + 900 output) │ -│ Context window: 100% left (2.25K used / 272K) │ -│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │ -│ Weekly limit: [████████████░░░░░░░░] 60% left (resets 03:34) │ -│ Warning: limits may be stale - start new turn to refresh. │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 1.9K total (1K input + 900 output) │ +│ Context window: 100% left (2.25K used / 272K) │ +│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │ +│ Weekly limit: [████████████░░░░░░░░] 60% left (resets 03:34) │ +│ Warning: limits may be stale - start new turn to refresh. │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap index 83d30b5adc..d46a483e4b 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_unavailable_limits_message.snap @@ -4,18 +4,18 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 used / 272K) │ -│ Limits: not available for this account │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 750 total (500 input + 250 output) │ +│ Context window: 100% left (750 used / 272K) │ +│ Limits: not available for this account │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_treats_refreshing_empty_limits_as_unavailable.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_treats_refreshing_empty_limits_as_unavailable.snap index 83d30b5adc..d46a483e4b 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_treats_refreshing_empty_limits_as_unavailable.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_treats_refreshing_empty_limits_as_unavailable.snap @@ -4,18 +4,18 @@ expression: sanitized --- /status -╭───────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 used / 272K) │ -│ Limits: not available for this account │ -╰───────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 750 total (500 input + 250 output) │ +│ Context window: 100% left (750 used / 272K) │ +│ Limits: not available for this account │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap index a048726bb3..6b28b53b62 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap @@ -12,7 +12,7 @@ expression: sanitized │ │ │ Model: gpt-5.1-codex-max (reasoning high, summaries de │ │ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-reque │ +│ Permissions: Custom (workspace with network access, Ask for │ │ Agents.md: │ │ │ │ Token usage: 1.9K total (1K input + 900 output) │ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap index 2f6925c830..9683beed97 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_default_reasoning_when_config_empty.snap @@ -4,21 +4,21 @@ expression: sanitized --- /status -╭──────────────────────────────────────────────────────────────────────────╮ -│ >_ OpenAI Codex (v0.0.0) │ -│ │ -│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ -│ information on rate limits and credits │ -│ │ -│ Remote: unix:///tmp/codex-home/app-server-control/app-server- │ -│ control.sock (v0.133.0) │ -│ │ -│ Model: gpt-5.1-codex-max (reasoning medium, summaries auto) │ -│ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ -│ Agents.md: │ -│ │ -│ Token usage: 750 total (500 input + 250 output) │ -│ Context window: 100% left (750 used / 272K) │ -│ Limits: data not available yet │ -╰──────────────────────────────────────────────────────────────────────────╯ +╭─────────────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │ +│ information on rate limits and credits │ +│ │ +│ Remote: unix:///tmp/codex-home/app-server-control/app-server- │ +│ control.sock (v0.133.0) │ +│ │ +│ Model: gpt-5.1-codex-max (reasoning medium, summaries auto) │ +│ Directory: [[workspace]] │ +│ Permissions: Custom (workspace with network access, Ask for approval) │ +│ Agents.md: │ +│ │ +│ Token usage: 750 total (500 input + 250 output) │ +│ Context window: 100% left (750 used / 272K) │ +│ Limits: data not available yet │ +╰─────────────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap index f983cf478d..6b6fad683b 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_uses_generic_limit_labels_for_unsupported_windows.snap @@ -12,7 +12,7 @@ expression: sanitized │ │ │ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │ │ Directory: [[workspace]] │ -│ Permissions: Custom (workspace with network access, on-request) │ +│ Permissions: Custom (workspace with network access, Ask for app │ │ Agents.md: │ │ │ │ Token usage: 1.2K total (800 input + 400 output) │ diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index 9609703b0d..8b4e41ce76 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -291,7 +291,7 @@ async fn status_permissions_non_default_workspace_write_uses_workspace_label() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Custom (workspace with network access, on-request)") + Some("Custom (workspace with network access, Ask for approval)") ); } @@ -314,7 +314,7 @@ async fn status_permissions_named_read_only_profile_shows_builtin_label() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Read Only (on-request)") + Some("Read Only (Ask for approval)") ); } @@ -344,7 +344,7 @@ async fn status_permissions_read_only_profile_shows_additional_writable_roots() assert_eq!( permissions_text_for(&config).as_deref(), - Some("Read Only (on-request)") + Some("Read Only (Ask for approval)") ); } @@ -367,7 +367,7 @@ async fn status_permissions_named_workspace_profile_shows_builtin_label() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Workspace (on-request)") + Some("Workspace (Ask for approval)") ); } @@ -391,7 +391,7 @@ async fn status_permissions_workspace_auto_review_shows_reviewer_label() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Workspace (auto-review)") + Some("Workspace (Approve for me)") ); } @@ -420,7 +420,7 @@ async fn status_permissions_named_profile_shows_additional_writable_roots() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Workspace (on-request)") + Some("Workspace (Ask for approval)") ); } @@ -449,7 +449,10 @@ async fn status_permissions_workspace_roots_show_additional_directories() { assert_eq!( permissions_text_for(&config), - Some(format!("Workspace [{}] (on-request)", extra_root.display())) + Some(format!( + "Workspace [{}] (Ask for approval)", + extra_root.display() + )) ); } @@ -483,7 +486,7 @@ async fn status_permissions_workspace_roots_include_profile_defined_directories( assert_eq!( permissions_text_for(&config), Some(format!( - "Workspace [{}] (on-request)", + "Workspace [{}] (Ask for approval)", profile_root.display() )) ); @@ -513,7 +516,7 @@ async fn status_permissions_broadened_workspace_profile_shows_builtin_label() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Workspace with network access (on-request)") + Some("Workspace with network access (Ask for approval)") ); } @@ -531,7 +534,7 @@ async fn status_permissions_user_defined_profile_shows_name() { assert_eq!( permissions_text_for(&config).as_deref(), - Some("Profile locked (read-only, on-request)") + Some("Profile locked (read-only, Ask for approval)") ); } @@ -756,7 +759,7 @@ async fn status_permissions_full_disk_managed_with_network_is_danger_full_access assert_eq!( permissions_text_for(&config).as_deref(), - Some("Custom (danger-full-access, on-request)") + Some("Custom (danger-full-access, Ask for approval)") ); } @@ -779,7 +782,7 @@ async fn status_permissions_full_disk_managed_without_network_is_external_sandbo assert_eq!( permissions_text_for(&config).as_deref(), - Some("Custom (external-sandbox, on-request)") + Some("Custom (external-sandbox, Ask for approval)") ); } diff --git a/codex-rs/windows-sandbox-rs/src/allow.rs b/codex-rs/windows-sandbox-rs/src/allow.rs index 59ed2468c6..5a10261d0c 100644 --- a/codex-rs/windows-sandbox-rs/src/allow.rs +++ b/codex-rs/windows-sandbox-rs/src/allow.rs @@ -63,17 +63,22 @@ mod tests { ) } + fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] + } + fn compute_allow_paths( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, ) -> AllowDenyPaths { - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - ) - .expect("managed permission profile"); + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + ) + .expect("managed permission profile"); compute_allow_paths_for_permissions(&permissions, command_cwd, env_map) } @@ -91,10 +96,11 @@ mod tests { /*exclude_tmpdir_env_var*/ false, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -113,10 +119,10 @@ mod tests { } #[test] - fn uses_profile_cwd_for_workspace_root() { + fn uses_runtime_workspace_roots_for_workspace_root() { let tmp = TempDir::new().expect("tempdir"); - let permission_profile_cwd = tmp.path().join("workspace"); - let command_cwd = permission_profile_cwd.join("subdir"); + let workspace_root = tmp.path().join("workspace"); + let command_cwd = workspace_root.join("subdir"); fs::create_dir_all(&command_cwd).expect("create command cwd"); let permission_profile = workspace_write_profile( @@ -124,10 +130,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); let paths = compute_allow_paths( &permission_profile, - &permission_profile_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -135,7 +142,7 @@ mod tests { assert!( paths .allow - .contains(&dunce::canonicalize(&permission_profile_cwd).unwrap()) + .contains(&dunce::canonicalize(&workspace_root).unwrap()) ); assert!( !paths @@ -161,8 +168,14 @@ mod tests { let mut env_map = HashMap::new(); env_map.insert("TEMP".into(), temp_dir.to_string_lossy().to_string()); env_map.insert("TMP".into(), temp_dir.to_string_lossy().to_string()); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); - let paths = compute_allow_paths(&permission_profile, &command_cwd, &command_cwd, &env_map); + let paths = compute_allow_paths( + &permission_profile, + workspace_roots.as_slice(), + &command_cwd, + &env_map, + ); assert!( paths @@ -193,8 +206,14 @@ mod tests { let mut env_map = HashMap::new(); env_map.insert("TEMP".into(), temp_dir.to_string_lossy().to_string()); env_map.insert("TMP".into(), temp_dir.to_string_lossy().to_string()); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); - let paths = compute_allow_paths(&permission_profile, &command_cwd, &command_cwd, &env_map); + let paths = compute_allow_paths( + &permission_profile, + workspace_roots.as_slice(), + &command_cwd, + &env_map, + ); let expected_allow: HashSet = [ dunce::canonicalize(&command_cwd).unwrap(), @@ -218,10 +237,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -245,10 +265,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -276,10 +297,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -308,10 +330,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); @@ -340,10 +363,11 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ false, ); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); let paths = compute_allow_paths( &permission_profile, - &command_cwd, + workspace_roots.as_slice(), &command_cwd, &HashMap::new(), ); diff --git a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs index afdbdd5813..682dc06191 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs +++ b/codex-rs/windows-sandbox-rs/src/bin/command_runner/win.rs @@ -238,7 +238,8 @@ fn spawn_ipc_process(req: &SpawnRequest) -> Result { hide_current_user_profile_dir(req.codex_home.as_path()); let token_mode = token_mode_for_permission_profile( &req.permission_profile, - &req.permission_profile_cwd, + &req.workspace_roots, + &req.cwd, &req.env, ) .context("resolve permission profile token mode")?; diff --git a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs index 9b178fdca9..41fa2f720e 100644 --- a/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs +++ b/codex-rs/windows-sandbox-rs/src/bin/setup_main/win.rs @@ -105,6 +105,7 @@ struct Payload { enum SetupMode { #[default] Full, + ProvisionOnly, ReadAclsOnly, } @@ -476,6 +477,7 @@ fn real_main() -> Result<()> { fn run_setup(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Result<()> { match payload.mode { SetupMode::ReadAclsOnly => run_read_acl_only(payload, log), + SetupMode::ProvisionOnly => run_provision_only(payload, log, sbx_dir), SetupMode::Full => run_setup_full(payload, log, sbx_dir), } } @@ -543,31 +545,182 @@ fn run_read_acl_only(payload: &Payload, log: &mut dyn Write) -> Result<()> { Ok(()) } +fn provision_and_hide_sandbox_users( + payload: &Payload, + log: &mut dyn Write, + sbx_dir: &Path, +) -> Result<()> { + let provision_result = provision_sandbox_users( + &payload.codex_home, + &payload.offline_username, + &payload.online_username, + &payload.proxy_ports, + payload.allow_local_binding, + log, + ); + if let Err(err) = provision_result { + if extract_setup_failure(&err).is_some() { + return Err(err); + } + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperUserProvisionFailed, + format!("provision sandbox users failed: {err}"), + ))); + } + let users = vec![ + payload.offline_username.clone(), + payload.online_username.clone(), + ]; + hide_newly_created_users(&users, sbx_dir); + Ok(()) +} + +fn configure_offline_sandbox_network( + payload: &Payload, + offline_sid_str: &str, + log: &mut dyn Write, +) -> Result<()> { + let proxy_allowlist_result = firewall::ensure_offline_proxy_allowlist( + offline_sid_str, + &payload.proxy_ports, + payload.allow_local_binding, + log, + ); + if let Err(err) = proxy_allowlist_result { + if extract_setup_failure(&err).is_some() { + return Err(err); + } + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("ensure offline proxy allowlist failed: {err}"), + ))); + } + let firewall_result = firewall::ensure_offline_outbound_block(offline_sid_str, log); + if let Err(err) = firewall_result { + if extract_setup_failure(&err).is_some() { + return Err(err); + } + return Err(anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, + format!("ensure offline outbound block failed: {err}"), + ))); + } + install_wfp_filters( + &payload.codex_home, + &payload.offline_username, + payload.otel.as_ref(), + |message| { + let _ = log_line(log, message); + }, + ); + Ok(()) +} + +fn lock_persistent_sandbox_dirs( + payload: &Payload, + sandbox_group_sid: &[u8], + log: &mut dyn Write, +) -> Result<()> { + lock_sandbox_dir( + &sandbox_dir(&payload.codex_home), + &payload.real_user, + sandbox_group_sid, + GRANT_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, + log, + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox dir {} failed: {err}", + sandbox_dir(&payload.codex_home).display() + ), + )) + })?; + lock_sandbox_dir( + &sandbox_secrets_dir(&payload.codex_home), + &payload.real_user, + sandbox_group_sid, + DENY_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, + log, + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox secrets dir {} failed: {err}", + sandbox_secrets_dir(&payload.codex_home).display() + ), + )) + })?; + let legacy_users = sandbox_dir(&payload.codex_home).join("sandbox_users.json"); + if legacy_users.exists() { + let _ = std::fs::remove_file(&legacy_users); + } + Ok(()) +} + +fn lock_sandbox_bin_dir( + payload: &Payload, + sandbox_group_sid: &[u8], + log: &mut dyn Write, +) -> Result<()> { + lock_sandbox_dir( + &sandbox_bin_dir(&payload.codex_home), + &payload.real_user, + sandbox_group_sid, + GRANT_ACCESS, + FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, + FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, + log, + ) + .map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSandboxLockFailed, + format!( + "lock sandbox bin dir {} failed: {err}", + sandbox_bin_dir(&payload.codex_home).display() + ), + )) + }) +} + +fn run_provision_only(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Result<()> { + provision_and_hide_sandbox_users(payload, log, sbx_dir)?; + let offline_sid = resolve_sid(&payload.offline_username).map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSidResolveFailed, + format!( + "resolve SID for offline user {} failed: {err}", + payload.offline_username + ), + )) + })?; + let offline_sid_str = string_from_sid_bytes(&offline_sid).map_err(anyhow::Error::msg)?; + + let sandbox_group_sid = resolve_sandbox_users_group_sid().map_err(|err| { + anyhow::Error::new(SetupFailure::new( + SetupErrorCode::HelperSidResolveFailed, + format!("resolve sandbox users group SID failed: {err}"), + )) + })?; + + configure_offline_sandbox_network(payload, &offline_sid_str, log)?; + + lock_sandbox_bin_dir(payload, &sandbox_group_sid, log)?; + lock_persistent_sandbox_dirs(payload, &sandbox_group_sid, log)?; + log_note("setup provisioning binary completed", Some(sbx_dir)); + Ok(()) +} + fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Result<()> { let refresh_only = payload.refresh_only; if !refresh_only { - let provision_result = provision_sandbox_users( - &payload.codex_home, - &payload.offline_username, - &payload.online_username, - &payload.proxy_ports, - payload.allow_local_binding, - log, - ); - if let Err(err) = provision_result { - if extract_setup_failure(&err).is_some() { - return Err(err); - } - return Err(anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperUserProvisionFailed, - format!("provision sandbox users failed: {err}"), - ))); - } - let users = vec![ - payload.offline_username.clone(), - payload.online_username.clone(), - ]; - hide_newly_created_users(&users, sbx_dir); + provision_and_hide_sandbox_users(payload, log, sbx_dir)?; } let offline_sid = resolve_sid(&payload.offline_username).map_err(|err| { anyhow::Error::new(SetupFailure::new( @@ -597,39 +750,7 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res let mut refresh_errors: Vec = Vec::new(); if !refresh_only { - let proxy_allowlist_result = firewall::ensure_offline_proxy_allowlist( - &offline_sid_str, - &payload.proxy_ports, - payload.allow_local_binding, - log, - ); - if let Err(err) = proxy_allowlist_result { - if extract_setup_failure(&err).is_some() { - return Err(err); - } - return Err(anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, - format!("ensure offline proxy allowlist failed: {err}"), - ))); - } - let firewall_result = firewall::ensure_offline_outbound_block(&offline_sid_str, log); - if let Err(err) = firewall_result { - if extract_setup_failure(&err).is_some() { - return Err(err); - } - return Err(anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperFirewallRuleCreateOrAddFailed, - format!("ensure offline outbound block failed: {err}"), - ))); - } - install_wfp_filters( - &payload.codex_home, - &payload.offline_username, - payload.otel.as_ref(), - |message| { - let _ = log_line(log, message); - }, - ); + configure_offline_sandbox_network(payload, &offline_sid_str, log)?; } // Deny-read ACEs must be present before the sandboxed command starts. Apply @@ -865,24 +986,7 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res } } - lock_sandbox_dir( - &sandbox_bin_dir(&payload.codex_home), - &payload.real_user, - &sandbox_group_sid, - GRANT_ACCESS, - FILE_GENERIC_READ | FILE_GENERIC_EXECUTE, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, - log, - ) - .map_err(|err| { - anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperSandboxLockFailed, - format!( - "lock sandbox bin dir {} failed: {err}", - sandbox_bin_dir(&payload.codex_home).display() - ), - )) - })?; + lock_sandbox_bin_dir(payload, &sandbox_group_sid, log)?; if refresh_only { log_line( @@ -895,46 +999,7 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res )?; } if !refresh_only { - lock_sandbox_dir( - &sandbox_dir(&payload.codex_home), - &payload.real_user, - &sandbox_group_sid, - GRANT_ACCESS, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, - log, - ) - .map_err(|err| { - anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperSandboxLockFailed, - format!( - "lock sandbox dir {} failed: {err}", - sandbox_dir(&payload.codex_home).display() - ), - )) - })?; - lock_sandbox_dir( - &sandbox_secrets_dir(&payload.codex_home), - &payload.real_user, - &sandbox_group_sid, - DENY_ACCESS, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE, - FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE, - log, - ) - .map_err(|err| { - anyhow::Error::new(SetupFailure::new( - SetupErrorCode::HelperSandboxLockFailed, - format!( - "lock sandbox secrets dir {} failed: {err}", - sandbox_secrets_dir(&payload.codex_home).display() - ), - )) - })?; - let legacy_users = sandbox_dir(&payload.codex_home).join("sandbox_users.json"); - if legacy_users.exists() { - let _ = std::fs::remove_file(&legacy_users); - } + lock_persistent_sandbox_dirs(payload, &sandbox_group_sid, log)?; } unsafe { @@ -986,6 +1051,15 @@ mod tests { assert_eq!(payload.otel, None); } + #[test] + fn payload_accepts_provision_only_mode() { + let mut payload = payload_json(); + payload["mode"] = json!("provision-only"); + let payload: Payload = serde_json::from_value(payload).expect("payload"); + + assert_eq!(payload.mode, super::SetupMode::ProvisionOnly); + } + #[test] fn payload_accepts_otel_settings() { let mut payload = payload_json(); diff --git a/codex-rs/windows-sandbox-rs/src/elevated/ipc_framed.rs b/codex-rs/windows-sandbox-rs/src/elevated/ipc_framed.rs index 5512ebefb4..7df6a1f4f2 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated/ipc_framed.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated/ipc_framed.rs @@ -11,6 +11,7 @@ use anyhow::Result; use base64::Engine as _; use base64::engine::general_purpose::STANDARD; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; @@ -25,7 +26,7 @@ use std::path::PathBuf; const MAX_FRAME_LEN: usize = 8 * 1024 * 1024; /// Protocol version shared by the parent process and elevated command runner. -pub const IPC_PROTOCOL_VERSION: u8 = 2; +pub const IPC_PROTOCOL_VERSION: u8 = 3; /// Length-prefixed, JSON-encoded frame. #[derive(Debug, Serialize, Deserialize, Clone)] @@ -60,7 +61,7 @@ pub struct SpawnRequest { pub cwd: PathBuf, pub env: HashMap, pub permission_profile: PermissionProfile, - pub permission_profile_cwd: PathBuf, + pub workspace_roots: Vec, pub codex_home: PathBuf, pub real_codex_home: PathBuf, pub cap_sids: Vec, @@ -197,6 +198,10 @@ mod tests { #[test] fn spawn_request_serializes_permission_profile() { + let workspace_roots = vec![ + AbsolutePathBuf::from_absolute_path(PathBuf::from(r"C:\workspace")) + .expect("absolute workspace root"), + ]; let msg = FramedMessage { version: IPC_PROTOCOL_VERSION, message: Message::SpawnRequest { @@ -205,7 +210,7 @@ mod tests { cwd: PathBuf::from(r"C:\workspace"), env: HashMap::new(), permission_profile: PermissionProfile::read_only(), - permission_profile_cwd: PathBuf::from(r"C:\workspace"), + workspace_roots: workspace_roots.clone(), codex_home: PathBuf::from(r"C:\codex"), real_codex_home: PathBuf::from(r"C:\Users\codex"), cap_sids: vec!["S-1-15-3-1024-1".to_string()], @@ -222,15 +227,13 @@ mod tests { assert_eq!("managed", encoded["payload"]["permission_profile"]["type"]); assert_eq!(None, encoded["payload"].get("policy_json_or_preset")); assert_eq!(None, encoded["payload"].get("sandbox_policy_cwd")); + assert_eq!(None, encoded["payload"].get("permission_profile_cwd")); let decoded: FramedMessage = serde_json::from_value(encoded).expect("deserialize"); let Message::SpawnRequest { payload } = decoded.message else { panic!("unexpected message"); }; assert_eq!(PermissionProfile::read_only(), payload.permission_profile); - assert_eq!( - PathBuf::from(r"C:\workspace"), - payload.permission_profile_cwd - ); + assert_eq!(workspace_roots, payload.workspace_roots); } } diff --git a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs index 6038a2413f..36e47a5396 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs @@ -6,12 +6,13 @@ use std::path::PathBuf; pub struct ElevatedSandboxProfileCaptureRequest<'a> { pub permission_profile: &'a PermissionProfile, - pub permission_profile_cwd: &'a Path, + pub workspace_roots: &'a [AbsolutePathBuf], pub codex_home: &'a Path, pub command: Vec, pub cwd: &'a Path, pub env_map: HashMap, pub timeout_ms: Option, + pub cancellation: Option, pub use_private_desktop: bool, pub proxy_enforced: bool, pub read_roots_override: Option<&'a [PathBuf]>, @@ -30,11 +31,14 @@ mod windows_impl { use crate::env::inherit_path_env; use crate::env::normalize_null_device_env; use crate::identity::require_logon_sandbox_creds; + use crate::ipc_framed::EmptyPayload; + use crate::ipc_framed::FramedMessage; use crate::ipc_framed::Message; use crate::ipc_framed::OutputStream; use crate::ipc_framed::SpawnRequest; use crate::ipc_framed::decode_bytes; use crate::ipc_framed::read_frame; + use crate::ipc_framed::write_frame; use crate::logging::log_failure; use crate::logging::log_start; use crate::logging::log_success; @@ -46,10 +50,48 @@ mod windows_impl { use crate::token::LocalSid; use anyhow::Result; use codex_utils_absolute_path::AbsolutePathBuf; + use std::fs::File; use std::path::Path; + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::Ordering; + use std::time::Duration; pub use crate::windows_impl::CaptureResult; + /// Polls for cancellation and sends the runner's terminate IPC frame when requested. + /// + /// The 50 ms park bounds cancellation latency without busy-waiting. + fn spawn_cancel_writer( + pipe_write: &File, + cancellation: Option, + ) -> Result, Arc)>> { + let Some(cancellation) = cancellation else { + return Ok(None); + }; + let mut pipe_write = pipe_write.try_clone()?; + let done = Arc::new(AtomicBool::new(false)); + let done_for_thread = Arc::clone(&done); + let handle = std::thread::spawn(move || { + while !done_for_thread.load(Ordering::SeqCst) { + if cancellation.is_cancelled() { + let _ = write_frame( + &mut pipe_write, + &FramedMessage { + version: 1, + message: Message::Terminate { + payload: EmptyPayload::default(), + }, + }, + ); + break; + } + std::thread::park_timeout(Duration::from_millis(50)); + } + }); + Ok(Some((handle, done))) + } + /// Launches the command runner under the sandbox user and captures its output. #[allow(clippy::too_many_arguments)] pub fn run_windows_sandbox_capture_for_permission_profile( @@ -57,12 +99,13 @@ mod windows_impl { ) -> Result { let ElevatedSandboxProfileCaptureRequest { permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, command, cwd, mut env_map, timeout_ms, + cancellation, use_private_desktop, proxy_enforced, read_roots_override, @@ -71,10 +114,11 @@ mod windows_impl { deny_read_paths_override, deny_write_paths_override, } = request; - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - )?; + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + )?; let deny_read_paths_override = deny_read_paths_override .iter() .map(AbsolutePathBuf::to_path_buf) @@ -139,7 +183,7 @@ mod windows_impl { cwd: cwd.to_path_buf(), env: env_map.clone(), permission_profile: permission_profile.clone(), - permission_profile_cwd: permission_profile_cwd.to_path_buf(), + workspace_roots: workspace_roots.to_vec(), codex_home: sandbox_base.clone(), real_codex_home: codex_home.to_path_buf(), cap_sids, @@ -156,33 +200,45 @@ mod windows_impl { spawn_request, )?; let (pipe_write, mut pipe_read) = transport.into_files(); - drop(pipe_write); + let cancel_writer = spawn_cancel_writer(&pipe_write, cancellation)?; let mut stdout = Vec::new(); let mut stderr = Vec::new(); - let (exit_code, timed_out) = loop { - let msg = read_frame(&mut pipe_read)? - .ok_or_else(|| anyhow::anyhow!("runner pipe closed before exit"))?; + let result = loop { + let msg = match read_frame(&mut pipe_read) { + Ok(Some(msg)) => msg, + Ok(None) => break Err(anyhow::anyhow!("runner pipe closed before exit")), + Err(err) => break Err(err), + }; match msg.message { Message::SpawnReady { .. } => {} - Message::Output { payload } => { - let bytes = decode_bytes(&payload.data_b64)?; - match payload.stream { + Message::Output { payload } => match decode_bytes(&payload.data_b64) { + Ok(bytes) => match payload.stream { OutputStream::Stdout => stdout.extend_from_slice(&bytes), OutputStream::Stderr => stderr.extend_from_slice(&bytes), + }, + Err(err) => { + break Err(err); } - } - Message::Exit { payload } => break (payload.exit_code, payload.timed_out), + }, + Message::Exit { payload } => break Ok((payload.exit_code, payload.timed_out)), Message::Error { payload } => { - return Err(anyhow::anyhow!("runner error: {}", payload.message)); + break Err(anyhow::anyhow!("runner error: {}", payload.message)); } other => { - return Err(anyhow::anyhow!( + break Err(anyhow::anyhow!( "unexpected runner message during capture: {other:?}" )); } } }; + if let Some((cancel_handle, done)) = cancel_writer { + done.store(true, Ordering::SeqCst); + cancel_handle.thread().unpark(); + let _ = cancel_handle.join(); + } + drop(pipe_write); + let (exit_code, timed_out) = result?; if exit_code == 0 { log_success(&command, logs_base_dir); diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index 26e22dde07..3bd2639868 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -5,6 +5,36 @@ #[cfg(any(target_os = "windows", test))] mod ssh_config_dependencies; +use std::fmt; +use std::sync::Arc; + +/// Cancellation hook used by Windows sandbox capture backends. +#[derive(Clone)] +pub struct WindowsSandboxCancellationToken { + is_cancelled: Arc bool + Send + Sync>, +} + +impl WindowsSandboxCancellationToken { + /// Creates a token backed by a cancellation predicate. + pub fn new(is_cancelled: impl Fn() -> bool + Send + Sync + 'static) -> Self { + Self { + is_cancelled: Arc::new(is_cancelled), + } + } + + /// Returns whether the caller has requested cancellation. + pub fn is_cancelled(&self) -> bool { + (self.is_cancelled)() + } +} + +impl fmt::Debug for WindowsSandboxCancellationToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WindowsSandboxCancellationToken") + .finish_non_exhaustive() + } +} + #[cfg(target_os = "windows")] mod acl; #[cfg(target_os = "windows")] @@ -211,6 +241,8 @@ pub use setup::SandboxSetupRequest; #[cfg(target_os = "windows")] pub use setup::SetupRootOverrides; #[cfg(target_os = "windows")] +pub use setup::run_elevated_provisioning_setup; +#[cfg(target_os = "windows")] pub use setup::run_elevated_setup; #[cfg(target_os = "windows")] pub use setup::run_setup_refresh; @@ -287,6 +319,7 @@ pub use stub::run_windows_sandbox_legacy_preflight; #[cfg(target_os = "windows")] mod windows_impl { + use super::WindowsSandboxCancellationToken; use super::logging::log_failure; use super::logging::log_success; use super::process::create_process_as_user; @@ -306,6 +339,8 @@ mod windows_impl { use std::io; use std::path::Path; use std::ptr; + use std::time::Duration; + use std::time::Instant; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::Foundation::HANDLE; @@ -318,6 +353,50 @@ mod windows_impl { type PipeHandles = ((HANDLE, HANDLE), (HANDLE, HANDLE), (HANDLE, HANDLE)); + enum WaitOutcome { + Exited, + TimedOut, + Cancelled, + } + + fn wait_for_process( + process: HANDLE, + timeout_ms: Option, + cancellation: Option<&WindowsSandboxCancellationToken>, + ) -> WaitOutcome { + let Some(cancellation) = cancellation else { + let timeout = timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE); + let res = unsafe { WaitForSingleObject(process, timeout) }; + return if res == 0x0000_0102 { + WaitOutcome::TimedOut + } else { + WaitOutcome::Exited + }; + }; + + let deadline = timeout_ms.map(|ms| Instant::now() + Duration::from_millis(ms)); + loop { + if cancellation.is_cancelled() { + return WaitOutcome::Cancelled; + } + let wait_ms = match deadline { + Some(deadline) => { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + remaining.min(Duration::from_millis(50)).as_millis() as u32 + } + None => 50, + }; + let res = unsafe { WaitForSingleObject(process, wait_ms) }; + if res == 0x0000_0102 { + continue; + } + return WaitOutcome::Exited; + } + } + unsafe fn setup_stdio_pipes() -> io::Result { let mut in_r: HANDLE = 0; let mut in_w: HANDLE = 0; @@ -356,22 +435,24 @@ mod windows_impl { #[allow(clippy::too_many_arguments)] pub fn run_windows_sandbox_capture( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, env_map: HashMap, timeout_ms: Option, + cancellation: Option, use_private_desktop: bool, ) -> Result { run_windows_sandbox_capture_with_filesystem_overrides( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, command, cwd, env_map, timeout_ms, + cancellation, &[], &[], use_private_desktop, @@ -381,12 +462,13 @@ mod windows_impl { #[allow(clippy::too_many_arguments)] pub fn run_windows_sandbox_capture_with_filesystem_overrides( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, mut env_map: HashMap, timeout_ms: Option, + cancellation: Option, additional_deny_read_paths: &[AbsolutePathBuf], additional_deny_write_paths: &[AbsolutePathBuf], use_private_desktop: bool, @@ -401,7 +483,7 @@ mod windows_impl { .collect::>(); let common = prepare_legacy_spawn_context( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, cwd, &mut env_map, @@ -531,11 +613,11 @@ mod windows_impl { let _ = tx_err.send(buf); }); - let timeout = timeout_ms.map(|ms| ms as u32).unwrap_or(INFINITE); - let res = unsafe { WaitForSingleObject(pi.hProcess, timeout) }; - let timed_out = res == 0x0000_0102; + let wait_outcome = wait_for_process(pi.hProcess, timeout_ms, cancellation.as_ref()); + let timed_out = matches!(wait_outcome, WaitOutcome::TimedOut); + let cancelled = matches!(wait_outcome, WaitOutcome::Cancelled); let mut exit_code_u32: u32 = 1; - if !timed_out { + if !timed_out && !cancelled { unsafe { GetExitCodeProcess(pi.hProcess, &mut exit_code_u32); } @@ -580,14 +662,14 @@ mod windows_impl { pub fn run_windows_sandbox_legacy_preflight( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, cwd: &Path, env_map: &HashMap, ) -> Result<()> { - let Ok(permissions) = super::resolved_permissions::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + let Ok(permissions) = super::resolved_permissions::ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( permission_profile, - permission_profile_cwd, + workspace_roots, ) else { return Ok(()); }; @@ -635,9 +717,9 @@ mod windows_impl { } fn should_apply_network_block(permission_profile: &PermissionProfile) -> bool { - ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( permission_profile, - Path::new("."), + &[], ) .expect("managed permissions") .should_apply_network_block() @@ -672,7 +754,7 @@ mod windows_impl { ] { super::run_windows_sandbox_legacy_preflight( &permission_profile, - Path::new("."), + &[], Path::new("."), Path::new("."), &HashMap::new(), @@ -685,9 +767,11 @@ mod windows_impl { #[cfg(not(target_os = "windows"))] mod stub { + use super::WindowsSandboxCancellationToken; use anyhow::Result; use anyhow::bail; use codex_protocol::models::PermissionProfile; + use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::path::Path; @@ -702,12 +786,13 @@ mod stub { #[allow(clippy::too_many_arguments)] pub fn run_windows_sandbox_capture( _permission_profile: &PermissionProfile, - _permission_profile_cwd: &Path, + _workspace_roots: &[AbsolutePathBuf], _codex_home: &Path, _command: Vec, _cwd: &Path, _env_map: HashMap, _timeout_ms: Option, + _cancellation: Option, _use_private_desktop: bool, ) -> Result { bail!("Windows sandbox is only available on Windows") @@ -715,7 +800,7 @@ mod stub { pub fn run_windows_sandbox_legacy_preflight( _permission_profile: &PermissionProfile, - _permission_profile_cwd: &Path, + _workspace_roots: &[AbsolutePathBuf], _codex_home: &Path, _cwd: &Path, _env_map: &HashMap, diff --git a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs index 75c4c216a3..712a80aade 100644 --- a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs +++ b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs @@ -37,13 +37,15 @@ pub enum WindowsSandboxTokenMode { /// Chooses the restricted-token family needed for a managed permission profile. pub fn token_mode_for_permission_profile( permission_profile: &PermissionProfile, + workspace_roots: &[AbsolutePathBuf], cwd: &Path, env_map: &HashMap, ) -> Result { - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - cwd, - )?; + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + )?; if permissions.file_system.has_full_disk_write_access() { anyhow::bail!( "permission profile requests full-disk filesystem writes, which cannot be enforced by the Windows sandbox" @@ -76,15 +78,15 @@ impl ResolvedWindowsSandboxPermissions { } /// Resolves a managed permission profile and binds symbolic `:workspace_roots` - /// entries to the permission root supplied by the caller. - pub fn try_from_permission_profile_for_cwd( + /// entries to the workspace roots supplied by the caller. + pub fn try_from_permission_profile_for_workspace_roots( permission_profile: &PermissionProfile, - cwd: &Path, + workspace_roots: &[AbsolutePathBuf], ) -> Result { let mut permissions = Self::try_from_permission_profile(permission_profile)?; permissions.file_system = permissions .file_system - .materialize_project_roots_with_cwd(cwd); + .materialize_project_roots_with_workspace_roots(workspace_roots); Ok(permissions) } @@ -202,9 +204,14 @@ mod tests { use codex_protocol::permissions::FileSystemAccessMode; use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSpecialPath; + use codex_protocol::permissions::project_roots_glob_pattern; use pretty_assertions::assert_eq; use tempfile::TempDir; + fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] + } + #[test] fn permission_profile_workspace_write_uses_windows_temp_env_vars() { let tmp = TempDir::new().expect("tempdir"); @@ -238,10 +245,10 @@ mod tests { } #[test] - fn permission_profile_workspace_root_stays_bound_to_profile_cwd() { + fn permission_profile_workspace_root_uses_runtime_workspace_roots() { let tmp = TempDir::new().expect("tempdir"); - let profile_cwd = tmp.path().join("workspace"); - let command_cwd = profile_cwd.join("subdir"); + let workspace_root = tmp.path().join("workspace"); + let command_cwd = workspace_root.join("subdir"); std::fs::create_dir_all(&command_cwd).expect("create command cwd"); let permission_profile = PermissionProfile::Managed { @@ -256,11 +263,13 @@ mod tests { }, network: NetworkSandboxPolicy::Restricted, }; - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - &permission_profile, - &profile_cwd, - ) - .expect("managed permission profile"); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + &permission_profile, + workspace_roots.as_slice(), + ) + .expect("managed permission profile"); let roots = permissions .writable_roots_for_cwd(&command_cwd, &HashMap::new()) @@ -270,7 +279,101 @@ mod tests { assert_eq!( roots, - vec![dunce::canonicalize(&profile_cwd).expect("canonical profile cwd")] + vec![dunce::canonicalize(&workspace_root).expect("canonical workspace root")] + ); + } + + #[test] + fn permission_profile_workspace_roots_expand_all_runtime_workspace_roots() { + let tmp = TempDir::new().expect("tempdir"); + let first = AbsolutePathBuf::from_absolute_path(tmp.path().join("first")) + .expect("absolute first root"); + let second = AbsolutePathBuf::from_absolute_path(tmp.path().join("second")) + .expect("absolute second root"); + let permission_profile = PermissionProfile::Managed { + file_system: ManagedFileSystemPermissions::Restricted { + entries: vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(Some(".git".into())), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: project_roots_glob_pattern(Path::new("**/*.env")), + }, + access: FileSystemAccessMode::Deny, + }, + ], + glob_scan_max_depth: None, + }, + network: NetworkSandboxPolicy::Restricted, + }; + + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + &permission_profile, + &[first.clone(), second.clone()], + ) + .expect("managed permission profile"); + + assert_eq!( + permissions.file_system, + FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: first.clone(), + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: second.clone(), + }, + access: FileSystemAccessMode::Write, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: first.join(".git"), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: second.join(".git"), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: AbsolutePathBuf::resolve_path_against_base( + "**/*.env", + first.as_path(), + ) + .to_string_lossy() + .into_owned(), + }, + access: FileSystemAccessMode::Deny, + }, + FileSystemSandboxEntry { + path: FileSystemPath::GlobPattern { + pattern: AbsolutePathBuf::resolve_path_against_base( + "**/*.env", + second.as_path(), + ) + .to_string_lossy() + .into_owned(), + }, + access: FileSystemAccessMode::Deny, + }, + ]) ); } @@ -279,9 +382,11 @@ mod tests { let tmp = TempDir::new().expect("tempdir"); let cwd = tmp.path().join("workspace"); std::fs::create_dir_all(&cwd).expect("create cwd"); + let workspace_roots = workspace_roots_for(cwd.as_path()); let token_mode = token_mode_for_permission_profile( &PermissionProfile::read_only(), + workspace_roots.as_slice(), &cwd, &HashMap::new(), ) @@ -295,9 +400,11 @@ mod tests { let tmp = TempDir::new().expect("tempdir"); let cwd = tmp.path().join("workspace"); std::fs::create_dir_all(&cwd).expect("create cwd"); + let workspace_roots = workspace_roots_for(cwd.as_path()); let token_mode = token_mode_for_permission_profile( &PermissionProfile::workspace_write(), + workspace_roots.as_slice(), &cwd, &HashMap::new(), ) @@ -353,9 +460,15 @@ mod tests { }, network: NetworkSandboxPolicy::Restricted, }; + let workspace_roots = workspace_roots_for(cwd.as_path()); - let err = token_mode_for_permission_profile(&permission_profile, &cwd, &HashMap::new()) - .expect_err("full disk writes should not resolve to a token mode"); + let err = token_mode_for_permission_profile( + &permission_profile, + workspace_roots.as_slice(), + &cwd, + &HashMap::new(), + ) + .expect_err("full disk writes should not resolve to a token mode"); assert!( err.to_string() diff --git a/codex-rs/windows-sandbox-rs/src/setup.rs b/codex-rs/windows-sandbox-rs/src/setup.rs index cc600b85ac..a0f46fe3f8 100644 --- a/codex-rs/windows-sandbox-rs/src/setup.rs +++ b/codex-rs/windows-sandbox-rs/src/setup.rs @@ -30,6 +30,7 @@ use anyhow::anyhow; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::GetLastError; @@ -105,16 +106,18 @@ pub struct SetupRootOverrides { pub fn run_setup_refresh( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, proxy_enforced: bool, ) -> Result<()> { - let Ok(permissions) = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - ) else { + let Ok(permissions) = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + ) + else { return Ok(()); }; run_setup_refresh_inner( @@ -138,17 +141,19 @@ pub fn run_setup_refresh_with_overrides( pub fn run_setup_refresh_with_extra_read_roots( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], command_cwd: &Path, env_map: &HashMap, codex_home: &Path, extra_read_roots: Vec, proxy_enforced: bool, ) -> Result<()> { - let Ok(permissions) = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - ) else { + let Ok(permissions) = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + ) + else { return Ok(()); }; let mut read_roots = gather_read_roots(command_cwd, &permissions, env_map, codex_home); @@ -198,6 +203,7 @@ fn run_setup_refresh_inner( allow_local_binding: offline_proxy_settings.allow_local_binding, otel: None, real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()), + mode: SetupMode::Full, refresh_only: true, }; let json = serde_json::to_vec(&payload)?; @@ -491,10 +497,18 @@ struct ElevationPayload { allow_local_binding: bool, otel: Option, real_user: String, + mode: SetupMode, #[serde(default)] refresh_only: bool, } +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "kebab-case")] +enum SetupMode { + Full, + ProvisionOnly, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct OfflineProxySettings { pub proxy_ports: Vec, @@ -803,6 +817,7 @@ pub fn run_elevated_setup( allow_local_binding: offline_proxy_settings.allow_local_binding, real_user: std::env::var("USERNAME").unwrap_or_else(|_| "Administrators".to_string()), otel: codex_otel::global_statsig_metrics_settings(), + mode: SetupMode::Full, refresh_only: false, }; let needs_elevation = !is_elevated().map_err(|err| { @@ -814,6 +829,45 @@ pub fn run_elevated_setup( run_setup_exe(&payload, needs_elevation, request.codex_home) } +pub fn run_elevated_provisioning_setup(codex_home: &Path, real_user: &str) -> Result<()> { + let sbx_dir = sandbox_dir(codex_home); + std::fs::create_dir_all(&sbx_dir).map_err(|err| { + failure( + SetupErrorCode::OrchestratorSandboxDirCreateFailed, + format!("failed to create sandbox dir {}: {err}", sbx_dir.display()), + ) + })?; + if !is_elevated().map_err(|err| { + failure( + SetupErrorCode::OrchestratorElevationCheckFailed, + format!("failed to determine elevation state: {err}"), + ) + })? { + return Err(failure( + SetupErrorCode::OrchestratorElevationRequired, + "sandbox provisioning setup must be run from an elevated process", + )); + } + let payload = ElevationPayload { + version: SETUP_VERSION, + offline_username: OFFLINE_USERNAME.to_string(), + online_username: ONLINE_USERNAME.to_string(), + codex_home: codex_home.to_path_buf(), + command_cwd: codex_home.to_path_buf(), + read_roots: Vec::new(), + write_roots: Vec::new(), + deny_read_paths: Vec::new(), + deny_write_paths: Vec::new(), + proxy_ports: Vec::new(), + allow_local_binding: false, + otel: codex_otel::global_statsig_metrics_settings(), + real_user: real_user.to_string(), + mode: SetupMode::ProvisionOnly, + refresh_only: false, + }; + run_setup_exe(&payload, /*needs_elevation*/ false, codex_home) +} + fn build_payload_roots( request: &SandboxSetupRequest<'_>, overrides: &SetupRootOverrides, @@ -1037,15 +1091,19 @@ mod tests { fn permissions_for( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], ) -> ResolvedWindowsSandboxPermissions { - ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( permission_profile, - permission_profile_cwd, + workspace_roots, ) .expect("managed permission profile") } + fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] + } + fn workspace_write_profile( writable_roots: &[AbsolutePathBuf], exclude_tmpdir_env_var: bool, @@ -1065,6 +1123,7 @@ mod tests { let command_cwd = tmp.path().join("workspace"); let codex_home = tmp.path().join("codex-home"); fs::create_dir_all(&command_cwd).expect("create workspace"); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); for permission_profile in [ PermissionProfile::Disabled, @@ -1074,7 +1133,7 @@ mod tests { ] { super::run_setup_refresh( &permission_profile, - command_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &HashMap::new(), codex_home.as_path(), @@ -1084,7 +1143,7 @@ mod tests { super::run_setup_refresh_with_extra_read_roots( &permission_profile, - command_cwd.as_path(), + workspace_roots.as_slice(), command_cwd.as_path(), &HashMap::new(), codex_home.as_path(), @@ -1413,7 +1472,8 @@ mod tests { let command_cwd = tmp.path().join("workspace"); fs::create_dir_all(&command_cwd).expect("create workspace"); let permission_profile = PermissionProfile::read_only(); - let permissions = permissions_for(&permission_profile, &command_cwd); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let roots = gather_read_roots(&command_cwd, &permissions, &HashMap::new(), &codex_home); let expected = @@ -1438,7 +1498,8 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = permissions_for(&permission_profile, &command_cwd); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let roots = gather_read_roots(&command_cwd, &permissions, &HashMap::new(), &codex_home); let expected_writable = @@ -1451,14 +1512,15 @@ mod tests { fn build_payload_roots_preserves_helper_roots_when_read_override_is_provided() { let tmp = TempDir::new().expect("tempdir"); let codex_home = tmp.path().join("codex-home"); - let permission_profile_cwd = tmp.path().join("permission-profile-cwd"); + let workspace_root = tmp.path().join("workspace-root"); let command_cwd = tmp.path().join("workspace"); let readable_root = tmp.path().join("docs"); - fs::create_dir_all(&permission_profile_cwd).expect("create permission profile cwd"); + fs::create_dir_all(&workspace_root).expect("create workspace root"); fs::create_dir_all(&command_cwd).expect("create workspace"); fs::create_dir_all(&readable_root).expect("create readable root"); let permission_profile = PermissionProfile::read_only(); - let permissions = permissions_for(&permission_profile, &permission_profile_cwd); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let (read_roots, write_roots) = build_payload_roots( &super::SandboxSetupRequest { @@ -1497,14 +1559,15 @@ mod tests { fn build_payload_roots_replaces_full_read_policy_when_read_override_is_provided() { let tmp = TempDir::new().expect("tempdir"); let codex_home = tmp.path().join("codex-home"); - let permission_profile_cwd = tmp.path().join("permission-profile-cwd"); + let workspace_root = tmp.path().join("workspace-root"); let command_cwd = tmp.path().join("workspace"); let readable_root = tmp.path().join("docs"); - fs::create_dir_all(&permission_profile_cwd).expect("create permission profile cwd"); + fs::create_dir_all(&workspace_root).expect("create workspace root"); fs::create_dir_all(&command_cwd).expect("create workspace"); fs::create_dir_all(&readable_root).expect("create readable root"); let permission_profile = PermissionProfile::read_only(); - let permissions = permissions_for(&permission_profile, &permission_profile_cwd); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let (read_roots, write_roots) = build_payload_roots( &super::SandboxSetupRequest { @@ -1555,7 +1618,8 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = permissions_for(&permission_profile, &command_cwd); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let override_roots = vec![ command_cwd.clone(), extra_root.clone(), @@ -1598,11 +1662,11 @@ mod tests { } #[test] - fn effective_write_roots_use_profile_cwd_for_workspace_root() { + fn effective_write_roots_use_runtime_workspace_roots_for_workspace_root() { let tmp = TempDir::new().expect("tempdir"); let codex_home = tmp.path().join("codex-home"); - let permission_profile_cwd = tmp.path().join("workspace"); - let command_cwd = permission_profile_cwd.join("subdir"); + let workspace_root = tmp.path().join("workspace"); + let command_cwd = workspace_root.join("subdir"); fs::create_dir_all(&codex_home).expect("create codex home"); fs::create_dir_all(&command_cwd).expect("create command cwd"); @@ -1611,7 +1675,8 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = permissions_for(&permission_profile, &permission_profile_cwd); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let effective_write_roots = super::effective_write_roots_for_setup( &permissions, @@ -1623,7 +1688,7 @@ mod tests { assert_eq!( effective_write_roots, - vec![dunce::canonicalize(&permission_profile_cwd).expect("canonical profile cwd")] + vec![dunce::canonicalize(&workspace_root).expect("canonical workspace root")] ); } @@ -1646,7 +1711,8 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = permissions_for(&permission_profile, &command_cwd); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let request = super::SandboxSetupRequest { permissions: &permissions, command_cwd: &command_cwd, @@ -1677,7 +1743,8 @@ mod tests { let command_cwd = tmp.path().join("workspace"); fs::create_dir_all(&command_cwd).expect("create workspace"); let permission_profile = PermissionProfile::read_only(); - let permissions = permissions_for(&permission_profile, &command_cwd); + let workspace_roots = workspace_roots_for(command_cwd.as_path()); + let permissions = permissions_for(&permission_profile, workspace_roots.as_slice()); let roots = gather_full_read_roots_for_permissions( &command_cwd, diff --git a/codex-rs/windows-sandbox-rs/src/setup_error.rs b/codex-rs/windows-sandbox-rs/src/setup_error.rs index efaaa531e2..4d2a9d57df 100644 --- a/codex-rs/windows-sandbox-rs/src/setup_error.rs +++ b/codex-rs/windows-sandbox-rs/src/setup_error.rs @@ -19,6 +19,8 @@ pub enum SetupErrorCode { OrchestratorSandboxDirCreateFailed, /// Failed to determine whether the current process is elevated. OrchestratorElevationCheckFailed, + /// The setup command requires an already elevated process. + OrchestratorElevationRequired, /// Failed to serialize the elevation payload before launching the helper. OrchestratorPayloadSerializeFailed, /// Failed to launch the setup helper process (spawn or ShellExecuteExW). @@ -75,6 +77,7 @@ impl SetupErrorCode { match self { Self::OrchestratorSandboxDirCreateFailed => "orchestrator_sandbox_dir_create_failed", Self::OrchestratorElevationCheckFailed => "orchestrator_elevation_check_failed", + Self::OrchestratorElevationRequired => "orchestrator_elevation_required", Self::OrchestratorPayloadSerializeFailed => "orchestrator_payload_serialize_failed", Self::OrchestratorHelperLaunchFailed => "orchestrator_helper_launch_failed", Self::OrchestratorHelperLaunchCanceled => "orchestrator_helper_launch_canceled", diff --git a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs index b68cc57a81..7bdd59bf53 100644 --- a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs +++ b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs @@ -32,6 +32,7 @@ use crate::workspace_acl::protect_workspace_codex_dir; use anyhow::Context; use anyhow::Result; use codex_protocol::models::PermissionProfile; +use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::ffi::c_void; use std::path::Path; @@ -80,17 +81,18 @@ pub(crate) struct LegacyAclSids<'a> { fn prepare_spawn_context_common( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, cwd: &Path, env_map: &mut HashMap, command: &[String], options: SpawnPrepOptions, ) -> Result { - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - )?; + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + )?; normalize_null_device_env(env_map); ensure_non_interactive_pager(env_map); @@ -119,7 +121,7 @@ fn prepare_spawn_context_common( pub(crate) fn prepare_legacy_spawn_context( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, cwd: &Path, env_map: &mut HashMap, @@ -128,7 +130,7 @@ pub(crate) fn prepare_legacy_spawn_context( ) -> Result { let common = prepare_spawn_context_common( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, cwd, env_map, @@ -472,10 +474,14 @@ mod tests { ) } + fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] + } + fn should_apply_network_block(permission_profile: &PermissionProfile) -> bool { - ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( permission_profile, - Path::new("."), + &[], ) .expect("managed permission profile") .should_apply_network_block() @@ -503,10 +509,11 @@ mod tests { let codex_home = TempDir::new().expect("tempdir"); let cwd = TempDir::new().expect("tempdir"); let mut env_map = HashMap::new(); + let workspace_roots = workspace_roots_for(cwd.path()); let _context = prepare_legacy_spawn_context( &PermissionProfile::workspace_write(), - cwd.path(), + workspace_roots.as_slice(), codex_home.path(), cwd.path(), &mut env_map, @@ -533,10 +540,11 @@ mod tests { "HTTP_PROXY".to_string(), "http://user.proxy:8080".to_string(), )]); + let workspace_roots = workspace_roots_for(cwd.path()); let context = prepare_spawn_context_common( &PermissionProfile::workspace_write(), - cwd.path(), + workspace_roots.as_slice(), codex_home.path(), cwd.path(), &mut env_map, @@ -557,11 +565,11 @@ mod tests { } #[test] - fn legacy_session_capability_roots_use_profile_cwd_for_workspace_root() { + fn legacy_session_capability_roots_use_runtime_workspace_roots_for_workspace_root() { let tmp = TempDir::new().expect("tempdir"); let codex_home = tmp.path().join("codex-home"); - let permission_profile_cwd = tmp.path().join("workspace"); - let command_cwd = permission_profile_cwd.join("subdir"); + let workspace_root = tmp.path().join("workspace"); + let command_cwd = workspace_root.join("subdir"); std::fs::create_dir_all(&codex_home).expect("create codex home"); std::fs::create_dir_all(&command_cwd).expect("create command cwd"); @@ -571,11 +579,13 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - &permission_profile, - &permission_profile_cwd, - ) - .expect("managed permission profile"); + let workspace_roots = workspace_roots_for(workspace_root.as_path()); + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + &permission_profile, + workspace_roots.as_slice(), + ) + .expect("managed permission profile"); let roots = legacy_session_capability_roots( &permissions, @@ -586,7 +596,7 @@ mod tests { assert_eq!( roots, - vec![dunce::canonicalize(&permission_profile_cwd).expect("canonical profile cwd")] + vec![dunce::canonicalize(&workspace_root).expect("canonical workspace root")] ); } @@ -686,11 +696,13 @@ mod tests { /*exclude_tmpdir_env_var*/ true, /*exclude_slash_tmp*/ true, ); - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - &permission_profile, - &workspace, - ) - .expect("managed permission profile"); + let workspace_roots = workspace_roots_for(workspace.as_path()); + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + &permission_profile, + workspace_roots.as_slice(), + ) + .expect("managed permission profile"); let roots = legacy_session_capability_roots(&permissions, &workspace, &HashMap::new(), &codex_home); diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs index 09ac786238..0a2af6d7ad 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs @@ -26,7 +26,7 @@ use tokio::sync::oneshot; #[allow(clippy::too_many_arguments)] pub(crate) async fn spawn_windows_sandbox_session_elevated_for_permission_profile( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, @@ -49,10 +49,11 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated_for_permission_profil .iter() .map(AbsolutePathBuf::to_path_buf) .collect::>(); - let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( - permission_profile, - permission_profile_cwd, - )?; + let permissions = + ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_workspace_roots( + permission_profile, + workspace_roots, + )?; let elevated = prepare_elevated_spawn_context_for_permissions( permissions, codex_home, @@ -71,7 +72,7 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated_for_permission_profil cwd: cwd.to_path_buf(), env: env_map.clone(), permission_profile: permission_profile.clone(), - permission_profile_cwd: permission_profile_cwd.to_path_buf(), + workspace_roots: workspace_roots.to_vec(), codex_home: elevated.sandbox_base.clone(), real_codex_home: codex_home.to_path_buf(), cap_sids: elevated.cap_sids.clone(), diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs index 2fc8c12e00..abd0c020d3 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/legacy.rs @@ -271,7 +271,7 @@ fn resize_conpty_handle(hpc: &Arc>>, size: TerminalSize) #[allow(clippy::too_many_arguments)] pub(crate) async fn spawn_windows_sandbox_session_legacy( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, @@ -285,7 +285,7 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy( ) -> Result { let common = prepare_legacy_spawn_context( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, cwd, &mut env_map, diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs index e327200426..2fe8b80ee1 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs @@ -20,7 +20,7 @@ use std::path::PathBuf; #[allow(clippy::too_many_arguments)] pub async fn spawn_windows_sandbox_session_legacy( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, @@ -34,7 +34,7 @@ pub async fn spawn_windows_sandbox_session_legacy( ) -> Result { backends::legacy::spawn_windows_sandbox_session_legacy( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, command, cwd, @@ -52,7 +52,7 @@ pub async fn spawn_windows_sandbox_session_legacy( #[allow(clippy::too_many_arguments)] pub async fn spawn_windows_sandbox_session_elevated_for_permission_profile( permission_profile: &PermissionProfile, - permission_profile_cwd: &Path, + workspace_roots: &[AbsolutePathBuf], codex_home: &Path, command: Vec, cwd: &Path, @@ -69,7 +69,7 @@ pub async fn spawn_windows_sandbox_session_elevated_for_permission_profile( ) -> Result { backends::elevated::spawn_windows_sandbox_session_elevated_for_permission_profile( permission_profile, - permission_profile_cwd, + workspace_roots, codex_home, command, cwd, diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs index b08d7a6b2f..96f5c39e92 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/tests.rs @@ -1,6 +1,7 @@ #![cfg(target_os = "windows")] use super::spawn_windows_sandbox_session_legacy; +use crate::WindowsSandboxCancellationToken; use crate::ipc_framed::Message; use crate::ipc_framed::decode_bytes; use crate::ipc_framed::read_frame; @@ -16,8 +17,10 @@ use std::io::Seek; use std::io::SeekFrom; use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use std::sync::Mutex; use std::sync::MutexGuard; +use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::time::Duration; @@ -76,6 +79,10 @@ fn sandbox_log(codex_home: &Path) -> String { .unwrap_or_else(|err| format!("failed to read {}: {err}", log_path.display())) } +fn workspace_roots_for(root: &Path) -> Vec { + vec![AbsolutePathBuf::from_absolute_path(root).expect("absolute workspace root")] +} + fn wait_for_frame_count(frames_path: &Path, expected_frames: usize) -> Vec { let deadline = Instant::now() + Duration::from_secs(2); loop { @@ -153,7 +160,7 @@ fn legacy_non_tty_cmd_emits_output() { let permission_profile = PermissionProfile::workspace_write(); let spawned = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ "C:\\Windows\\System32\\cmd.exe".to_string(), @@ -194,7 +201,7 @@ fn legacy_non_tty_cmd_rejects_deny_read_overrides() { let permission_profile = PermissionProfile::workspace_write(); let err = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ "C:\\Windows\\System32\\cmd.exe".to_string(), @@ -234,7 +241,7 @@ fn legacy_non_tty_powershell_emits_output() { let permission_profile = PermissionProfile::workspace_write(); let spawned = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ pwsh.display().to_string(), @@ -420,7 +427,7 @@ fn legacy_capture_powershell_emits_output() { let permission_profile = PermissionProfile::workspace_write(); let result = run_windows_sandbox_capture( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ pwsh.display().to_string(), @@ -431,6 +438,7 @@ fn legacy_capture_powershell_emits_output() { cwd.as_path(), HashMap::new(), Some(10_000), + /*cancellation*/ None, /*use_private_desktop*/ true, ) .expect("run legacy capture powershell"); @@ -446,6 +454,57 @@ fn legacy_capture_powershell_emits_output() { ); } +#[test] +fn legacy_capture_cancellation_is_not_reported_as_timeout() { + let Some(pwsh) = pwsh_path() else { + eprintln!("skipping cancellation regression test: PowerShell 7 is not installed"); + return; + }; + let _guard = legacy_process_test_guard(); + let cwd = sandbox_cwd(); + let codex_home = sandbox_home("legacy-capture-cancel"); + let permission_profile = PermissionProfile::workspace_write(); + let cancelled = Arc::new(AtomicBool::new(false)); + let cancelled_for_token = Arc::clone(&cancelled); + let cancellation = + WindowsSandboxCancellationToken::new(move || cancelled_for_token.load(Ordering::SeqCst)); + let cancelled_for_thread = Arc::clone(&cancelled); + let cancel_thread = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + cancelled_for_thread.store(true, Ordering::SeqCst); + }); + + let started_at = Instant::now(); + let result = run_windows_sandbox_capture( + &permission_profile, + workspace_roots_for(cwd.as_path()).as_slice(), + codex_home.path(), + vec![ + pwsh.display().to_string(), + "-NoProfile".to_string(), + "-Command".to_string(), + "Start-Sleep -Seconds 30".to_string(), + ], + cwd.as_path(), + HashMap::new(), + Some(30_000), + /*cancellation*/ Some(cancellation), + /*use_private_desktop*/ true, + ) + .expect("run legacy capture powershell with cancellation"); + cancel_thread.join().expect("cancel thread should finish"); + + assert!( + started_at.elapsed() < Duration::from_secs(10), + "cancellation should end capture before the timeout" + ); + assert!( + !result.timed_out, + "cancellation should not be reported as a timeout" + ); + assert_ne!(result.exit_code, 0); +} + #[test] fn legacy_tty_powershell_emits_output_and_accepts_input() { let Some(pwsh) = pwsh_path() else { @@ -460,7 +519,7 @@ fn legacy_tty_powershell_emits_output_and_accepts_input() { let permission_profile = PermissionProfile::workspace_write(); let spawned = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ pwsh.display().to_string(), @@ -514,7 +573,7 @@ fn legacy_tty_cmd_emits_output_and_accepts_input() { let permission_profile = PermissionProfile::workspace_write(); let spawned = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ "C:\\Windows\\System32\\cmd.exe".to_string(), @@ -568,7 +627,7 @@ fn legacy_tty_cmd_default_desktop_emits_output_and_accepts_input() { let permission_profile = PermissionProfile::workspace_write(); let spawned = spawn_windows_sandbox_session_legacy( &permission_profile, - cwd.as_path(), + workspace_roots_for(cwd.as_path()).as_slice(), codex_home.path(), vec![ "C:\\Windows\\System32\\cmd.exe".to_string(), diff --git a/sdk/python-runtime/pyproject.toml b/sdk/python-runtime/pyproject.toml index e01a517037..18967bab51 100644 --- a/sdk/python-runtime/pyproject.toml +++ b/sdk/python-runtime/pyproject.toml @@ -11,7 +11,6 @@ requires-python = ">=3.10" license = { text = "Apache-2.0" } authors = [{ name = "OpenAI" }] classifiers = [ - "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", diff --git a/sdk/python/README.md b/sdk/python/README.md index d3b74b02cf..d5bffc2ab7 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -1,132 +1,74 @@ -# OpenAI Codex Python SDK (Experimental) +# OpenAI Codex Python SDK (Beta) -Experimental Python SDK for `codex app-server` JSON-RPC v2 over stdio, with a small default surface optimized for real scripts and apps. - -The generated wire-model layer is sourced from the pinned `openai-codex-cli-bin` -runtime package and exposed as Pydantic models with snake_case Python fields -that serialize back to the protocol's camelCase wire format. -The package root exports the ergonomic client API; public Codex protocol value and -event types live in `openai_codex.types`. +Build Python applications that start Codex threads, run turns, stream progress, +and control workspace access. ## Install -```bash -cd sdk/python -uv sync -source .venv/bin/activate -``` +Install the SDK: -Published SDK builds pin an exact `openai-codex-cli-bin` runtime dependency -with the same version as the SDK. Pass `CodexConfig(codex_bin=...)` only -when you intentionally want to run against a specific local app-server binary. +```bash +pip install openai-codex +``` ## Quickstart -```python -from openai_codex import Codex, Sandbox - -with Codex() as codex: - # Call login_api_key(...) first when this Codex session is not - # already authenticated. - thread = codex.thread_start(model="gpt-5", sandbox=Sandbox.workspace_write) - result = thread.run("Say hello in one sentence.") - print(result.final_response) - print(len(result.items)) -``` - -`thread.run(...)` and `thread.turn(...).run()` return `TurnResult`. Its -`final_response` is `None` when the turn completes without a final-answer or -phase-less assistant message item. - -## Sandbox - -Use the same enum when creating a thread or changing its sandbox for a turn: - -```python -from openai_codex import Codex, Sandbox - -with Codex() as codex: - thread = codex.thread_start(sandbox=Sandbox.workspace_write) - thread.run("Make the requested change.") - review = thread.run("Review the diff only.", sandbox=Sandbox.read_only) -``` - -Available presets: - -- `Sandbox.read_only`: read files without allowing writes. -- `Sandbox.workspace_write`: the normal default for projects with a recorded trust decision; read files and write inside the workspace and configured writable roots. -- `Sandbox.full_access`: run without filesystem access restrictions. - -When `sandbox=` is omitted, Codex uses its configured default. A sandbox -passed to `run(...)` or `turn(...)` applies to that turn and subsequent turns -on the thread. - -## Login - -Use the auth helper that matches your app: +The SDK reuses your existing Codex authentication when one is already +available: ```python from openai_codex import Codex with Codex() as codex: - codex.login_api_key("sk-...") - account = codex.account() - print(account.account) + thread = codex.thread_start() + result = thread.run("Explain this repository in three bullets.") + print(result.final_response) ``` -Interactive ChatGPT login returns a handle. Open the provided URL or device-code -page, then wait for the matching completion event: +`thread.run(...)` returns a `TurnResult` containing the final response, +collected items, and token usage. + +## Authentication + +Existing Codex authentication is reused automatically. To start ChatGPT +browser login explicitly: ```python +from openai_codex import Codex + with Codex() as codex: login = codex.login_chatgpt() print(login.auth_url) - completed = login.wait() - print(completed.success) + print(login.wait().success) ``` -Use `login_chatgpt_device_code()` for device-code auth, `handle.cancel()` to -stop an in-progress interactive login, and `logout()` to clear the active -Codex account session. +For device-code login: -## Docs map - -- Golden path tutorial: `docs/getting-started.md` -- API reference (signatures + behavior): `docs/api-reference.md` -- Common decisions and pitfalls: `docs/faq.md` -- Runnable examples index: `examples/README.md` -- Jupyter walkthrough notebook: `notebooks/sdk_walkthrough.ipynb` - -## Examples - -Start here: - -```bash -cd sdk/python -python examples/01_quickstart_constructor/sync.py -python examples/01_quickstart_constructor/async.py +```python +with Codex() as codex: + login = codex.login_chatgpt_device_code() + print(login.verification_url, login.user_code) + login.wait() ``` -## Runtime +For API-key login: -Published SDK builds are pinned to an exact `openai-codex-cli-bin` package -version, and that runtime package carries the platform-specific binary for the -target wheel. The SDK package version and runtime package version must match. +```python +with Codex() as codex: + codex.login_api_key("sk-...") +``` -## Compatibility and versioning +## Built-In Help -- Package: `openai-codex` -- Runtime package: `openai-codex-cli-bin` -- Python: `>=3.10` -- Target protocol: Codex `app-server` JSON-RPC v2 -- Versioning rule: the SDK package version is the underlying Codex runtime version +Use Python's standard `help(openai_codex)`, `help(Codex)`, or +`python -m pydoc openai_codex` documentation tools. -## Notes +## Documentation -- `Codex()` is eager and performs startup + `initialize` in the constructor. -- Use context managers (`with Codex() as codex:`) to ensure shutdown. -- Plain strings are accepted anywhere a turn input is accepted; they are - shorthand for `TextInput(...)`. -- Prefer `thread.run("...")` for the common case. Use `thread.turn(...)` when - you need streaming, steering, or interrupt control. -- For transient overload, use `retry_on_overload` from the package root. +- [Getting started](https://github.com/openai/codex/blob/main/sdk/python/docs/getting-started.md) +- [API reference](https://github.com/openai/codex/blob/main/sdk/python/docs/api-reference.md) +- [FAQ](https://github.com/openai/codex/blob/main/sdk/python/docs/faq.md) +- [Examples](https://github.com/openai/codex/blob/main/sdk/python/examples/README.md) + +The package is licensed under the +[repository Apache License 2.0](https://github.com/openai/codex/blob/main/LICENSE). diff --git a/sdk/python/docs/api-reference.md b/sdk/python/docs/api-reference.md index f56234540b..f003a28511 100644 --- a/sdk/python/docs/api-reference.md +++ b/sdk/python/docs/api-reference.md @@ -1,8 +1,8 @@ -# OpenAI Codex SDK — API Reference +# OpenAI Codex Python SDK (Beta) - API Reference Public surface of `openai_codex` for Codex workflows. -This SDK surface is experimental. Turn streams are routed by turn ID so one client can consume multiple active turns concurrently. +This SDK is in beta. Public APIs may change before `1.0`. Turn streams are routed by turn ID so one client can consume multiple active turns concurrently. Thread starts default to `ApprovalMode.auto_review`; turn starts accept an optional `approval_mode` override. ## Package Entry diff --git a/sdk/python/docs/faq.md b/sdk/python/docs/faq.md index b0c496579b..6fff536a71 100644 --- a/sdk/python/docs/faq.md +++ b/sdk/python/docs/faq.md @@ -1,5 +1,17 @@ # FAQ +## Is the Python SDK stable? + +`openai-codex` is a public beta. Install it with +`pip install openai-codex`; public APIs may change before `1.0`. While beta +releases are the only published SDK releases, pip selects the latest beta. +After a stable release exists, pass `--pre` to opt into newer prereleases. + +## Why does the SDK install a runtime package? + +The SDK and runtime packages are versioned independently. Each SDK release +pins and installs one compatible runtime dependency automatically. + ## Thread vs turn - A `Thread` is conversation state. @@ -84,9 +96,9 @@ This avoids duplicate ways to do the same operation and keeps behavior explicit. Common causes: -- published runtime package (`openai-codex-cli-bin`) is not installed +- installation is incomplete and the pinned `openai-codex-cli-bin` dependency is missing - local `codex_bin` override points to a missing file -- installed Codex runtime version older than the SDK schema +- a custom local Codex executable does not support the SDK operation being used ## Why does a turn "hang"? @@ -99,7 +111,8 @@ A turn is complete only when `turn/completed` arrives for that turn ID. Use `retry_on_overload(...)` for transient overload failures (`ServerBusyError`). -Do not blindly retry all errors. For `InvalidParamsError` or `MethodNotFoundError`, fix inputs or update the runtime/schema version instead. +Do not blindly retry all errors. For `InvalidParamsError` or +`MethodNotFoundError`, fix the input or use the runtime pinned by the SDK. ## Common pitfalls diff --git a/sdk/python/docs/getting-started.md b/sdk/python/docs/getting-started.md index 45271ed64d..fb2c88b4c3 100644 --- a/sdk/python/docs/getting-started.md +++ b/sdk/python/docs/getting-started.md @@ -1,68 +1,64 @@ # Getting Started -This is the fastest path from install to a multi-turn thread using the public SDK surface. +This guide gets a published OpenAI Codex Python SDK beta installation running +with a multi-turn thread. -The SDK is experimental, so the public API and runtime requirements may keep evolving before the first public release. +## 1. Install -## 1) Install - -From repo root: +Install the SDK: ```bash -cd sdk/python -uv sync -source .venv/bin/activate +pip install openai-codex ``` Requirements: - Python `>=3.10` -- uv -- installed `openai-codex-cli-bin` runtime package, or an explicit `codex_bin` override +- An existing Codex account session, or one of the login flows below -## 2) Authenticate when needed +The SDK installs its compatible `openai-codex-cli-bin` runtime dependency +automatically. While beta releases are the only published SDK releases, this +normal install command selects the latest beta. After a stable release exists, +use `pip install --pre openai-codex` to opt into a newer prerelease. -Existing Codex auth state is reused automatically. To authenticate from the SDK, -use the flow that fits your app: +## 2. Authenticate When Needed -```python -from openai_codex import Codex, Sandbox - -with Codex() as codex: - codex.login_api_key("sk-...") - account = codex.account() - print(account.account) -``` - -Interactive ChatGPT browser login returns a handle that carries the URL and the -matching completion event: - -```python -with Codex() as codex: - login = codex.login_chatgpt() - print(login.auth_url) - completed = login.wait() - print(completed.success) -``` - -Device-code login works the same way with -`login_chatgpt_device_code()`, which exposes `verification_url`, `user_code`, -and `wait()`. - -## 3) Run your first turn (sync) +Existing Codex authentication is reused automatically. For ChatGPT browser +login: ```python from openai_codex import Codex with Codex() as codex: - server = codex.metadata.serverInfo - print("Server:", None if server is None else server.name, None if server is None else server.version) + login = codex.login_chatgpt() + print(login.auth_url) + print(login.wait().success) +``` - thread = codex.thread_start( - model="gpt-5.4", - config={"model_reasoning_effort": "high"}, - sandbox=Sandbox.workspace_write, - ) +For device-code login: + +```python +with Codex() as codex: + login = codex.login_chatgpt_device_code() + print(login.verification_url, login.user_code) + print(login.wait().success) +``` + +For API-key login: + +```python +with Codex() as codex: + codex.login_api_key("sk-...") + print(codex.account().account) +``` + +## 3. Run A Turn + +```python +from openai_codex import Codex, Sandbox + +with Codex() as codex: + thread = codex.thread_start(sandbox=Sandbox.workspace_write) result = thread.run("Say hello in one sentence.") print("Thread:", thread.id) @@ -70,19 +66,15 @@ with Codex() as codex: print("Items:", len(result.items)) ``` -What happened: +`Thread.run(...)` starts a turn, waits for completion, and returns +`TurnResult`. Plain strings are shorthand for `TextInput(...)`. -- `Codex()` started and initialized `codex app-server`. -- `thread_start(...)` created a thread. -- `thread.run("...")` started a turn, consumed events until completion, and returned `TurnResult` with turn metadata, final assistant response, collected items, and usage. -- `result.final_response` is `None` when no final-answer or phase-less assistant message item completes for the turn. -- plain strings are accepted anywhere a turn input is accepted; typed inputs are still available for multimodal and structured cases -- use `thread.turn(...)` when you need a `TurnHandle` for streaming, steering, or interrupting before collecting `TurnResult` -- one client can consume multiple active turns concurrently; turn streams are routed by turn ID +Use `Thread.turn(...)` when you need a `TurnHandle` for streaming, steering, +or interrupting an active turn. -## 4) Change sandbox access +## 4. Choose Sandbox Access -Use one enum for the initial sandbox and for later turn overrides: +Use one enum for the initial thread and later turn overrides: ```python from openai_codex import Codex, Sandbox @@ -96,40 +88,44 @@ with Codex() as codex: Available presets: - `Sandbox.read_only`: read files without allowing writes. -- `Sandbox.workspace_write`: the normal default for projects with a recorded trust decision; read files and write inside the workspace and configured writable roots. +- `Sandbox.workspace_write`: read files and write inside the workspace and + configured writable roots; this is the normal default for workspace work. - `Sandbox.full_access`: run without filesystem access restrictions. -When `sandbox=` is omitted, Codex uses its configured default. A turn -override also becomes the sandbox for subsequent turns on that thread. +When `sandbox=` is omitted, Codex uses its configured default. A turn override +also applies to subsequent turns on that thread. -## 5) Continue the same thread (multi-turn) +## 5. Continue A Thread ```python from openai_codex import Codex with Codex() as codex: - thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) - - first = thread.run("Summarize Rust ownership in 2 bullets.") - second = thread.run("Now explain it to a Python developer.") - - print("first:", first.final_response) - print("second:", second.final_response) + thread = codex.thread_start() + thread.run("Summarize Rust ownership in two bullets.") + result = thread.run("Now explain it to a Python developer.") + print(result.final_response) ``` -## 6) Async parity +To resume a stored thread later: -Use `async with AsyncCodex()` as the normal async entrypoint. `AsyncCodex` -initializes lazily, and context entry makes startup/shutdown explicit. +```python +with Codex() as codex: + thread = codex.thread_resume("thr_123") + print(thread.run("Continue where we left off.").final_response) +``` + +## 6. Use The Async Client ```python import asyncio -from openai_codex import AsyncCodex + +from openai_codex import AsyncCodex, Sandbox async def main() -> None: async with AsyncCodex() as codex: - thread = await codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"}) + thread = await codex.thread_start(sandbox=Sandbox.workspace_write) result = await thread.run("Continue where we left off.") print(result.final_response) @@ -137,30 +133,36 @@ async def main() -> None: asyncio.run(main()) ``` -## 7) Resume an existing thread +## 7. Get Help + +Python's built-in documentation tools cover the curated SDK surface: ```python -from openai_codex import Codex +import openai_codex +from openai_codex import Codex, CodexConfig -THREAD_ID = "thr_123" # replace with a real id - -with Codex() as codex: - thread = codex.thread_resume(THREAD_ID) - result = thread.run("Continue where we left off.") - print(result.final_response) +help(openai_codex) +help(Codex) +help(CodexConfig) ``` -## 8) Public Codex protocol types - -The convenience wrappers live at the package root. Public Codex protocol value and -event types live under: - -```python -from openai_codex.types import ThreadReadResponse, Turn, TurnStatus +```bash +python -m pydoc openai_codex ``` -## 9) Next stops +## Developing From This Repository -- API surface and signatures: `docs/api-reference.md` -- Common decisions/pitfalls: `docs/faq.md` -- End-to-end runnable examples: `examples/README.md` +Contributors working from a checkout can install development dependencies from +the repository: + +```bash +cd sdk/python +uv sync --extra dev +source .venv/bin/activate +``` + +## Next Stops + +- [API reference](https://github.com/openai/codex/blob/main/sdk/python/docs/api-reference.md) +- [FAQ](https://github.com/openai/codex/blob/main/sdk/python/docs/faq.md) +- [Runnable examples](https://github.com/openai/codex/blob/main/sdk/python/examples/README.md) diff --git a/sdk/python/examples/README.md b/sdk/python/examples/README.md index eef3893721..8efeb75b14 100644 --- a/sdk/python/examples/README.md +++ b/sdk/python/examples/README.md @@ -14,25 +14,30 @@ multimodal or structured input lists. ## Prerequisites - Python `>=3.10` -- Install SDK dependencies for the same Python interpreter you will use to run examples +- Install the SDK for the same Python interpreter you will use to run examples -Recommended setup (from `sdk/python`): +Install the published beta: ```bash -uv sync +python -m pip install openai-codex +``` + +The SDK installs its pinned `openai-codex-cli-bin` runtime dependency. +The pinned runtime version comes from the SDK package dependency. + +## Run From A Checkout + +Contributors using these checked-in scripts should install development +dependencies from `sdk/python`: + +```bash +uv sync --extra dev source .venv/bin/activate ``` -When running examples from this repo checkout, the SDK source uses the local -tree and does not bundle a runtime binary. The helper in `examples/_bootstrap.py` -uses the installed `openai-codex-cli-bin` runtime package. - -If the pinned `openai-codex-cli-bin` runtime is not already installed, the bootstrap -will download the matching GitHub release artifact, stage a temporary local -`openai-codex-cli-bin` package, install it into your active interpreter, and clean up -the temporary files afterward. - -The pinned runtime version comes from the SDK package dependency. +The examples bootstrap local SDK imports from `sdk/python/src`. If the pinned +runtime is not already installed, the bootstrap installs the matching runtime +package for the active interpreter and cleans up temporary files afterward. ## Run examples @@ -43,10 +48,7 @@ python examples//sync.py python examples//async.py ``` -The examples bootstrap local imports from `sdk/python/src` automatically, so no -SDK wheel install is required. You only need the Python dependencies for your -active interpreter and an installed `openai-codex-cli-bin` runtime package (either -already present or automatically provisioned by the bootstrap). +The checked-in examples use the local SDK source tree automatically. ## Recommended first run diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml index b7c890d06e..9c93be69a5 100644 --- a/sdk/python/pyproject.toml +++ b/sdk/python/pyproject.toml @@ -1,33 +1,28 @@ [build-system] -requires = ["hatchling>=1.24.0"] +requires = ["hatchling>=1.27.0"] build-backend = "hatchling.build" [project] name = "openai-codex" -version = "0.131.0a4" -description = "Python SDK for Codex app-server v2" +version = "0.0.0-dev" +description = "Python SDK for Codex" readme = "README.md" requires-python = ">=3.10" -license = { text = "Apache-2.0" } +license = "Apache-2.0" authors = [{ name = "OpenAI" }] -keywords = ["codex", "json-rpc", "sdk", "llm", "app-server"] +keywords = ["codex", "sdk", "llm", "ai", "agents"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", "Topic :: Software Development :: Libraries :: Python Modules", ] -dependencies = ["pydantic>=2.12", "openai-codex-cli-bin==0.131.0a4"] +dependencies = ["pydantic>=2.12", "openai-codex-cli-bin==0.132.0"] [project.urls] Homepage = "https://github.com/openai/codex" Repository = "https://github.com/openai/codex" Issues = "https://github.com/openai/codex/issues" +Documentation = "https://github.com/openai/codex/tree/main/sdk/python/docs" [project.optional-dependencies] dev = ["pytest>=8.0", "datamodel-code-generator==0.31.2", "ruff>=0.15.8"] @@ -51,9 +46,6 @@ include = [ include = [ "src/openai_codex/**", "README.md", - "CHANGELOG.md", - "CONTRIBUTING.md", - "RELEASE_CHECKLIST.md", "pyproject.toml", ] @@ -86,10 +78,10 @@ combine-as-imports = true [tool.uv] exclude-newer = "7 days" -exclude-newer-package = { openai-codex-cli-bin = "2026-05-10T00:00:00Z" } +exclude-newer-package = { openai-codex-cli-bin = "2026-05-20T21:00:00Z" } index-strategy = "first-index" [tool.uv.pip] exclude-newer = "7 days" -exclude-newer-package = { openai-codex-cli-bin = "2026-05-10T00:00:00Z" } +exclude-newer-package = { openai-codex-cli-bin = "2026-05-20T21:00:00Z" } index-strategy = "first-index" diff --git a/sdk/python/scripts/update_sdk_artifacts.py b/sdk/python/scripts/update_sdk_artifacts.py index b20f814f66..1742ced547 100755 --- a/sdk/python/scripts/update_sdk_artifacts.py +++ b/sdk/python/scripts/update_sdk_artifacts.py @@ -216,25 +216,8 @@ def _rewrite_project_name(pyproject_text: str, name: str) -> str: return updated -def _rewrite_sdk_runtime_dependency(pyproject_text: str, runtime_version: str) -> str: - match = re.search(r"^dependencies = \[(.*?)\]$", pyproject_text, flags=re.MULTILINE) - if match is None: - raise RuntimeError("Could not find dependencies array in sdk/python/pyproject.toml") - - raw_items = [item.strip() for item in match.group(1).split(",") if item.strip()] - raw_items = [ - item - for item in raw_items - if RUNTIME_DISTRIBUTION_NAME.removeprefix("openai-") not in item - and RUNTIME_DISTRIBUTION_NAME not in item - ] - raw_items.append(f'"{RUNTIME_DISTRIBUTION_NAME}=={runtime_version}"') - replacement = "dependencies = [\n " + ",\n ".join(raw_items) + ",\n]" - return pyproject_text[: match.start()] + replacement + pyproject_text[match.end() :] - - -def stage_python_sdk_package(staging_dir: Path, codex_version: str) -> Path: - package_version = normalize_codex_version(codex_version) +def stage_python_sdk_package(staging_dir: Path, sdk_version: str) -> Path: + package_version = normalize_codex_version(sdk_version) _copy_package_tree(sdk_root(), staging_dir) sdk_bin_dir = staging_dir / "src" / "openai_codex" / "bin" if sdk_bin_dir.exists(): @@ -244,7 +227,6 @@ def stage_python_sdk_package(staging_dir: Path, codex_version: str) -> Path: pyproject_text = pyproject_path.read_text() pyproject_text = _rewrite_project_name(pyproject_text, SDK_DISTRIBUTION_NAME) pyproject_text = _rewrite_project_version(pyproject_text, package_version) - pyproject_text = _rewrite_sdk_runtime_dependency(pyproject_text, package_version) pyproject_path.write_text(pyproject_text) return staging_dir @@ -936,6 +918,7 @@ def _render_codex_block( *_approval_mode_start_signature_lines(), *_kw_signature_lines(thread_start_fields), " ) -> Thread:", + ' """Create a new Codex conversation thread."""', _approval_mode_assignment_line("_approval_mode_settings"), " params = ThreadStartParams(", *_approval_mode_model_arg_lines(), @@ -949,6 +932,7 @@ def _render_codex_block( " *,", *_kw_signature_lines(thread_list_fields), " ) -> ThreadListResponse:", + ' """List saved conversation threads."""', " params = ThreadListParams(", *_model_arg_lines(thread_list_fields), " )", @@ -961,6 +945,7 @@ def _render_codex_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(resume_fields), " ) -> Thread:", + ' """Resume an existing conversation thread by ID."""', _approval_mode_assignment_line("_approval_mode_override_settings"), " params = ThreadResumeParams(", " thread_id=thread_id,", @@ -977,6 +962,7 @@ def _render_codex_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(fork_fields), " ) -> Thread:", + ' """Create a new thread from an existing thread."""', _approval_mode_assignment_line("_approval_mode_override_settings"), " params = ThreadForkParams(", " thread_id=thread_id,", @@ -987,9 +973,11 @@ def _render_codex_block( " return Thread(self._client, forked.thread.id)", "", " def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:", + ' """Archive a stored conversation thread."""', " return self._client.thread_archive(thread_id)", "", " def thread_unarchive(self, thread_id: str) -> Thread:", + ' """Restore an archived conversation thread."""', " unarchived = self._client.thread_unarchive(thread_id)", " return Thread(self._client, unarchived.thread.id)", ] @@ -1009,6 +997,7 @@ def _render_async_codex_block( *_approval_mode_start_signature_lines(), *_kw_signature_lines(thread_start_fields), " ) -> AsyncThread:", + ' """Create a new Codex conversation thread."""', " await self._ensure_initialized()", _approval_mode_assignment_line("_approval_mode_settings"), " params = ThreadStartParams(", @@ -1023,6 +1012,7 @@ def _render_async_codex_block( " *,", *_kw_signature_lines(thread_list_fields), " ) -> ThreadListResponse:", + ' """List saved conversation threads."""', " await self._ensure_initialized()", " params = ThreadListParams(", *_model_arg_lines(thread_list_fields), @@ -1036,6 +1026,7 @@ def _render_async_codex_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(resume_fields), " ) -> AsyncThread:", + ' """Resume an existing conversation thread by ID."""', " await self._ensure_initialized()", _approval_mode_assignment_line("_approval_mode_override_settings"), " params = ThreadResumeParams(", @@ -1053,6 +1044,7 @@ def _render_async_codex_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(fork_fields), " ) -> AsyncThread:", + ' """Create a new thread from an existing thread."""', " await self._ensure_initialized()", _approval_mode_assignment_line("_approval_mode_override_settings"), " params = ThreadForkParams(", @@ -1064,10 +1056,12 @@ def _render_async_codex_block( " return AsyncThread(self, forked.thread.id)", "", " async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse:", + ' """Archive a stored conversation thread."""', " await self._ensure_initialized()", " return await self._client.thread_archive(thread_id)", "", " async def thread_unarchive(self, thread_id: str) -> AsyncThread:", + ' """Restore an archived conversation thread."""', " await self._ensure_initialized()", " unarchived = await self._client.thread_unarchive(thread_id)", " return AsyncThread(self, unarchived.thread.id)", @@ -1086,6 +1080,7 @@ def _render_thread_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(turn_fields), " ) -> TurnHandle:", + ' """Start a turn and return a handle for streaming or control."""', " wire_input = _to_wire_input(_normalize_run_input(input))", _approval_mode_assignment_line("_approval_mode_override_settings"), " params = TurnStartParams(", @@ -1111,6 +1106,7 @@ def _render_async_thread_block( *_approval_mode_override_signature_lines(), *_kw_signature_lines(turn_fields), " ) -> AsyncTurnHandle:", + ' """Start a turn and return a handle for streaming or control."""', " await self._codex._ensure_initialized()", " wire_input = _to_wire_input(_normalize_run_input(input))", _approval_mode_assignment_line("_approval_mode_override_settings"), @@ -1229,28 +1225,20 @@ def build_parser() -> argparse.ArgumentParser: stage_sdk_parser = subparsers.add_parser( "stage-sdk", - help="Stage a releasable SDK package pinned to a runtime version", + help="Stage a releasable SDK package while preserving its reviewed runtime pin", ) stage_sdk_parser.add_argument( "staging_dir", type=Path, help="Output directory for the staged SDK package", ) - stage_sdk_parser.add_argument( - "--codex-version", - help=( - "Codex release version to write into the staged SDK package and exact " - f"{RUNTIME_DISTRIBUTION_NAME} dependency. Accepts PEP 440 versions " - "or release tags such as rust-v0.116.0-alpha.1." - ), - ) - stage_sdk_parser.add_argument( - "--runtime-version", - help=argparse.SUPPRESS, - ) stage_sdk_parser.add_argument( "--sdk-version", - help=argparse.SUPPRESS, + required=True, + help=( + "Python SDK release version to write into the staged package. " + "Accepts PEP 440 versions such as 0.1.0b1." + ), ) stage_runtime_parser = subparsers.add_parser( @@ -1269,15 +1257,12 @@ def build_parser() -> argparse.ArgumentParser: ) stage_runtime_parser.add_argument( "--codex-version", + required=True, help=( "Codex release version to write into the staged runtime package. " "Accepts PEP 440 versions or release tags such as rust-v0.116.0-alpha.1." ), ) - stage_runtime_parser.add_argument( - "--runtime-version", - help=argparse.SUPPRESS, - ) stage_runtime_parser.add_argument( "--platform-tag", help=( @@ -1301,40 +1286,19 @@ def default_cli_ops() -> CliOps: ) -def _resolve_codex_version(args: argparse.Namespace) -> str: - versions = [ - value - for value in ( - getattr(args, "codex_version", None), - getattr(args, "runtime_version", None), - getattr(args, "sdk_version", None), - ) - if value is not None - ] - if not versions: - raise RuntimeError("Pass --codex-version to stage Python release artifacts") - - normalized_versions = [normalize_codex_version(version) for version in versions] - if len(set(normalized_versions)) != 1: - raise RuntimeError("SDK and runtime package versions must match; pass one --codex-version") - return normalized_versions[0] - - def run_command(args: argparse.Namespace, ops: CliOps) -> None: if args.command == "generate-types": ops.generate_types() elif args.command == "stage-sdk": - codex_version = _resolve_codex_version(args) ops.generate_types() ops.stage_python_sdk_package( args.staging_dir, - codex_version, + normalize_codex_version(args.sdk_version), ) elif args.command == "stage-runtime": - codex_version = _resolve_codex_version(args) ops.stage_python_runtime_package( args.staging_dir, - codex_version, + normalize_codex_version(args.codex_version), args.package_archive.resolve(), args.platform_tag, ) diff --git a/sdk/python/src/openai_codex/__init__.py b/sdk/python/src/openai_codex/__init__.py index 3453388498..2829958dc1 100644 --- a/sdk/python/src/openai_codex/__init__.py +++ b/sdk/python/src/openai_codex/__init__.py @@ -1,3 +1,17 @@ +"""Python SDK for running Codex workflows. + +Start with :class:`Codex` for synchronous applications or +:class:`AsyncCodex` for async applications. Most programs create a thread and +run a turn:: + + from openai_codex import Codex, Sandbox + + with Codex() as codex: + thread = codex.thread_start(sandbox=Sandbox.workspace_write) + result = thread.run("Describe this project.") + print(result.final_response) +""" + from ._version import __version__ from .api import ( ApprovalMode, diff --git a/sdk/python/src/openai_codex/_inputs.py b/sdk/python/src/openai_codex/_inputs.py index e3cd1c3969..a6e5e7b528 100644 --- a/sdk/python/src/openai_codex/_inputs.py +++ b/sdk/python/src/openai_codex/_inputs.py @@ -7,27 +7,37 @@ from .models import JsonObject @dataclass(slots=True) class TextInput: + """Text supplied to a turn or steering request.""" + text: str @dataclass(slots=True) class ImageInput: + """Remote image URL supplied as turn input.""" + url: str @dataclass(slots=True) class LocalImageInput: + """Local image path supplied as turn input.""" + path: str @dataclass(slots=True) class SkillInput: + """Named skill reference supplied as turn input.""" + name: str path: str @dataclass(slots=True) class MentionInput: + """Named resource mention supplied as turn input.""" + name: str path: str diff --git a/sdk/python/src/openai_codex/_run.py b/sdk/python/src/openai_codex/_run.py index f5c72d5109..8a66923704 100644 --- a/sdk/python/src/openai_codex/_run.py +++ b/sdk/python/src/openai_codex/_run.py @@ -20,6 +20,8 @@ from .models import Notification @dataclass(slots=True) class TurnResult: + """Collected result returned after a turn completes.""" + id: str status: TurnStatus error: TurnError | None diff --git a/sdk/python/src/openai_codex/api.py b/sdk/python/src/openai_codex/api.py index f27de49ebc..6fc9a8243d 100644 --- a/sdk/python/src/openai_codex/api.py +++ b/sdk/python/src/openai_codex/api.py @@ -73,7 +73,11 @@ from .models import InitializeResponse, JsonObject, Notification class Codex: - """Typed Python client for Codex workflows.""" + """Synchronous client for creating threads and running Codex turns. + + The client starts its runtime connection during construction. Use it as a + context manager so resources are closed promptly. + """ def __init__(self, config: CodexConfig | None = None) -> None: self._client = CodexClient(config=config) @@ -143,6 +147,7 @@ class Codex: session_start_source: ThreadStartSource | None = None, thread_source: ThreadSource | None = None, ) -> Thread: + """Create a new Codex conversation thread.""" approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode) params = ThreadStartParams( approval_policy=approval_policy, @@ -178,6 +183,7 @@ class Codex: source_kinds: list[ThreadSourceKind] | None = None, use_state_db_only: bool | None = None, ) -> ThreadListResponse: + """List saved conversation threads.""" params = ThreadListParams( archived=archived, cursor=cursor, @@ -207,6 +213,7 @@ class Codex: sandbox: Sandbox | None = None, service_tier: str | None = None, ) -> Thread: + """Resume an existing conversation thread by ID.""" approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) params = ThreadResumeParams( thread_id=thread_id, @@ -241,6 +248,7 @@ class Codex: service_tier: str | None = None, thread_source: ThreadSource | None = None, ) -> Thread: + """Create a new thread from an existing thread.""" approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) params = ThreadForkParams( thread_id=thread_id, @@ -261,15 +269,18 @@ class Codex: return Thread(self._client, forked.thread.id) def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: + """Archive a stored conversation thread.""" return self._client.thread_archive(thread_id) def thread_unarchive(self, thread_id: str) -> Thread: + """Restore an archived conversation thread.""" unarchived = self._client.thread_unarchive(thread_id) return Thread(self._client, unarchived.thread.id) # END GENERATED: Codex.flat_methods def models(self, *, include_hidden: bool = False) -> ModelListResponse: + """List available models reported by Codex.""" return self._client.model_list(include_hidden=include_hidden) @@ -376,6 +387,7 @@ class AsyncCodex: session_start_source: ThreadStartSource | None = None, thread_source: ThreadSource | None = None, ) -> AsyncThread: + """Create a new Codex conversation thread.""" await self._ensure_initialized() approval_policy, approvals_reviewer = _approval_mode_settings(approval_mode) params = ThreadStartParams( @@ -412,6 +424,7 @@ class AsyncCodex: source_kinds: list[ThreadSourceKind] | None = None, use_state_db_only: bool | None = None, ) -> ThreadListResponse: + """List saved conversation threads.""" await self._ensure_initialized() params = ThreadListParams( archived=archived, @@ -442,6 +455,7 @@ class AsyncCodex: sandbox: Sandbox | None = None, service_tier: str | None = None, ) -> AsyncThread: + """Resume an existing conversation thread by ID.""" await self._ensure_initialized() approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) params = ThreadResumeParams( @@ -477,6 +491,7 @@ class AsyncCodex: service_tier: str | None = None, thread_source: ThreadSource | None = None, ) -> AsyncThread: + """Create a new thread from an existing thread.""" await self._ensure_initialized() approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) params = ThreadForkParams( @@ -498,10 +513,12 @@ class AsyncCodex: return AsyncThread(self, forked.thread.id) async def thread_archive(self, thread_id: str) -> ThreadArchiveResponse: + """Archive a stored conversation thread.""" await self._ensure_initialized() return await self._client.thread_archive(thread_id) async def thread_unarchive(self, thread_id: str) -> AsyncThread: + """Restore an archived conversation thread.""" await self._ensure_initialized() unarchived = await self._client.thread_unarchive(thread_id) return AsyncThread(self, unarchived.thread.id) @@ -515,6 +532,8 @@ class AsyncCodex: @dataclass(slots=True) class Thread: + """Synchronous conversation thread used to run one or more turns.""" + _client: CodexClient id: str @@ -532,6 +551,7 @@ class Thread: service_tier: str | None = None, summary: ReasoningSummary | None = None, ) -> TurnResult: + """Run a complete turn and collect its final result.""" turn = self.turn( input, approval_mode=approval_mode, @@ -565,6 +585,7 @@ class Thread: service_tier: str | None = None, summary: ReasoningSummary | None = None, ) -> TurnHandle: + """Start a turn and return a handle for streaming or control.""" wire_input = _to_wire_input(_normalize_run_input(input)) approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) params = TurnStartParams( @@ -587,6 +608,7 @@ class Thread: # END GENERATED: Thread.flat_methods def read(self, *, include_turns: bool = False) -> ThreadReadResponse: + """Read this thread, optionally including its turn history.""" return self._client.thread_read(self.id, include_turns=include_turns) def set_name(self, name: str) -> ThreadSetNameResponse: @@ -598,6 +620,8 @@ class Thread: @dataclass(slots=True) class AsyncThread: + """Asynchronous conversation thread used to run one or more turns.""" + _codex: AsyncCodex id: str @@ -615,6 +639,7 @@ class AsyncThread: service_tier: str | None = None, summary: ReasoningSummary | None = None, ) -> TurnResult: + """Run a complete turn asynchronously and collect its final result.""" turn = await self.turn( input, approval_mode=approval_mode, @@ -648,6 +673,7 @@ class AsyncThread: service_tier: str | None = None, summary: ReasoningSummary | None = None, ) -> AsyncTurnHandle: + """Start a turn and return a handle for streaming or control.""" await self._codex._ensure_initialized() wire_input = _to_wire_input(_normalize_run_input(input)) approval_policy, approvals_reviewer = _approval_mode_override_settings(approval_mode) @@ -675,6 +701,7 @@ class AsyncThread: # END GENERATED: AsyncThread.flat_methods async def read(self, *, include_turns: bool = False) -> ThreadReadResponse: + """Read this thread, optionally including its turn history.""" await self._codex._ensure_initialized() return await self._codex._client.thread_read(self.id, include_turns=include_turns) @@ -689,11 +716,14 @@ class AsyncThread: @dataclass(slots=True) class TurnHandle: + """Control and consume a synchronous turn after it has started.""" + _client: CodexClient thread_id: str id: str def steer(self, input: RunInput) -> TurnSteerResponse: + """Send additional input to this active turn.""" return self._client.turn_steer( self.thread_id, self.id, @@ -701,6 +731,7 @@ class TurnHandle: ) def interrupt(self) -> TurnInterruptResponse: + """Request interruption of this active turn.""" return self._client.turn_interrupt(self.thread_id, self.id) def stream(self) -> Iterator[Notification]: @@ -720,6 +751,7 @@ class TurnHandle: self._client.unregister_turn_notifications(self.id) def run(self) -> TurnResult: + """Consume the turn stream and return its completed result.""" stream = self.stream() try: return _collect_turn_result(stream, turn_id=self.id) @@ -729,11 +761,14 @@ class TurnHandle: @dataclass(slots=True) class AsyncTurnHandle: + """Control and consume an asynchronous turn after it has started.""" + _codex: AsyncCodex thread_id: str id: str async def steer(self, input: RunInput) -> TurnSteerResponse: + """Send additional input to this active turn.""" await self._codex._ensure_initialized() return await self._codex._client.turn_steer( self.thread_id, @@ -742,6 +777,7 @@ class AsyncTurnHandle: ) async def interrupt(self) -> TurnInterruptResponse: + """Request interruption of this active turn.""" await self._codex._ensure_initialized() return await self._codex._client.turn_interrupt(self.thread_id, self.id) @@ -763,6 +799,7 @@ class AsyncTurnHandle: self._codex._client.unregister_turn_notifications(self.id) async def run(self) -> TurnResult: + """Consume the turn stream and return its completed result.""" stream = self.stream() try: return await _collect_async_turn_result(stream, turn_id=self.id) diff --git a/sdk/python/src/openai_codex/client.py b/sdk/python/src/openai_codex/client.py index a97e12f658..9951d6d1f3 100644 --- a/sdk/python/src/openai_codex/client.py +++ b/sdk/python/src/openai_codex/client.py @@ -172,6 +172,12 @@ def _resolve_codex_bin(config: "CodexConfig") -> Path: @dataclass(slots=True) class CodexConfig: + """Configuration for launching and identifying the local Codex runtime. + + Most callers can use ``Codex()`` without configuration. Set ``codex_bin`` + only when intentionally using a specific local Codex executable. + """ + codex_bin: str | None = None launch_args_override: tuple[str, ...] | None = None config_overrides: tuple[str, ...] = () diff --git a/sdk/python/src/openai_codex/errors.py b/sdk/python/src/openai_codex/errors.py index 63ff7d2d2a..db3e7238d3 100644 --- a/sdk/python/src/openai_codex/errors.py +++ b/sdk/python/src/openai_codex/errors.py @@ -26,23 +26,23 @@ class CodexRpcError(JsonRpcError): class ParseError(CodexRpcError): - pass + """Raised when a request or response cannot be parsed.""" class InvalidRequestError(CodexRpcError): - pass + """Raised when the runtime rejects the request shape.""" class MethodNotFoundError(CodexRpcError): - pass + """Raised when the requested operation is unavailable.""" class InvalidParamsError(CodexRpcError): - pass + """Raised when an operation receives invalid parameters.""" class InternalRpcError(CodexRpcError): - pass + """Raised when the runtime reports an internal RPC failure.""" class ServerBusyError(CodexRpcError): diff --git a/sdk/python/src/openai_codex/generated/v2_all.py b/sdk/python/src/openai_codex/generated/v2_all.py index 363d87495c..85120b8293 100644 --- a/sdk/python/src/openai_codex/generated/v2_all.py +++ b/sdk/python/src/openai_codex/generated/v2_all.py @@ -49,26 +49,24 @@ class AccountLoginCompletedNotification(BaseModel): success: bool -class AdditionalWritableRootActivePermissionProfileModification(BaseModel): +class ActivePermissionProfile(BaseModel): model_config = ConfigDict( populate_by_name=True, ) - path: AbsolutePathBuf - type: Annotated[ - Literal["additionalWritableRoot"], - Field(title="AdditionalWritableRootActivePermissionProfileModificationType"), + extends: Annotated[ + str | None, + Field( + description="Parent profile identifier once permissions profiles support inheritance. This is currently always `null`." + ), + ] = None + id: Annotated[ + str, + Field( + description="Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile." + ), ] -class ActivePermissionProfileModification( - RootModel[AdditionalWritableRootActivePermissionProfileModification] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: AdditionalWritableRootActivePermissionProfileModification - - class AddCreditsNudgeCreditType(Enum): credits = "credits" usage_limit = "usage_limit" @@ -597,6 +595,12 @@ class UserConfigLayerSource(BaseModel): description="This is the path to the user's config.toml file, though it is not guaranteed to exist." ), ] + profile: Annotated[ + str | None, + Field( + description="Name of the selected profile-v2 config layered on top of the base user config, when this layer represents one." + ), + ] = None type: Annotated[Literal["user"], Field(title="UserConfigLayerSourceType")] @@ -680,6 +684,7 @@ class CommandConfiguredHookHandler(BaseModel): ) async_: Annotated[bool, Field(alias="async")] command: str + command_windows: Annotated[str | None, Field(alias="commandWindows")] = None status_message: Annotated[str | None, Field(alias="statusMessage")] = None timeout_sec: Annotated[int | None, Field(alias="timeoutSec", ge=0)] = None type: Annotated[Literal["command"], Field(title="CommandConfiguredHookHandlerType")] @@ -842,6 +847,13 @@ class ExperimentalFeatureListParams(BaseModel): int | None, Field(description="Optional page size; defaults to a reasonable server-side value.", ge=0), ] = None + thread_id: Annotated[ + str | None, + Field( + alias="threadId", + description="Optional loaded thread id. Pass this when showing feature state for an existing thread so enablement is computed from that thread's refreshed config, including project-local config for the thread's cwd.", + ), + ] = None class ExperimentalFeatureStage(Enum): @@ -1014,6 +1026,18 @@ class FileSystemSpecialPath( ) +class ForcedChatgptWorkspaceIds(RootModel[str | list[str]]): + model_config = ConfigDict( + populate_by_name=True, + ) + root: Annotated[ + str | list[str], + Field( + description="Backward-compatible API shape for ChatGPT workspace login restrictions." + ), + ] + + class ForcedLoginMethod(Enum): chatgpt = "chatgpt" api = "api" @@ -1482,8 +1506,6 @@ class HooksListParams(BaseModel): class ImageDetail(Enum): - auto = "auto" - low = "low" high = "high" original = "original" @@ -2166,66 +2188,6 @@ class PatchChangeKind( root: AddPatchChangeKind | DeletePatchChangeKind | UpdatePatchChangeKind -class DisabledPermissionProfile(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[Literal["disabled"], Field(title="DisabledPermissionProfileType")] - - -class UnrestrictedPermissionProfileFileSystemPermissions(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - type: Annotated[ - Literal["unrestricted"], - Field(title="UnrestrictedPermissionProfileFileSystemPermissionsType"), - ] - - -class AdditionalWritableRootPermissionProfileModificationParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - path: AbsolutePathBuf - type: Annotated[ - Literal["additionalWritableRoot"], - Field(title="AdditionalWritableRootPermissionProfileModificationParamsType"), - ] - - -class PermissionProfileModificationParams( - RootModel[AdditionalWritableRootPermissionProfileModificationParams] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: AdditionalWritableRootPermissionProfileModificationParams - - -class PermissionProfileNetworkPermissions(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - enabled: bool - - -class ProfilePermissionProfileSelectionParams(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - id: str - modifications: list[PermissionProfileModificationParams] | None = None - type: Annotated[Literal["profile"], Field(title="ProfilePermissionProfileSelectionParamsType")] - - -class PermissionProfileSelectionParams(RootModel[ProfilePermissionProfileSelectionParams]): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ProfilePermissionProfileSelectionParams - - class Personality(Enum): none = "none" friendly = "friendly" @@ -2298,6 +2260,23 @@ class PluginInstallResponse(BaseModel): auth_policy: Annotated[PluginAuthPolicy, Field(alias="authPolicy")] +class PluginInstalledParams(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + cwds: Annotated[ + list[AbsolutePathBuf] | None, + Field(description="Optional working directories used to discover repo marketplaces."), + ] = None + install_suggestion_plugin_names: Annotated[ + list[str] | None, + Field( + alias="installSuggestionPluginNames", + description="Additional uninstalled plugin names that should be returned when present locally. This is used by mention surfaces that intentionally expose install entrypoints.", + ), + ] = None + + class PluginInterface(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -2385,6 +2364,26 @@ class PluginReadParams(BaseModel): remote_marketplace_name: Annotated[str | None, Field(alias="remoteMarketplaceName")] = None +class PluginShareCheckoutParams(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + remote_plugin_id: Annotated[str, Field(alias="remotePluginId")] + + +class PluginShareCheckoutResponse(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + marketplace_name: Annotated[str, Field(alias="marketplaceName")] + marketplace_path: Annotated[AbsolutePathBuf, Field(alias="marketplacePath")] + plugin_id: Annotated[str, Field(alias="pluginId")] + plugin_name: Annotated[str, Field(alias="pluginName")] + plugin_path: Annotated[AbsolutePathBuf, Field(alias="pluginPath")] + remote_plugin_id: Annotated[str, Field(alias="remotePluginId")] + remote_version: Annotated[str | None, Field(alias="remoteVersion")] = None + + class PluginShareDeleteParams(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -2745,6 +2744,7 @@ class RemoteControlStatusChangedNotification(BaseModel): ) environment_id: Annotated[str | None, Field(alias="environmentId")] = None installation_id: Annotated[str, Field(alias="installationId")] + server_name: Annotated[str, Field(alias="serverName")] status: RemoteControlConnectionStatus @@ -2911,6 +2911,13 @@ class CompactionResponseItem(BaseModel): type: Annotated[Literal["compaction"], Field(title="CompactionResponseItemType")] +class CompactionTriggerResponseItem(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + type: Annotated[Literal["compaction_trigger"], Field(title="CompactionTriggerResponseItemType")] + + class ContextCompactionResponseItem(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -3627,6 +3634,8 @@ class ThreadGoalClearedNotification(BaseModel): class ThreadGoalStatus(Enum): active = "active" paused = "paused" + blocked = "blocked" + usage_limited = "usageLimited" budget_limited = "budgetLimited" complete = "complete" @@ -4308,6 +4317,7 @@ class ImageUserInput(BaseModel): model_config = ConfigDict( populate_by_name=True, ) + detail: ImageDetail | None = None type: Annotated[Literal["image"], Field(title="ImageUserInputType")] url: str @@ -4316,6 +4326,7 @@ class LocalImageUserInput(BaseModel): model_config = ConfigDict( populate_by_name=True, ) + detail: ImageDetail | None = None path: str type: Annotated[Literal["localImage"], Field(title="LocalImageUserInputType")] @@ -4525,30 +4536,6 @@ class AccountUpdatedNotification(BaseModel): plan_type: Annotated[PlanType | None, Field(alias="planType")] = None -class ActivePermissionProfile(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - extends: Annotated[ - str | None, - Field( - description="Parent profile identifier once permissions profiles support inheritance. This is currently always `null`." - ), - ] = None - id: Annotated[ - str, - Field( - description="Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile." - ), - ] - modifications: Annotated[ - list[ActivePermissionProfileModification] | None, - Field( - description="Bounded user-requested modifications applied on top of the named profile, if any." - ), - ] = [] - - class AppConfig(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -4790,6 +4777,15 @@ class PluginListRequest(BaseModel): params: PluginListParams +class PluginInstalledRequest(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + id: RequestId + method: Annotated[Literal["plugin/installed"], Field(title="Plugin/installedRequestMethod")] + params: PluginInstalledParams + + class PluginReadRequest(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -4817,6 +4813,17 @@ class PluginShareListRequest(BaseModel): params: PluginShareListParams +class PluginShareCheckoutRequest(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + id: RequestId + method: Annotated[ + Literal["plugin/share/checkout"], Field(title="Plugin/share/checkoutRequestMethod") + ] + params: PluginShareCheckoutParams + + class PluginShareDeleteRequest(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -5424,6 +5431,7 @@ class ConfigRequirements(BaseModel): model_config = ConfigDict( populate_by_name=True, ) + allow_managed_hooks_only: Annotated[bool | None, Field(alias="allowManagedHooksOnly")] = None allowed_approval_policies: Annotated[ list[AskForApproval] | None, Field(alias="allowedApprovalPolicies") ] = None @@ -5851,40 +5859,6 @@ class OverriddenMetadata(BaseModel): overriding_layer: Annotated[ConfigLayerMetadata, Field(alias="overridingLayer")] -class ExternalPermissionProfile(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - network: PermissionProfileNetworkPermissions - type: Annotated[Literal["external"], Field(title="ExternalPermissionProfileType")] - - -class RestrictedPermissionProfileFileSystemPermissions(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - entries: list[FileSystemSandboxEntry] - glob_scan_max_depth: Annotated[int | None, Field(alias="globScanMaxDepth", ge=1)] = None - type: Annotated[ - Literal["restricted"], Field(title="RestrictedPermissionProfileFileSystemPermissionsType") - ] - - -class PermissionProfileFileSystemPermissions( - RootModel[ - RestrictedPermissionProfileFileSystemPermissions - | UnrestrictedPermissionProfileFileSystemPermissions - ] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ( - RestrictedPermissionProfileFileSystemPermissions - | UnrestrictedPermissionProfileFileSystemPermissions - ) - - class PluginSharePrincipal(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -6626,7 +6600,6 @@ class ToolsV2(BaseModel): model_config = ConfigDict( populate_by_name=True, ) - view_image: bool | None = None web_search: WebSearchToolConfig | None = None @@ -7072,24 +7045,6 @@ class ListMcpServerStatusResponse(BaseModel): ] = None -class ManagedPermissionProfile(BaseModel): - model_config = ConfigDict( - populate_by_name=True, - ) - file_system: Annotated[PermissionProfileFileSystemPermissions, Field(alias="fileSystem")] - network: PermissionProfileNetworkPermissions - type: Annotated[Literal["managed"], Field(title="ManagedPermissionProfileType")] - - -class PermissionProfile( - RootModel[ManagedPermissionProfile | DisabledPermissionProfile | ExternalPermissionProfile] -): - model_config = ConfigDict( - populate_by_name=True, - ) - root: ManagedPermissionProfile | DisabledPermissionProfile | ExternalPermissionProfile - - class PluginShareContext(BaseModel): model_config = ConfigDict( populate_by_name=True, @@ -7098,6 +7053,13 @@ class PluginShareContext(BaseModel): creator_name: Annotated[str | None, Field(alias="creatorName")] = None discoverability: PluginShareDiscoverability | None = None remote_plugin_id: Annotated[str, Field(alias="remotePluginId")] + remote_version: Annotated[ + str | None, + Field( + alias="remoteVersion", + description="Version of the remote shared plugin release when available.", + ), + ] = None share_principals: Annotated[ list[PluginSharePrincipal] | None, Field(alias="sharePrincipals") ] = None @@ -7129,7 +7091,20 @@ class PluginSummary(BaseModel): installed: bool interface: PluginInterface | None = None keywords: list[str] | None = [] + local_version: Annotated[ + str | None, + Field( + alias="localVersion", + description="Version of the locally materialized plugin package when available.", + ), + ] = None name: str + remote_plugin_id: Annotated[ + str | None, + Field( + alias="remotePluginId", description="Backend remote plugin identifier when available." + ), + ] = None share_context: Annotated[ PluginShareContext | None, Field( @@ -7209,6 +7184,7 @@ class ResponseItem( | WebSearchCallResponseItem | ImageGenerationCallResponseItem | CompactionResponseItem + | CompactionTriggerResponseItem | ContextCompactionResponseItem | OtherResponseItem ] @@ -7229,6 +7205,7 @@ class ResponseItem( | WebSearchCallResponseItem | ImageGenerationCallResponseItem | CompactionResponseItem + | CompactionTriggerResponseItem | ContextCompactionResponseItem | OtherResponseItem ) @@ -7448,8 +7425,9 @@ class Config(BaseModel): ), ] = None compact_prompt: str | None = None + desktop: dict[str, Any] | None = None developer_instructions: str | None = None - forced_chatgpt_workspace_id: str | None = None + forced_chatgpt_workspace_id: ForcedChatgptWorkspaceIds | None = None forced_login_method: ForcedLoginMethod | None = None instructions: str | None = None model: str | None = None @@ -7827,7 +7805,7 @@ class ThreadForkResponse(BaseModel): sandbox: Annotated[ SandboxPolicy, Field( - description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `permissionProfile` when they need exact runtime permissions." + description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance." ), ] service_tier: Annotated[str | None, Field(alias="serviceTier")] = None @@ -7895,7 +7873,7 @@ class ThreadResumeResponse(BaseModel): sandbox: Annotated[ SandboxPolicy, Field( - description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `permissionProfile` when they need exact runtime permissions." + description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance." ), ] service_tier: Annotated[str | None, Field(alias="serviceTier")] = None @@ -7940,7 +7918,7 @@ class ThreadStartResponse(BaseModel): sandbox: Annotated[ SandboxPolicy, Field( - description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `permissionProfile` when they need exact runtime permissions." + description="Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance." ), ] service_tier: Annotated[str | None, Field(alias="serviceTier")] = None @@ -7998,11 +7976,13 @@ class ClientRequest( | MarketplaceRemoveRequest | MarketplaceUpgradeRequest | PluginListRequest + | PluginInstalledRequest | PluginReadRequest | PluginSkillReadRequest | PluginShareSaveRequest | PluginShareUpdateTargetsRequest | PluginShareListRequest + | PluginShareCheckoutRequest | PluginShareDeleteRequest | AppListRequest | FsReadFileRequest @@ -8079,11 +8059,13 @@ class ClientRequest( | MarketplaceRemoveRequest | MarketplaceUpgradeRequest | PluginListRequest + | PluginInstalledRequest | PluginReadRequest | PluginSkillReadRequest | PluginShareSaveRequest | PluginShareUpdateTargetsRequest | PluginShareListRequest + | PluginShareCheckoutRequest | PluginShareDeleteRequest | AppListRequest | FsReadFileRequest @@ -8135,6 +8117,16 @@ class ClientRequest( ] +class PluginInstalledResponse(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + ) + marketplace_load_errors: Annotated[ + list[MarketplaceLoadErrorInfo] | None, Field(alias="marketplaceLoadErrors") + ] = [] + marketplaces: list[PluginMarketplaceEntry] + + class PluginListResponse(BaseModel): model_config = ConfigDict( populate_by_name=True, diff --git a/sdk/python/tests/test_artifact_workflow_and_binaries.py b/sdk/python/tests/test_artifact_workflow_and_binaries.py index c7b5713ba1..d3f2f8d0ec 100644 --- a/sdk/python/tests/test_artifact_workflow_and_binaries.py +++ b/sdk/python/tests/test_artifact_workflow_and_binaries.py @@ -158,8 +158,8 @@ def test_schema_normalization_only_flattens_string_literal_oneofs( "AuthMode", "InputModality", "ExperimentalFeatureStage", - "CommandExecOutputStream", "ProcessOutputStream", + "CommandExecOutputStream", ] @@ -239,25 +239,53 @@ def test_runtime_distribution_name_is_consistent() -> None: ) -def test_source_sdk_package_pins_published_runtime() -> None: - """The source package metadata should pin the runtime wheel that ships schemas.""" +def test_source_sdk_template_pins_published_runtime() -> None: + """The source template should carry a development version and reviewed runtime pin.""" script = _load_update_script_module() pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) assert { - "sdk_version": pyproject["project"]["version"], + "sdk_template_version": pyproject["project"]["version"], "runtime_pin": script.pinned_runtime_version(), "dependencies": pyproject["project"]["dependencies"], } == { - "sdk_version": "0.131.0a4", - "runtime_pin": "0.131.0a4", + "sdk_template_version": "0.0.0-dev", + "runtime_pin": "0.132.0", "dependencies": [ "pydantic>=2.12", - "openai-codex-cli-bin==0.131.0a4", + "openai-codex-cli-bin==0.132.0", ], } +def test_source_sdk_package_declares_beta_documentation_and_release_files() -> None: + """Public package metadata should link beta docs and ship package metadata.""" + pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) + readme = (ROOT / "README.md").read_text() + + assert { + "description": pyproject["project"]["description"], + "is_beta": "Development Status :: 4 - Beta" in pyproject["project"]["classifiers"], + "license": pyproject["project"]["license"], + "documentation": pyproject["project"]["urls"]["Documentation"], + "sdist_include": pyproject["tool"]["hatch"]["build"]["targets"]["sdist"]["include"], + "readme_is_beta": "# OpenAI Codex Python SDK (Beta)" in readme, + "local_license_file": (ROOT / "LICENSE").exists(), + } == { + "description": "Python SDK for Codex", + "is_beta": True, + "license": "Apache-2.0", + "documentation": "https://github.com/openai/codex/tree/main/sdk/python/docs", + "sdist_include": [ + "src/openai_codex/**", + "README.md", + "pyproject.toml", + ], + "readme_is_beta": True, + "local_license_file": False, + } + + def test_release_metadata_retries_without_invalid_auth( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -284,19 +312,26 @@ def test_release_metadata_retries_without_invalid_auth( assert authorizations == ["Bearer invalid-token", None] -def test_runtime_setup_uses_pep440_package_version_and_codex_release_tags() -> None: - """The SDK uses PEP 440 package pins and converts only when fetching releases.""" +def test_runtime_setup_reads_independent_runtime_pin_and_release_tags() -> None: + """Runtime package pins remain independent of the SDK beta version.""" runtime_setup = _load_runtime_setup_module() pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) - assert runtime_setup.PACKAGE_NAME == "openai-codex-cli-bin" - assert runtime_setup.pinned_runtime_version() == pyproject["project"]["version"] - assert ( - f"{runtime_setup.PACKAGE_NAME}=={pyproject['project']['version']}" - in pyproject["project"]["dependencies"] - ) - assert runtime_setup._normalized_package_version("rust-v0.116.0-alpha.1") == "0.116.0a1" - assert runtime_setup._release_tag("0.116.0a1") == "rust-v0.116.0-alpha.1" + assert { + "package_name": runtime_setup.PACKAGE_NAME, + "sdk_template_version": pyproject["project"]["version"], + "runtime_pin": runtime_setup.pinned_runtime_version(), + "normalized_release_version": runtime_setup._normalized_package_version( + "rust-v0.116.0-alpha.1" + ), + "release_tag": runtime_setup._release_tag("0.116.0a1"), + } == { + "package_name": "openai-codex-cli-bin", + "sdk_template_version": "0.0.0-dev", + "runtime_pin": "0.132.0", + "normalized_release_version": "0.116.0a1", + "release_tag": "rust-v0.116.0-alpha.1", + } @pytest.mark.parametrize( @@ -491,23 +526,32 @@ def test_runtime_package_layout_is_included_by_wheel_config( ] -def test_stage_sdk_release_injects_exact_runtime_pin(tmp_path: Path) -> None: +def test_stage_sdk_release_preserves_reviewed_runtime_pin(tmp_path: Path) -> None: script = _load_update_script_module() staged = script.stage_python_sdk_package( tmp_path / "sdk-stage", - "rust-v0.116.0-alpha.1", + "0.1.0b1", ) - pyproject = (staged / "pyproject.toml").read_text() - assert 'name = "openai-codex"' in pyproject - assert 'version = "0.116.0a1"' in pyproject - assert '"openai-codex-cli-bin==0.116.0a1"' in pyproject + pyproject = tomllib.loads((staged / "pyproject.toml").read_text()) + assert { + "name": pyproject["project"]["name"], + "version": pyproject["project"]["version"], + "dependencies": pyproject["project"]["dependencies"], + } == { + "name": "openai-codex", + "version": "0.1.0b1", + "dependencies": [ + "pydantic>=2.12", + "openai-codex-cli-bin==0.132.0", + ], + } assert ( - '__version__ = "0.116.0a1"' + '__version__ = "0.1.0b1"' not in (staged / "src" / "openai_codex" / "__init__.py").read_text() ) assert ( - 'client_version: str = "0.116.0a1"' + 'client_version: str = "0.1.0b1"' not in (staged / "src" / "openai_codex" / "client.py").read_text() ) assert not any((staged / "src" / "openai_codex").glob("bin/**")) @@ -520,34 +564,41 @@ def test_stage_sdk_release_replaces_existing_staging_dir(tmp_path: Path) -> None old_file.parent.mkdir(parents=True) old_file.write_text("stale") - staged = script.stage_python_sdk_package(staging_dir, "0.116.0a1") + staged = script.stage_python_sdk_package(staging_dir, "0.1.0b1") assert staged == staging_dir assert not old_file.exists() -def test_staged_sdk_and_runtime_versions_match(tmp_path: Path) -> None: +def test_sdk_beta_release_can_pin_stable_runtime(tmp_path: Path) -> None: script = _load_update_script_module() package_archive = _write_fake_codex_package_archive(tmp_path, script) sdk_stage = script.stage_python_sdk_package( tmp_path / "sdk-stage", - "rust-v0.116.0-alpha.1", + "0.1.0b1", ) runtime_stage = script.stage_python_runtime_package( tmp_path / "runtime-stage", - "rust-v0.116.0-alpha.1", + "0.132.0", package_archive, ) sdk_pyproject = tomllib.loads((sdk_stage / "pyproject.toml").read_text()) runtime_pyproject = tomllib.loads((runtime_stage / "pyproject.toml").read_text()) - assert sdk_pyproject["project"]["version"] == runtime_pyproject["project"]["version"] - assert sdk_pyproject["project"]["dependencies"] == [ - "pydantic>=2.12", - "openai-codex-cli-bin==0.116.0a1", - ] + assert { + "sdk_version": sdk_pyproject["project"]["version"], + "runtime_version": runtime_pyproject["project"]["version"], + "sdk_dependencies": sdk_pyproject["project"]["dependencies"], + } == { + "sdk_version": "0.1.0b1", + "runtime_version": "0.132.0", + "sdk_dependencies": [ + "pydantic>=2.12", + "openai-codex-cli-bin==0.132.0", + ], + } def test_stage_sdk_runs_type_generation_before_staging(tmp_path: Path) -> None: @@ -557,16 +608,16 @@ def test_stage_sdk_runs_type_generation_before_staging(tmp_path: Path) -> None: [ "stage-sdk", str(tmp_path / "sdk-stage"), - "--codex-version", - "rust-v0.116.0-alpha.1", + "--sdk-version", + "0.1.0b1", ] ) def fake_generate_types() -> None: calls.append("generate_types") - def fake_stage_sdk_package(_staging_dir: Path, codex_version: str) -> Path: - calls.append(f"stage_sdk:{codex_version}") + def fake_stage_sdk_package(_staging_dir: Path, sdk_version: str) -> Path: + calls.append(f"stage_sdk:{sdk_version}") return tmp_path / "sdk-stage" def fake_stage_runtime_package( @@ -589,26 +640,7 @@ def test_stage_sdk_runs_type_generation_before_staging(tmp_path: Path) -> None: script.run_command(args, ops) - assert calls == ["generate_types", "stage_sdk:0.116.0a1"] - - -def test_stage_sdk_rejects_mismatched_legacy_versions(tmp_path: Path) -> None: - script = _load_update_script_module() - args = script.parse_args( - [ - "stage-sdk", - str(tmp_path / "sdk-stage"), - "--codex-version", - "0.116.0a1", - "--runtime-version", - "0.116.0a1", - "--sdk-version", - "0.115.0", - ] - ) - - with pytest.raises(RuntimeError, match="versions must match"): - script.run_command(args, script.default_cli_ops()) + assert calls == ["generate_types", "stage_sdk:0.1.0b1"] def test_stage_runtime_stages_package_without_type_generation(tmp_path: Path) -> None: diff --git a/sdk/python/tests/test_contract_generation.py b/sdk/python/tests/test_contract_generation.py index f809d05294..2c95d06a3e 100644 --- a/sdk/python/tests/test_contract_generation.py +++ b/sdk/python/tests/test_contract_generation.py @@ -40,7 +40,7 @@ def test_generated_files_are_up_to_date(): # Regenerate contract artifacts via the pinned runtime package, not a local # app-server binary from the checkout or CI environment. - assert importlib.metadata.version("openai-codex-cli-bin") == "0.131.0a4" + assert importlib.metadata.version("openai-codex-cli-bin") == "0.132.0" env = os.environ.copy() env.pop("CODEX_EXEC_PATH", None) python_bin = str(Path(sys.executable).parent) diff --git a/sdk/python/tests/test_public_api_signatures.py b/sdk/python/tests/test_public_api_signatures.py index 59e25dda24..c26ac90f6b 100644 --- a/sdk/python/tests/test_public_api_signatures.py +++ b/sdk/python/tests/test_public_api_signatures.py @@ -211,6 +211,30 @@ def test_package_and_default_client_versions_follow_project_version() -> None: assert CodexConfig().client_version == openai_codex.__version__ +def test_curated_public_api_has_builtin_help_documentation() -> None: + """The package's normal ``help()`` surface should explain common first-use APIs.""" + documented = { + "module": openai_codex, + "Codex": Codex, + "AsyncCodex": AsyncCodex, + "CodexConfig": CodexConfig, + "Thread": Thread, + "AsyncThread": AsyncThread, + "TurnHandle": TurnHandle, + "AsyncTurnHandle": AsyncTurnHandle, + "TurnResult": TurnResult, + "Sandbox": Sandbox, + "thread_start": Codex.thread_start, + "thread_resume": Codex.thread_resume, + "thread_run": Thread.run, + "thread_turn": Thread.turn, + } + + assert {name: inspect.getdoc(value) is not None for name, value in documented.items()} == ( + dict.fromkeys(documented, True) + ) + + def test_package_includes_py_typed_marker() -> None: """The wheel should advertise that inline type information is available.""" marker = resources.files("openai_codex").joinpath("py.typed") diff --git a/sdk/python/uv.lock b/sdk/python/uv.lock index d8d079e722..6d9e40e37a 100644 --- a/sdk/python/uv.lock +++ b/sdk/python/uv.lock @@ -2,6 +2,13 @@ version = 1 revision = 3 requires-python = ">=3.10" +[options] +exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. +exclude-newer-span = "P7D" + +[options.exclude-newer-package] +openai-codex-cli-bin = "2026-05-20T21:00:00Z" + [[package]] name = "annotated-types" version = "0.7.0" @@ -275,7 +282,7 @@ wheels = [ [[package]] name = "openai-codex" -version = "0.131.0a4" +version = "0.0.0.dev0" source = { editable = "." } dependencies = [ { name = "openai-codex-cli-bin" }, @@ -292,7 +299,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "datamodel-code-generator", marker = "extra == 'dev'", specifier = "==0.31.2" }, - { name = "openai-codex-cli-bin", specifier = "==0.131.0a4" }, + { name = "openai-codex-cli-bin", specifier = "==0.132.0" }, { name = "pydantic", specifier = ">=2.12" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15.8" }, @@ -301,15 +308,15 @@ provides-extras = ["dev"] [[package]] name = "openai-codex-cli-bin" -version = "0.131.0a4" +version = "0.132.0" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/9f/f9fc4bb1b2b7a20d4d65143ebb4c4dcd2301a718183b539ecb5b1c0ac3ec/openai_codex_cli_bin-0.131.0a4-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:db0f3cb7dda310641ac04fbaf3f128693a3817ab83ae59b67a3c9c74bd53f8b8", size = 88367585, upload-time = "2026-05-09T06:14:09.453Z" }, - { url = "https://files.pythonhosted.org/packages/dc/39/eb95ed0e8156669e895a192dec760be07dabe891c3c6340f7c6487b9a976/openai_codex_cli_bin-0.131.0a4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6cae5af6edca7f6d3f0bcbbd93cfc8a6dc3e33fb5955af21ae492b6d5d0dcb72", size = 79245567, upload-time = "2026-05-09T06:14:13.581Z" }, - { url = "https://files.pythonhosted.org/packages/0c/92/ade176fa78d746d5ff7a6e371d64740c0d95ab299b0dd58a5404b89b3915/openai_codex_cli_bin-0.131.0a4-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:5728f9887baf62d7e72f4f242093b3ff81e26c81d80d346fe1eef7eda6838aa8", size = 77758628, upload-time = "2026-05-09T06:14:18.374Z" }, - { url = "https://files.pythonhosted.org/packages/28/e6/bfe6c65f8e3e5499f71b24c3b6e8d07e4d426543d25e429b9b141b544e5f/openai_codex_cli_bin-0.131.0a4-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:d7a47fd3667fbcc216593839c202deffa056e9b3d46c6933e72594d461f4fea0", size = 84535509, upload-time = "2026-05-09T06:14:22.851Z" }, - { url = "https://files.pythonhosted.org/packages/bd/b7/53dc094a691ab6f2ca079e8e865b122843809ac4fad51cac4d59021e599d/openai_codex_cli_bin-0.131.0a4-py3-none-win_amd64.whl", hash = "sha256:c61bcf029672494c4c7fdc8567dbaa659a48bb75641d91c2ade27c1e46803434", size = 88185543, upload-time = "2026-05-09T06:14:27.282Z" }, - { url = "https://files.pythonhosted.org/packages/82/99/e0852ffcf9b4d2794fef83e0c3a267b3c773a776f136e9f7ce19f0c8df42/openai_codex_cli_bin-0.131.0a4-py3-none-win_arm64.whl", hash = "sha256:bbde750186861f102e346ac066f4e9608f515f7b71b16a6e8b7ef1ddc02a97a5", size = 81196380, upload-time = "2026-05-09T06:14:32.103Z" }, + { url = "https://files.pythonhosted.org/packages/be/a1/b92b7a1b73a83785d2e1dcd0faecd1b7f886a38cf02a30abe1c35f42f0f7/openai_codex_cli_bin-0.132.0-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:1c22b51dbd679413f84f00b9d8fd4e5cf8a1c0d1c7cc8c42bcb3f9f1b33e2334", size = 89403211, upload-time = "2026-05-20T02:37:22.311Z" }, + { url = "https://files.pythonhosted.org/packages/5f/68/163272e582de55a7f460e2329281267908d75d0fbcbbbb2c6749a6329e6b/openai_codex_cli_bin-0.132.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:56217495e6635c8a5d96df820cc0da5f46cd9b6ec6f3a5f67f1607d69ef74256", size = 79058685, upload-time = "2026-05-20T02:37:27.165Z" }, + { url = "https://files.pythonhosted.org/packages/0b/18/a60c6b137e7cd3959cae16ba757f57ca5702979b0ea107a21f516ba15d98/openai_codex_cli_bin-0.132.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:09642e7578a3078bfccc82af4077b085d42b0022b529e4b5c645e0a0af3397a4", size = 78689038, upload-time = "2026-05-20T02:37:31.548Z" }, + { url = "https://files.pythonhosted.org/packages/f8/eb/1b184307a67c1006d59b61636bcfcea73a89aa95271f6516ed28dce554ca/openai_codex_cli_bin-0.132.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:85aec095f9d144d7a2d1aff39fce77b7240f42014580c35801ba74b9317aa5f7", size = 85528820, upload-time = "2026-05-20T02:37:36.559Z" }, + { url = "https://files.pythonhosted.org/packages/0e/e8/1b823a8bf7b96d1513905ad79b16a146d797f81a19a6bc350a2f95a16661/openai_codex_cli_bin-0.132.0-py3-none-win_amd64.whl", hash = "sha256:3cb5c90c55baa39bd5ddc890d2068d3e1322a57a54d1d0e623819009a205c7f5", size = 86916218, upload-time = "2026-05-20T02:37:41.886Z" }, + { url = "https://files.pythonhosted.org/packages/6b/e6/bb8634bd4f3adaea299c95d7b03105ac417e32dd6d8bc2af5dda141d6f28/openai_codex_cli_bin-0.132.0-py3-none-win_arm64.whl", hash = "sha256:74ef93d3deef7cb83c71d19fc667defe749cdab337ec331f59a23511561b6f6a", size = 79892931, upload-time = "2026-05-20T02:37:46.828Z" }, ] [[package]]